Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions languages/golang/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit.
`[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to
one. `stashgen` does not yet map a Go type to it.

### Changed

- The doc comments on exported names in `encrypt`, `encrypt/eql`,
`encrypt/gensupport`, `auth`, and `stashgen` now say what each name does
and which errors it returns. The Rust crate and type names, the
engine's internal exports, and the storage format moved to ordinary code
comments. pkg.go.dev does not show those comments. Only comments changed.

## [0.1.0-rc.7] - 2026-11-25

### Upgrading from rc.6
Expand Down
4 changes: 2 additions & 2 deletions languages/golang/auth/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ var (
type Diagnostic = guest.Diagnostic

// Cause is one error in a [Diagnostic]'s cause chain: a Code and a Message.
// A cause from a library outside the stack crates has no Code, and its
// Message is a description the guest vouches for, never that library's own
// A cause from a library the SDK uses, outside its own code, has no Code.
// Its Message is a description the guest writes, never that library's own
// text.
type Cause = guest.Cause
2 changes: 1 addition & 1 deletion languages/golang/auth/oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
)

// OAuth2TokenSource adapts an existing x/oauth2 provider to OIDCProvider.
// Its AccessToken is read afresh whenever the Rust federation strategy asks.
// Its AccessToken is read again each time the federation strategy asks.
func OAuth2TokenSource(source oauth2.TokenSource) OIDCProvider {
return OIDCProviderFunc(func(context.Context) (string, error) {
if source == nil {
Expand Down
30 changes: 20 additions & 10 deletions languages/golang/auth/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,11 @@ type root struct {
cleanup runtime.Cleanup
}

// Resolve opens the profile directory the Rust crate would: CS_CONFIG_PATH
// when set and not blank, else ~/.cipherstash. The directory must exist;
// `stash auth login` creates it.
// Resolve opens the developer profile directory: CS_CONFIG_PATH when set
// and not blank, else ~/.cipherstash. The directory must exist;
// `stash auth login` creates it. A directory that cannot be found or
// opened, or is not a directory, is [ErrNoProfile]. So is a missing home
// directory when CS_CONFIG_PATH is unset.
func Resolve(ctx context.Context, opts ...Option) (*ProfileStore, error) {
// Blankness is tested on the trimmed value and the value itself is
// used, as ProfileStore::resolve does: a directory named with a space
Expand Down Expand Up @@ -123,9 +125,12 @@ func Open(ctx context.Context, dir string, opts ...Option) (*ProfileStore, error
// [ProfileStore.AccessKey] and [ProfileStore.OIDC] — where there is none to
// open: CI, a container, a server authenticating by federation. Every
// profile read on it fails with ErrNoProfile, and [ProfileStore.Auto] on it
// is the environment's access key or ErrNotAuthenticated, as stack-auth's
// AutoStrategy is with no profile store.
// is the environment's access key or ErrNotAuthenticated. Auto returns
// ErrConfig for an access key without CS_WORKSPACE_CRN, or for a
// CS_WORKSPACE_CRN that is not a CRN.
func OpenWithoutProfile(ctx context.Context, opts ...Option) (*ProfileStore, error) {
// Auto here behaves as stack-auth's AutoStrategy does with no profile
// store.
return open(ctx, "", opts)
}

Expand Down Expand Up @@ -367,12 +372,17 @@ func (s *ProfileStore) CurrentWorkspaceStore(ctx context.Context) (*ProfileStore
return s.WorkspaceStore(ctx, id)
}

// LockPath is the host path of the lock file the Rust crate takes for
// filename in this store: a sibling `.<filename>.lock`. Nothing is created
// or locked. DeviceSession holds this lock across the guest's refresh call;
// the guest cannot lock under WASI. This package never composes a profile
// path itself.
// LockPath is the host path of the lock file that guards filename in this
// store: a sibling `.<filename>.lock`. Nothing is created or locked.
// [ProfileStore.DeviceSession] holds this lock while it refreshes a token,
// and the CLI takes the same lock. A filename that is empty, "." or "..",
// or that contains `/` or `\`, is [ErrInvalidFilename], on every platform.
// So is a name whose lock file would not be directly in this store.
func (s *ProfileStore) LockPath(ctx context.Context, filename string) (string, error) {
// The lock file is the one the stack-profile crate takes. Go holds the
// lock across the guest's refresh call, because the guest cannot lock
// under WASI. This package never composes a profile path itself.
//
// The guest validates the filename as the crate does, against the
// guest's separator, which is `/`. The host's is checked here: on
// Windows a backslash passes the guest and would become a separator
Expand Down
29 changes: 20 additions & 9 deletions languages/golang/auth/strategy.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ func strategyConfig(opts []StrategyOption) strategyOptions {
return o
}

// Strategy is a Rust stack-auth strategy retained inside the credential
// guest: the source of the bearer token encrypt.NewCredentials takes.
// Strategy is an auth strategy held inside the credential guest: the
// source of the bearer token encrypt.NewCredentials takes.
// Close drops its cached credential; closing the parent profile closes all
// its strategies. It is the caller's to close: an encrypt client that
// was given it asks it for tokens but never closes it, so it must stay open
Expand Down Expand Up @@ -77,9 +77,12 @@ func (s *ProfileStore) newStrategy(ctx context.Context, config any, device bool)
return &Strategy{store: s, handle: string(out), device: device}, nil
}

// AccessKey constructs stack-auth's access-key strategy for crn. The key
// stays in the guest after construction; it is not sent on each Token call.
// AccessKey constructs the access-key strategy for the workspace crn: it
// exchanges key for a token. The key stays in the guest after
// construction; it is not sent on each Token call. An empty crn or key is
// [ErrConfig].
func (s *ProfileStore) AccessKey(ctx context.Context, crn, key string, opts ...StrategyOption) (*Strategy, error) {
// This is stack-auth's access-key strategy.
if crn == "" || key == "" {
return nil, ErrConfig
}
Expand All @@ -92,14 +95,15 @@ func (s *ProfileStore) AccessKey(ctx context.Context, crn, key string, opts ...S
}{"access_key", crn, key, o.baseURL}, false)
}

// OIDC constructs stack-auth's federation strategy. provider is called on
// OIDC constructs the OIDC federation strategy. provider is called on
// every Token call for the IdP JWT of the user that call is for; the
// strategy keeps one CTS token per distinct JWT and mints a new one only
// for a JWT that has no unexpired token. [WithCacheCapacity] sets how many
// JWTs that cache holds. crn names the workspace, and an empty crn is
// [ErrConfig]; [ProfileStore.OIDCWithDetectedWorkspace] finds the workspace
// instead.
func (s *ProfileStore) OIDC(ctx context.Context, crn string, provider OIDCProvider, opts ...StrategyOption) (*Strategy, error) {
// This is stack-auth's federation strategy.
if crn == "" || provider == nil {
return nil, ErrConfig
}
Expand Down Expand Up @@ -191,8 +195,8 @@ func (s *ProfileStore) detectWorkspaceCRN(ctx context.Context) (string, error) {
}

// DeviceSession uses this workspace store's auth.json. Fresh tokens are read
// without a lock. A refresh takes the same cross-process lock as the Rust
// CLI, then the guest re-reads and saves before the lock is released.
// without a lock. A refresh takes the same cross-process lock as the CLI,
// then the guest re-reads and saves before the lock is released.
func (s *ProfileStore) DeviceSession(ctx context.Context, opts ...StrategyOption) (*Strategy, error) {
if s.dir == guestRoot {
return nil, ErrConfig
Expand All @@ -205,9 +209,16 @@ func (s *ProfileStore) DeviceSession(ctx context.Context, opts ...StrategyOption
}{"device_session", s.dir, o.baseURL}, true)
}

// Auto follows stack-auth's detection order against the Go host's
// environment: access key first, then the current workspace's device token.
// Auto picks a strategy from the environment and the profile. When
// CS_CLIENT_ACCESS_KEY is set, it is [ProfileStore.AccessKey] for the
// workspace CS_WORKSPACE_CRN names. Otherwise it is
// [ProfileStore.DeviceSession] for the current workspace's saved token.
// An access key without CS_WORKSPACE_CRN is [ErrConfig], and so is a
// CS_WORKSPACE_CRN that is set but is not a CRN, with or without an access
// key. No current workspace, or no saved token, is [ErrNotAuthenticated].
func (s *ProfileStore) Auto(ctx context.Context, opts ...StrategyOption) (*Strategy, error) {
// The order is stack-auth's AutoStrategy order, read from the Go host's
// environment because the guest has none.
crn, crnSet := os.LookupEnv("CS_WORKSPACE_CRN")
if crnSet {
_, err := s.callArgs(ctx, func(i *instance) api.Function { return i.authValidateCRN }, guest.BufArg([]byte(crn)))
Expand Down
11 changes: 7 additions & 4 deletions languages/golang/auth/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
)

// Token is the stored access token, as auth.json holds it and
// [ProfileStore.Token] reads it through the Rust crate's own type. The
// refresh token is not in it: the guest handles refresh through a Strategy.
// [ProfileStore.Token] reads it. The refresh token is not in it: a
// [Strategy] refreshes the token.
type Token struct {
// AccessToken is the bearer credential.
AccessToken string
Expand All @@ -30,9 +30,12 @@ type Token struct {
DeviceInstanceID string
}

// For contributors: Usable is the stack-auth crate's is_usable, not its
// is_expired, which subtracts a refresh-ahead margin that belongs to
// refreshing.

// Usable reports whether the token is still usable at now: before its real
// expiry. The Rust crate's is_usable, not its is_expired, which subtracts a
// refresh-ahead margin that belongs to refreshing.
// expiry. It subtracts no margin for an early refresh.
func (t Token) Usable(now time.Time) bool { return now.Before(t.ExpiresAt) }

// Token reads auth.json in this store (a workspace store; the root holds
Expand Down
2 changes: 1 addition & 1 deletion languages/golang/auth/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
)

// OIDCProvider supplies the identity-provider JWT of the user a call is
// for. The Rust federation strategy asks on every Strategy.Token call: the
// for. The federation strategy asks on every Strategy.Token call: the
// JWT is how it tells one user from another, and it keeps one CTS token per
// distinct JWT, exchanging a JWT only when it has no unexpired CTS token.
// So a server that serves many users through one client must return the
Expand Down
7 changes: 4 additions & 3 deletions languages/golang/encrypt/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import (
"github.com/cipherstash/stack/languages/golang/internal/record"
)

// For contributors: AuditMetadata is the Rust crate's AuditMetadata, and
// the unverified context of the ZeroKMS protocol.

// AuditMetadata is facts about a call that ZeroKMS writes to its audit log.
//
// Every Encrypt and Decrypt asks ZeroKMS for data keys. ZeroKMS logs each
Expand All @@ -28,9 +31,7 @@ import (
// Text("request_id", requestID)
// people, err := users.Decrypt(ctx, cipher.Audit(metadata), rows)
//
// Audit metadata is optional. A cipher without it sends none. It is the
// Rust crate's AuditMetadata, and the unverified context of the ZeroKMS
// protocol.
// Audit metadata is optional. A cipher without it sends none.
//
// # Rules
//
Expand Down
15 changes: 8 additions & 7 deletions languages/golang/encrypt/cipher.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ func (cph *Cipher) Client() *Client { return cph.client }
// Keyset is the selector this cipher is bound to.
func (cph *Cipher) Keyset() KeysetSelector { return cph.keyset }

// KeysetID resolves the cipher's keyset to its id: Rust's
// KeysetCipher::keyset_id, and in Go the one explicit resolution point,
// since a Cipher is made without a request. The first use of a name or id
// on the client is one ZeroKMS round trip, later uses come from the
// guest's cache; the default keyset never makes a request. Use it at boot
// to validate a tenant's keyset and learn its id.
// KeysetID resolves the cipher's keyset to its id. Making a Cipher sends no
// request, so this is the one call that resolves a keyset on its own. The
// first use of a name or id on the client is one ZeroKMS round trip, later
// uses come from the guest's cache; the default keyset never makes a
// request. Use it at boot to validate a tenant's keyset and learn its id.
func (cph *Cipher) KeysetID(ctx context.Context) (KeysetID, error) {
// Rust's KeysetCipher::keyset_id.
return cph.client.resolveKeyset(ctx, cph.keyset)
}

Expand Down Expand Up @@ -158,7 +158,7 @@ func ownedParts(parts []any) []any {

// Context returns a cipher that names the context every row through it is
// under, for a type whose context is one of its own fields (a field tagged
// `context_field`): the Rust chain's `.context(..)`. Through such a cipher,
// `context_field`). Through such a cipher,
// Decrypt checks each row's stored context field against the label before
// any key is retrieved and refuses a row that names another with
// [ErrContextMismatch]; Encrypt refuses a value whose context field says
Expand All @@ -171,6 +171,7 @@ func ownedParts(parts []any) []any {
// The label is segments separated by '/', such as "tenants/acme"; one that
// is not a plain label is reported by the first call, as ErrEncoding.
func (cph *Cipher) Context(label string) *Cipher {
// The Rust chain's `.context(..)`.
next := cph.copy()
next.context = label
if _, err := record.ParseContext(label); err != nil && next.err == nil {
Expand Down
38 changes: 22 additions & 16 deletions languages/golang/encrypt/ciphertext.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,30 @@ import (
"github.com/cipherstash/vitaminc/bindings/go/vcffi"
)

// Ciphertext is one sealed field as a database column holds it: the frozen
// stack-encrypt leaf encoding (version, keyset id, IV, ZeroKMS tag,
// ciphertext). A generated type holds one for each field sealed in separate
// columns, beside that field's terms. It is a distinct type from vitaminc's
// own leaf on purpose: a stack-encrypt leaf is not decryptable by
// vitaminc-encrypt and must never scan or marshal where one belongs.
// For contributors: a Ciphertext is the frozen stack-encrypt leaf encoding
// (version, keyset id, IV, ZeroKMS tag, ciphertext). It is a distinct type
// from vitaminc's own leaf on purpose: a stack-encrypt leaf is not
// decryptable by vitaminc-encrypt and must never scan or marshal where one
// belongs. A sealed field seals as vitaminc's tagged leaf, which a Rust
// record opens when its field is a Value (not a bare u32 or String). An
// opaque struct crosses the binding as one storage blob and is one leaf.

// Ciphertext is one sealed field as a database column holds it. The bytes
// are a fixed encoding that later releases still read; treat them as
// opaque. A generated type holds one for each field sealed in separate
// columns, beside that field's terms.
//
// A sealed field is one scalar — a string, a number, a bool or a []byte, or
// a type defined over one, or a pointer to either, whose nil is sealed as a
// null as long as a value or stored as SQL NULL — and seals as vitaminc's
// tagged leaf, which a
// Rust record opens when its field is a Value (not a bare u32 or String). A
// struct, slice or map is not a Ciphertext field. It seals as part of an
// opaque struct, which crosses as one storage blob and is one leaf, or as a
// JSON document in a field that names an EQL type which holds one
// (encrypt_into=Json or encrypt_into=JsonSearch). stashgen refuses it
// anywhere else, because the engine would seal it as a tree of leaves and a
// column holds one.
// a type defined over one, or a pointer to either. A nil pointer is sealed
// as a null the same length as a value. With the `null=sql` tag it is
// stored as SQL NULL instead, and stashgen requires that tag for a type of
// variable width or a field with an index other than equality. A struct,
// slice or map is
// not a Ciphertext field. It seals as part of an opaque struct, which is
// stored as one value in one column, or as a JSON document in a field that
// names an EQL type which holds one (encrypt_into=Json or
// encrypt_into=JsonSearch). stashgen refuses it anywhere else, because the
// engine would seal it as many values and a column holds one.
type Ciphertext []byte

// Value implements driver.Valuer, binding the leaf as a byte column.
Expand Down
23 changes: 13 additions & 10 deletions languages/golang/encrypt/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -445,26 +445,29 @@ func (c *Client) release() error {
return err
}

// Keyset binds the client to one keyset, by name or by id: Rust's
// StackCipher::keyset. No request is made here — Go has no await, so the
// keyset is resolved by the guest on the cipher's first use (and cached),
// Keyset binds the client to one keyset, by name or by id. No request is
// made here: the keyset is resolved on the cipher's first use, and cached,
// which makes a Cipher cheap to make per call, per tenant or per request.
// [Cipher.KeysetID] is the explicit resolution point. A nil selector gives a
// cipher whose every call fails with [ErrEncoding]; the default keyset is
// [Client.DefaultKeyset].
// [Cipher.KeysetID] resolves it on its own. A nil selector gives a cipher
// whose encrypt, decrypt and query calls fail with [ErrEncoding]. Its
// KeysetID does not fail: it returns the default keyset's id. The default
// keyset is [Client.DefaultKeyset].
func (c *Client) Keyset(sel KeysetSelector) *Cipher {
// Rust's StackCipher::keyset. Go has no await, so the guest resolves
// the keyset on the cipher's first use.
if sel == nil {
return &Cipher{client: c, keyset: defaultKeyset{}, err: fmt.Errorf("%w: Client.Keyset(nil); the default keyset is Client.DefaultKeyset", ErrEncoding)}
}
return &Cipher{client: c, keyset: sel}
}

// For contributors: DefaultKeyset is Rust's StackCipher::default_keyset.

// DefaultKeyset binds the client to its default keyset — the one a ZeroKMS
// administrator set for this client, which is what naming no keyset
// resolves to: Rust's StackCipher::default_keyset. Loaded at NewClient, so
// using it never touches ZeroKMS. There is no way to redefine it from here;
// which keyset is the default is the server's to say. Any other keyset is
// [Client.Keyset].
// resolves to. Loaded at NewClient, so using it never touches ZeroKMS.
// There is no way to redefine it from here; which keyset is the default is
// the server's to say. Any other keyset is [Client.Keyset].
func (c *Client) DefaultKeyset() *Cipher { return &Cipher{client: c, keyset: defaultKeyset{}} }

// resolveKeyset asks the guest for a selector's keyset id: the first use
Expand Down
Loading
Loading