Repository navigation
feat(stack-encrypt)!: attach a credential to a call, and load a keyset when a call needs it - #1709
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
🦋 Changeset detectedLatest commit: 0156249 The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Mutation testing (cargo-mutants,
|
| caught | missed | unviable | timeout |
|---|---|---|---|
| 75 | 0 | 186 | 0 |
Every mutant in the changed lines was caught by a test.
9ed27a3 to
526879c
Compare
|
Rebased onto
The description has the details under "Rebase onto |
526879c to
dfd402f
Compare
|
Force-pushed a redesign, as one commit (
The description is rewritten for this version. See "How this PR got here" and "Review notes". |
dfd402f to
2f1c781
Compare
|
Force-pushed another redesign, as one commit (
The description is rewritten for this version. See "How the deferred load works" and "Review notes". |
2f1c781 to
574ddf0
Compare
|
Pushed
The description has a new "Sibling pull requests" section on #1725, #1726, #1727 and #1729. |
adc8d82 to
eabbdf2
Compare
|
Force-pushed
One thing goes further than the review asked. A JSON read through a keyset that is not loaded could not be merged, and failed with Each inline comment has a reply. The description is rewritten for this version. |
b09754a to
7d3a79d
Compare
3d55934 to
7b86835
Compare
47b2cc3 to
3990804
Compare
…tialAuthStrategy` A server that serves many users through one `OidcFederationStrategy` had one way to say whose JWT a call was for: a provider callback that reads a task-local variable. The call itself could not carry the JWT. A strategy is now one of two kinds. `AuthStrategy` has an identity of its own, and `get_token()` asks for nothing. `CredentialAuthStrategy` takes a credential with each call: `get_token_with_credential(credential)`. `OidcFederationStrategy::credential_per_call(crn)` builds the second kind. It has no provider callback (`CredentialPerCall` stands where one would be) and no `get_token`, so a call that brings no JWT does not compile. Both kinds share one exchange and one per-JWT token cache. An OIDC strategy has one source for the JWT of a call. Built with a provider, it asks the provider, and has no method that takes a JWT from its caller: `get_token_for_jwt` is private. That method was added for the language bindings in 0.44.0, which is not released. The Node and wasm bindings now build a `credential_per_call` strategy and keep the `getJwt` callback themselves, so the JavaScript API is unchanged. `StrategyKind` stops a type from being both kinds. Every `AuthStrategy` has `Kind = OwnIdentity` from a blanket impl, and `CredentialAuthStrategy` requires `Kind = CredentialPerCall`. A type that implements both strategy traits has two impls of `StrategyKind`, which is E0119. Stack KMS and Stack Encrypt build on these two traits, so the rule about who supplies the JWT is held here and not checked again above. Refs #1708.
…lKeySource` ZeroKMS serves and logs a key request as whoever its token names. A `StackKms` could only make requests as its own auth strategy, so a server could not make one as the end user of the request it was handling. A key source is now one of two kinds, following the two kinds of strategy in stack-auth. `DataKeySource` and `IndexKeySource` are a key source with an identity of its own. `CredentialKeySource` makes each request with a credential handed in with the call, and has no request without one. `StackKms` is the first kind over a `stack_auth::AuthStrategy`, as before. Over a `stack_auth::CredentialAuthStrategy` it is the second kind, with `generate_keys_with_credential`, `retrieve_keys_with_credential` and `load_keyset_with_credential`. The builder and `StackKms::connect` accept both kinds of strategy. `FakeCredentialKeySource` (behind `test-support`) is the test double of the second kind. It records the credential of each request. Refs #1708.
…t when a call needs it A Rust server that decrypts as the end user who signed in had to build its cipher inside the first request, because `init` loaded the default keyset and that takes a token. It also had to pass each user's JWT to the auth strategy through a task-local variable. A call now takes its credential itself, last, as it takes audit metadata: `keyset.decrypt(stored).with_credential(jwt).await`. Every request the call makes is made with that credential: its key requests, and the load of a keyset it needs. A key source is one of two kinds (`KeySource<I>`), and the types tell them apart. Through a key source that takes a credential with each call (`kms::CredentialKeySource`), a call is not a future until it has one, so a handler that forgets `.with_credential(..)` does not compile. Through a key source with an identity of its own, a call is awaited as it is and has no `.with_credential(..)`, so a credential is never taken and ignored. `init` is one call for both kinds. With an identity of its own it loads the default keyset, as before. With a credential per call it has no credential, so it makes no request, and the server builds its cipher at startup. A keyset handle may therefore be on a keyset that is not loaded yet. `default_keyset()` and `keyset(..)` make no request. A call built through such a handle records the keyset it works under (`KeysetSelector`), asks for the keyset's state as a request where it needs the id or the index key, and does that part of its work when the answer arrives. Awaiting the call loads the keyset once, with the credential of the call, and the handle keeps it. Calls built through one handle run under one keyset. A call loads the keyset it works under and no other. A call on a loaded keyset runs the code it ran before. The JSON queries, typed and `dynamic`, derive their operands the same way through a keyset that is not loaded. A `dynamic` JSON read builds its key requests from a key derived under the keyset, so it is built when it is awaited (`Pending::after_load`). Breaking: - `StackCipher::keyset(..)` is not `async` and returns the handle. - `KeysetCipher::keyset_id()` and `keyset_name()` return a `Pending`, and `with_prf(..)` replaces `prf()`. - `CipherRef` is `Clone` and no longer `Copy`. - `StackCipherBuilder::kms(source)` returns a builder in its own state, `WithKeySource<K>`. The Go guest reads a keyset's id where it selects the keyset, so a keyset that ZeroKMS does not know still fails the call that named it. Closes #1708.
3990804 to
0156249
Compare
Summary
Stack Encrypt, the Rust crate that encrypts and decrypts values, asks ZeroKMS (the CipherStash key service) for a data key on every call. Each request carries a token, and ZeroKMS serves and logs the request as whoever the token names. A web server often wants that to be the end user who signed in, so it exchanges the user's JWT (a signed login token from Supabase Auth, Clerk and so on) for a token naming that user.
Until now a Rust server doing that had to work around the crate twice. It had to build its cipher inside the first request, because building one needs a token and at startup there is no user. And it had to put each user's JWT in a task-local variable for a callback to find, because a call could not say whose JWT to use.
This PR removes both. The server builds its cipher at startup with the same
initevery program uses, and each request handler attaches its own credential to the call:The method is
with_credential, notas_user, because the credential is not always a user's: it can be a service's or a job's.A handler cannot forget the credential. On this cipher,
keyset.decrypt(stored).awaitdoes not compile. Onlykeyset.decrypt(stored).with_credential(..).awaitdoes. On a cipher with an identity of its own, such as one over an access key, it is the other way round: a call is awaited as it is, and.with_credential(..)does not compile. So a credential is never forgotten and never ignored.Four breaking changes to the released
stack-encrypt:StackCipher::keyset(..)is no longerasync. It returns the keyset handle, not aResult, and makes no request.KeysetCipher::keyset_id()andkeyset_name()return aPending, so.await?them.with_prf(..)replacesprf().CipherRefisCloneand no longerCopy.StackCipher::builder().kms(source)returns aStackCipherBuilder<WithKeySource<K>>, where it returned aStackCipherBuilder<K>. Code that chains.kms(..).init()is unchanged.default_keyset()does not change.Rebased onto #1687
This PR was stacked on #1687. #1687 and the four PRs below it (#1613, #1659, #1664 and #1666) are now merged into
next, so this PR's base isnext, and it sits on top of the merge commit of #1687. The diff shown here is this PR's change alone.#1666 removes the plan chain (
cipher.encrypt(..).using(..),all(..),PlanKms), and #1687 moves the JSON query code. Replaying the twelve old commits one by one would have resolved the same conflicts three times, against designs that later commits replaced. So the end state of the old branch was merged onto #1687 once, and laid down as three commits, one for each crate. Each one builds and passes its tests alone:feat(stack-auth)!: the two kinds of strategy,credential_per_call,StrategyKind, and the Node and wasm bindings.feat(stack-kms):CredentialKeySourceandStackKmsover both kinds of strategy.feat(stack-encrypt)!:.with_credential(..),KeySource<I>, and the deferred keyset load. It also has the Go guest and the EQL test change.The old history is not lost: its head is
b09754ab3, and the hashes in the next section are from it.What the rebase changed in the code:
plan/chain.rs,PlanKms<I>, and two helpers only the chain called. That is about 200 lines. Every call is now aPending, soPending::with_credentialis the one place a credential is attached.json/inputs.rs). So the typed JSON queries that feat(stack-encrypt,eql-bindings): typed JSON queries from a field reference #1687 adds work through a keyset that is not loaded yet, as thedynamicones do. Two new tests intests/credential.rscheck that.encrypt_into,decrypt_from), field reference queries andzip: ten tests intests/credential.rs, and the chain and batch cases of the two compile tests. Nothing else in a test changed but call sites.credential.rs. APendinghas noDebug, and the chain, which had one, is gone.Rebased again, onto #1687 at
382c907db#1687 was itself rebased onto
nextand gained six commits. The three commits of this PR were replayed on top. stack-auth, stack-kms and the two bindings are the same files as before. Two things changed in stack-encrypt:zipandPending::allwipe it when a later operation of the same call fails. This PR builds some calls only when they are awaited, after the keyset is loaded (Pending::after_load). The two met intarget/pending.rs, the one conflict of this rebase. A call that is not built yet is now marked when it is built, and a merged call keeps each side's mark until then. A new unit test,a_pending_built_after_the_load_is_wiped_when_a_later_one_fails, checks a pair and a column, and checks that a call with no mark is not wiped.ordered = { "$.age": u32, .. }on the field,at().age(),elements().visits().place(), and.var("min", 30). What they assert is unchanged.What changed since the last review
Eight changes, on top of the version that was reviewed (
eabbdf2d6). Each was one commit before the rebase.1. A forgotten
.with_credential(..)is a compile error (1fcc508b5).Before, a call that forgot its credential was caught late or not at all:
credential_per_call, it failed when it ran, with a missing-credential error.Now a key source is one of two kinds, and never both:
call.awaitcall.with_credential(..).awaitOidcFederationStrategy::credential_per_call(crn)What follows from that:
.with_credential(..). It has one source for the caller's JWT, its callback. This is a change from the reviewed version, where it took both.AuthError::MissingCredential,kms::Error::missing_credential()andis_missing_credential().initno longer asks a key source for a keyset to find out that it has no identity. It knows from the type. For a key source that takes a credential with each call,initmakes no request at all.FakeDataKeySourceis as it was before this PR.FakeCredentialKeySourceis the one that takes and records a credential.FakeDataKeySource::without_identity()is gone.2. Calls built through one keyset handle run under one keyset (
e7b24327b). A code review of this PR found a bug in the reviewed version. A call built before its handle's keyset was loaded resolved the handle's name again when it was awaited. If the name had come to mean another keyset in between, the call minted its data key under the new keyset and named the old one in the value it stored. That value could not be decrypted. Now the first such call to be awaited loads the keyset, and every other call through that handle uses it.3. Docs (
1db716ae7). Three passages said that a user without a grant on a keyset could still make its query terms. That was wrong: ZeroKMS grants a keyset to a client, not to a user, and a cipher has one client. The passages now say what the shared index key does change, which is the ZeroKMS log. Two of the three came from #1701. Thestack-kmsandstack-authchangelogs now list what this PR adds to them.4. Two assertions the mutation gate asked for (
d848a73b5). The gate changes a line and checks that a test fails. On the first CI run, two changes to the code of item 2 went unnoticed. A new handle on a keyset the cipher had already loaded could start as not loaded. The debug output of a keyset selection that is not loaded could print nothing. One unit test intarget/pending.rsnow checks both. Each change, applied by hand, makes it fail. Tests only.5. A call loads the keyset it works under, and no other (
c60477971). With a key source that takes a credential with each call, the first call on a keyset selected by id or by name loaded two keysets: the default keyset, then the one it asked for. Both went out with that caller's credential. The cause: the cipher created its cache of selected keysets together with the default keyset, so every other load waited for the default one. The cache is now created with the cipher. A call on a tenant's keyset makes one load, of that keyset. The first call on the default keyset loads the default keyset. A cipher with an identity of its own is unchanged:initloads its default keyset before any call.6. A test of what compiles over each kind of OIDC strategy (
809b9308f). The compile-fail tests already checked that.with_credential(..)does not compile on a call through an OIDC strategy with a provider callback. Nothing checked the other half: that such a call is awaited with no credential.tests/ui/pass/oidc_strategies.rsnow compiles a single call, an audited call, a value sealed under a context and a zipped call over a strategy with a provider, each with no credential. It compiles the same four over acredential_per_callstrategy, each with a credential. Tests only.7. stack-auth holds the rule about who supplies the JWT (
43b9f5c8d). An OIDC strategy has one source for the JWT of a call: its provider callback, or the call. The two strategy traits said so, but stack-auth had one public method that went round them.get_token_for_jwttook a JWT from the caller on either kind of strategy, so a strategy with a provider could be handed one. That method is now private. Stack KMS and Stack Encrypt get the rule from stack-auth's two traits, and add no check of their own.The method was public for the Node and wasm bindings (
@cipherstash/auth). They now build the Rust strategy withcredential_per_calland keep thegetJwtcallback themselves.getTokenasks the callback and passes the JWT on.getTokenForJwtpasses on the JWT it was given. The JavaScript API is unchanged, and both entries still share one token cache.get_token_for_jwtwas added in stack-auth 0.44.0, which is not released, so no released version loses a method.8. A strategy type cannot be both kinds (
b09754ab3). A strategy makes every request as itself (AuthStrategy), or as the caller whose credential comes with the call (CredentialAuthStrategy). The docs said a type implements one and never both. For a strategy written outside stack-auth, nothing checked that. stack-auth now hasStrategyKind, with one associated type,Kind:AuthStrategyhasKind = OwnIdentity, from a blanket impl. An existing strategy needs no change.CredentialAuthStrategyrequiresKind = CredentialPerCall. A strategy that implements it writes one more impl:impl StrategyKind for &Mine { type Kind = CredentialPerCall; }.E0119).OwnIdentitymoves from stack-encrypt to stack-auth. stack-kms re-exports it, andstack_encrypt::OwnIdentityis that re-export.The earlier rework, still in this PR
.with_credential(..)returns aWithCredential, which can be awaited, or audited and then awaited, and nothing else. So one call has one credential, and two credentials never meet.CredentialCipher,StackCipher::with_credentialandError::CredentialMismatchare gone.keyset(..)stops beingasync.Error::KeysetNotLoadedis gone.NoProviderisCredentialPerCall, andOidcFederationStrategy::credential_per_call(crn)builds the strategy, so a caller rarely writes the type.LimitisKeysetSelector. "Scope" names only a part of a context: parameters that hold aCipherRefarecipher_ref.Merging two keysets is still checked (
Error::KeysetMismatch, which is onnext). That check cannot be removed by design:a.zip(b)is one request for data keys under one keyset, and two tenants' calls can be zipped by mistake.New public names
KeySource<I>(stack-encrypt): the sealed trait implemented for both kinds of key source.Iis what a request is made as.OwnIdentity(stack-auth, re-exported by stack-kms and stack-encrypt): the identity of a strategy, or of a key source, that has one of its own. In stack-encrypt it is theIof such a key source; the otherIisSecretToken.StrategyKind(stack-auth): which of the two kinds a strategy is. ItsKindisOwnIdentityorCredentialPerCall.WithKeySource<K>(stack-encrypt): the builder's state after.kms(source), beside the existingWithAuthStrategy.FakeCredentialKeySource(stack-kms, behindtest-support).initis declaredinit<I>(self) where K: KeySource<I>. Nobody writesI: the compiler works it out from the key source. It is there because oneinithas to serve both kinds, and Rust cannot otherwise tell two blanket impls apart.Changes
stack-encrypt
Pendinghas.with_credential(credential), and every call is aPending. It goes in either order with.audit(..). Every request the awaited call makes is made with the credential: its key requests, and the load of a keyset it needs.kms::CredentialKeySource) is not a future until.with_credential(..). A call through a key source with an identity of its own has no.with_credential(..). Both mistakes are compile errors.KeySource<I>is implemented for both kinds. The code that settles a call is generic overI, where it took an optional credential.initis one call for every auth strategy. With an access key or a saved login it loads the client's default keyset (the group of keys it encrypts under by default), as before, so bad credentials still fail at startup. With a key source that takes a credential with each call, it makes no request and returns the cipher with no keyset loaded.default_keyset()andkeyset(..)make no request. A handle is on a keyset that is loaded, or on one that is not loaded yet. Every call on it works either way. The first call that is awaited loads the keyset, and the handle keeps it from then on. A call loads the keyset it works under, and no other. Callers that arrive together make one load of the default keyset between them. A load that fails leaves the cipher as it was, and the next call tries again.StackCipher::keyset(..)returns the handle. A keyset that ZeroKMS does not know now fails the first call on the handle, with the same error. To fail where it is selected, awaitkeyset.keyset_id()there.keyset_id()andkeyset_name()return aPending, andwith_prf(..)replacesprf(), because a handle on a keyset that is not loaded loads it there. On a loaded keyset they make no request.CipherRefisClone, notCopy, because a reference to a keyset selected by name keeps the name..kms(source)returns a builder in its own state,WithKeySource<K>, so that each builder state has oneinit.dynamic(the API the language bindings use), and thedynamicreads work through a keyset that is not loaded. A query operand is derived when it is awaited. A read (json_open) is built when it is awaited, and merges with other calls.dispatch, the function that makes the requests.stack-kms
CredentialKeySource: a key source that makes each request with a credential. It does not haveDataKeySourceandIndexKeySourceas supertraits, so it has no request without one.StackKmshas the plain requests over astack_auth::AuthStrategy, andgenerate_keys_with_credential,retrieve_keys_with_credentialandload_keyset_with_credentialover astack_auth::CredentialAuthStrategy.StackKmsBuilderandStackKms::connectaccept both.FakeCredentialKeySource, the test double of aCredentialKeySource. It records each credential (credentials_seen()). A test of a request handler built on it does not compile if the handler forgets its caller's credential.SecretToken, the type of a credential.stack-auth
CredentialAuthStrategy::get_token_with_credential. A strategy implements it orAuthStrategy, never both:StrategyKindmakes a type that implements both a compile error.OidcFederationStrategy::credential_per_call(crn): a strategy with no provider callback. It implementsCredentialAuthStrategy, and has noget_token.CredentialPerCallstands where its provider would be. One long-lived strategy still serves every caller, with its per-JWT token cache.OidcFederationStrategybuilt with a provider implementsAuthStrategyonly. It has no method that takes a JWT from its caller:get_token_for_jwt, which the unreleased 0.44.0 had for the language bindings, is private.Node and wasm bindings (
@cipherstash/auth)credential_per_call, and the binding keeps thegetJwtcallback. The JavaScript API is unchanged.Go guest
scope_foriscipher_ref_for. Its interface to Go is the same.Docs
CONTEXT.md(Credential, Cipher reference), a section in the crate docs, and a changeset for@cipherstash/auth, which CI requires for anystack-authchange. The JavaScript API is unchanged.How the deferred load works
A keyset handle used to always hold a loaded keyset: its id and its index key (the key search terms are derived from). Three things read those while a call is built, before anything is awaited: the id stamped on each sealed value, the search terms, and the checks that refuse mixing two keysets.
Now a handle may hold nothing yet. A call built through it:
KeysetSelector::not_loadedintarget/pending.rs): the default keyset, or the id or name it was selected by;Request::selected_keyset()), and does that part of its work when the answer arrives. This is how a JSON document already asks for a keyset it names.Awaiting the call (
Pending::settle_with, thenresolved) loads the keyset once, with the credential of the call, turns those requests into requests for that keyset by id, and applies the keyset checks that the build could not. The handle and every call built through it share one slot for the loaded keyset. The first call to be awaited fills it, and the others read it.One call cannot work that way. A JSON read (
dynamic::json_open) opens its rows with a key derived under the keyset, and builds its key requests from that key. So with the keyset not loaded it has no requests to list. For that call,Pending::after_loadholds a closure. Awaiting the pending loads the keyset, runs the closure with a handle on the loaded keyset, and settles the pending it returns. Merging such a pending makes another one of the same kind: it is built, and then merged, when it settles.A call on a loaded keyset runs the code it ran before. Each place that reads the keyset branches on whether it is loaded, and the loaded branch is the old code. That matters for the tests that watch freed memory for plaintext.
Verification
The head is
01562493e, onnextatd7c215097, the merge commit of #1687. The numbers below are from the push before it,39908044b, which sat on #1687's last commit (fa2a15849). Merging #1687 changed no file ofnextbeyond that commit, so every file at01562493eis the same as at39908044b:git diffbetween the two is empty. The local runs were not repeated. For CI on the head, read the checks on this PR.CI passed on
39908044b: 61 checks passed, 2 skipped (the automated review job, which is switched off in this repository, and the nightly fuzz campaign, which does not run on a pull request). That includes the mutation gate on every line this PR changes, the Go test suite on Linux, macOS and Windows, and the EQL tests that need PostgreSQL. The latest push brought in one commit of #1687, which changes the text of one compiler note, one compile-fail test and one test of the JSONPath crate. The rebase onto it had no conflicts.Local runs on
39908044b:cargo nextest run -p stack-auth -p stack-kms -p stack-encrypt -p stack-encrypt-derive -p stack-encrypt-jsonpath -p stack-auth-node -p stack-auth-wasm --all-features, with the compile tests: 2053 passed, 2 skipped.stack-encrypt-jsonpathis a crate that feat(stack-encrypt,eql-bindings): typed JSON queries from a field reference #1687 adds. Two stack-auth tests in that run,test_poll_for_token_clamps_an_oversized_device_code_lifetimeandtest_poll_for_token_clamps_an_oversized_token_lifetime, failed in 4 of 6 repeats afterwards, while the machine was under heavy load from other builds. They fail the same way on feat(stack-encrypt,eql-bindings): typed JSON queries from a field reference #1687's head without this PR, and this PR changes none of the device-code files. They passed in CI.cargo test --no-default-features: stack-auth 131, stack-kms 106, stack-encrypt 1009 passed.cargo clippy --workspace --all-features --all-targets -- -D warnings,cargo fmt --all -- --check,RUSTDOCFLAGS="-D warnings" cargo docfor the three crates with every feature,mise run wasm:wasi-check, andcargo check -p stack-auth-wasm --target wasm32-unknown-unknown: clean.cargo test -p eql-bindings -p eql-encryption-tests --all-features: 414 passed, 64 ignored. The ignored tests need a PostgreSQL database.eqlfeature:cargo teston the native build, 77 passed, andcargo check --target wasm32-wasip1, clean. Two pushes earlier (c6abfccfd), which differs only in what feat(stack-encrypt,eql-bindings): typed JSON queries from a field reference #1687 changed: the encrypt guest withouteql, 75 passed, the auth guest, 15 passed, and thewasm32-wasip1checks of both guests, clean.Not run locally on this head:
cargo mutants. CI runs it on every line this PR changes, and it passed on this head. Before the second rebase, a local run on the four files the first rebase changed found 41 mutants: 16 caught, 25 that do not compile, none missed.cargo check --workspace --all-features --all-targetswas clean on each, and their tests passed. The files of those two commits have not changed since.Not run again after the rebase, because stack-auth and the two bindings are the same files as before it: the Node binding's JavaScript tests (120 passed on the old history) and
wasm-pack testfor the wasm binding (28 passed).One thing an EQL run caught, before the rebase. Its test that watches freed memory for plaintext failed when the cipher called the key source's request methods directly. A call's future is built on the stack and moved to the heap with every byte it does not initialise, so a change to its layout changes which stale stack bytes go with it. The cipher now calls each request through one small
async fn, as it did before, and the test passes.credential.rssays why those functions exist. That test passes on the rebased head too, and so do the heap tests #1687 adds.Tests of the new behaviour, none of which needs the network:
tests/ui):call_with_no_credential:.awaitwith no credential does not compile on a call throughFakeCredentialKeySource, through aStackKmsovercredential_per_call, on an audited call, on a value sealed under a context, or on a zipped call.credential_on_a_source_with_its_own_identity:.with_credential(..)does not compile on a call through a test key source with its own identity, aStackKmsover an access key, or aStackKmsover an OIDC strategy with a provider.pass/oidc_strategies(must compile): over an OIDC strategy with a provider, a single call, an audited call, a value sealed under a context and a zipped call are awaited with no credential. Over acredential_per_callstrategy, the same four are awaited with one.get_token_with_credentialon an OIDC strategy with a provider (in stack-auth), a call awaited with no credential,a.with_credential(jwt).zip(b),get_token()on acredential_per_callstrategy, and a plain request onFakeCredentialKeySource.packages/stack-encrypt/tests/credential.rs, 30 tests, over a fake key source that only takes a credential and records it.initmakes no request; taking a keyset makes no request; the first call loads the keyset and later ones load nothing; reading the id loads it; callers arriving together make one load; a refused or cancelled first load leaves the keyset unloaded;initstill fails at startup on bad credentials, for a key source with its own identity.tests/keysets.rs: a new test renames a keyset between two calls built through one handle, and checks that both run under the handle's keyset and that the stored value opens. The cache, eviction and rename tests are unchanged in what they assert.tests/heap_hygiene.rs: an equality term, a match term, an order term and a scalar encrypt through a keyset that is not loaded leave no plaintext in freed memory.tests/json_operators.rs, over several ciphers that share one key store, as several processes share one ZeroKMS. Each kind of JSON query operand built before the load equals the one built after it. A read built before the load opens when awaited, with one load and one key request. Two such reads merged make one load and one key request.target/pending.rsfor the keyset selector's merge rules, the keyset checks before an id is known, a request for the pending's keyset, a pending built after the load, alone and merged, and the wipe of what such a pending recovered when a later operation fails.keyset.rs: a cache with no default keyset holds every keyset in its bound; a default keyset loaded late is held apart from what is cached; a cached keyset that turns out to be the default leaves the bound, keeps its name, and keeps its place in the order of lookups; the default is decided by the first load.auth_strategy(..).key_provider(..).init()over a realStackKmsand a strategy that only takes a credential:initasks it for no token, and the first call asks with the credential of that call.Run by CI only, not locally:
cargo mutants, on every line this PR changes. Before the rebase, the first run on the compile-error commit found the two gaps that item 4 above closes. The run on39908044bpassed.cargo publish --dry-run.Not run:
next(get_token_for_jwtthere, now the privatetoken_for_jwt). This PR calls it and does not change what it does.Sibling pull requests
cipher.rswhen last checked. Whichever merges second resolves those two.context.Context, in the Go host, and the guest asks the host for a token on each request. So Go passes the caller per call withoutwith_credential. What Go does not have is the deferred startup:NewClientstill loads the default keyset with whatever token the provider gives for its ownctx. This PR does not change that.Related
Closes #1708. Builds on #1687, #1707 and #1701, all merged.
Refs #1565, the same need in the TypeScript package.
Review notes
Read in this order:
packages/stack-encrypt/src/credential.rs:KeySource,OwnIdentity,WithCredential. Thenpackages/stack-kms/src/key_source.rsfor the three traits, andpackages/stack-auth/src/oidc_federation_strategy.rsfor the two trait impls.packages/stack-encrypt/src/target/pending.rs:KeysetSelector,settle_with,resolved_id,resolved,check_keyset, andwith_credential.packages/stack-encrypt/src/keyset.rs:KeysetCipher,loaded_state,deferred.packages/stack-encrypt/src/cipher.rs:StackCipher::keyset,selected_state,loadedandStackCipherBuilder::init.sem/mod.rs,json/derive.rs,json/inputs.rs,target/core.rs.One decision is settled:
.with_credential(..), and does not take one. A call that passes it a credential does not compile. The provider is the one source for the caller's JWT. A server that wants a callback for most calls and a JWT for a few builds one strategy of each kind, or usescredential_per_callfor all of them. stack-auth holds this rule, in its two strategy traits. Stack KMS and Stack Encrypt follow from them. The JavaScript API of the language bindings is not affected: inside, they use acredential_per_callstrategy.Decisions that are open to change:
init, as onnext. Build the strategy withcredential_per_callto defer.keyset(..)making no request. The Go guest keeps the old behaviour by reading the id where it selects.Other things to know:
Pending<'a, T, K>statesT: 'a. The compiler inferred that bound until the type came to name itself in the build stage.initchecks nothing against ZeroKMS. A mistake in the configuration shows up on the first call. A program that holds a credential at startup can run the check then:cipher.default_keyset().keyset_id().with_credential(credential).await?.CipherRef::keyset_id()returnsNonefor a keyset that is not loaded yet, unless it was selected by its id.StackCipher's andKeysetCipher'sDebugoutput showskeyset_id: Noneuntil the keyset is loaded.tests/ui/foreign_cipher_ref.rschanges. The case builds aCipherReffrom its private fields, and one field has a new type that an outside crate cannot name..cargo/mutants.tomlgains two entries for the wasm32-onlyinto_futureof a call with a credential, beside the two that are there for the same reason.Pending<..>is not a future", and it shows the boundK: DataKeySource + IndexKeySource. It does not name.with_credential(..): Rust has no way to customise the message of.await. The docs ofPending,WithCredentialandKeySourcesay it.stack-authandstack-kmschangelogs list this PR's additions under the version in the tree, which is not released. The three crates have to be released together.b09754ab3.