From d2bbf5bac577d62b6742d0f580b3b8427539ef1e Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Thu, 19 Nov 2026 23:22:06 +1100 Subject: [PATCH 1/3] feat(stack-encrypt)!: read credentials only where the caller names them StackCipher::new() and init() on the bare builder read CS_CLIENT_ID, CS_CLIENT_KEY, CS_CLIENT_ACCESS_KEY, CS_WORKSPACE_CRN and the CLI's profile directory, and nothing in the call said so. A developer with the variables exported for another project, or a test that inherits them from CI, got credentials nobody chose for the cipher. StackCipher::with_detected_credentials() replaces new(). It reads the same places in the same order, and its name says what it does. It is the only way to build a cipher that looks for credentials itself. The bare builder no longer has init(). Name a data-key source first, with kms(..), or with auth_strategy(..) and then key_provider(..). Its state type FromEnv is renamed NoKms. A compile-fail test pins that StackCipher::builder().init() does not compile. BREAKING CHANGE: StackCipher::new() is now StackCipher::with_detected_credentials(). StackCipher::builder().init() needs a data-key source: write .auth_strategy(AutoStrategy::detect()?).key_provider(FallbackKeyProvider::new(EnvKeyProvider, ProfileKeyProvider::for_detected_workspace())) for the same cipher with builder options. FromEnv is renamed NoKms. Closes #1722 --- languages/golang/encrypt/credentials.go | 4 +- packages/stack-encrypt/CHANGELOG.md | 19 +- packages/stack-encrypt/Cargo.toml | 7 +- .../examples/encrypted_record.rs | 4 +- packages/stack-encrypt/examples/mixed_user.rs | 2 +- .../stack-encrypt/examples/opaque_blob.rs | 2 +- packages/stack-encrypt/examples/scalar.rs | 2 +- .../stack-encrypt/examples/search_terms.rs | 7 +- .../stack-encrypt/examples/zerokms_auth.rs | 12 +- packages/stack-encrypt/src/cipher.rs | 170 ++++++++++-------- packages/stack-encrypt/src/lib.rs | 28 +-- .../tests/ui/builder_init_without_a_source.rs | 13 ++ .../ui/builder_init_without_a_source.stderr | 14 ++ 13 files changed, 182 insertions(+), 102 deletions(-) create mode 100644 packages/stack-encrypt/tests/ui/builder_init_without_a_source.rs create mode 100644 packages/stack-encrypt/tests/ui/builder_init_without_a_source.stderr diff --git a/languages/golang/encrypt/credentials.go b/languages/golang/encrypt/credentials.go index 0e65c94e7c..1135b956e0 100644 --- a/languages/golang/encrypt/credentials.go +++ b/languages/golang/encrypt/credentials.go @@ -179,8 +179,8 @@ var envZeroKMSHost = []string{"CS_ZEROKMS_HOST", "CS_VITUR_HOST"} // AutoCredentials is [Credentials] from the environment first, then the // developer profile `stash auth login` writes — the order the Rust client -// (stack-encrypt's StackCipher::builder().init()) resolves them in, so one -// set of variables configures a service in either language: +// (stack-encrypt's StackCipher::with_detected_credentials()) resolves them +// in, so one set of variables configures a service in either language: // // - The token, by stack-auth's AutoStrategy order: CS_CLIENT_ACCESS_KEY // (with CS_WORKSPACE_CRN, which is then required) exchanged for a token; diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 79ef9967c6..afab28d277 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `StackCipher::builder().auth_strategy(strategy).key_provider(provider).init()` builds the ZeroKMS client from an auth strategy and a client key provider that you choose. Before, a caller who wanted another auth strategy had to - build the `StackKms` by hand. `init()` and `kms(..)` are unchanged. + build the `StackKms` by hand. `kms(..)` is unchanged. - `auth_strategy` takes any strategy `StackKmsBuilder::new` takes: an `OidcFederationStrategy`, an `AccessKeyStrategy`, or an `AuthStrategyFn`. - `key_provider` is required after `auth_strategy`. The builder then reads @@ -133,6 +133,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Breaking +- **A cipher no longer reads credentials you did not name** (#1722). + `StackCipher::new()` and `init()` on the bare builder read + `CS_CLIENT_ID`, `CS_CLIENT_KEY`, `CS_CLIENT_ACCESS_KEY`, + `CS_WORKSPACE_CRN` and the CLI's profile directory, and nothing in the + call said so. Both are removed. + - `StackCipher::with_detected_credentials()` replaces `new()`. It reads + the same places in the same order, and its name says so. To upgrade, + rename the call. + - `StackCipher::builder()` has no `init()` until you name a data-key + source, with `kms(..)` or with `auth_strategy(..)` and then + `key_provider(..)`. For `StackCipher::builder().init()` with builder + options such as `keyset_cache_size`, write + `.auth_strategy(AutoStrategy::detect()?)` and + `.key_provider(FallbackKeyProvider::new(EnvKeyProvider, ProfileKeyProvider::for_detected_workspace()))` + before `init()`. That builds the same cipher. + - The builder state `FromEnv` is renamed `NoKms`, since the builder no + longer reads the environment in it. - **`target::ExpectedContext` is no longer part of the API** (#1488). It is the check that a `#[stash(context_field)]` record runs on decrypt: the stored context must equal the one the caller expects, if the caller diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index 759e430b9e..6b3a98bffa 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -14,9 +14,10 @@ license-file = "LICENSE" [dependencies] # `profile` (native only; stack-kms gates it off wasm32 itself) lets -# `StackCipher::new()` fall back to the client key `stash auth login` writes -# to the profile directory (`secretkey.json`) when CS_CLIENT_ID / -# CS_CLIENT_KEY are not set — the same place `AutoStrategy` finds the token. +# `StackCipher::with_detected_credentials()` fall back to the client key +# `stash auth login` writes to the profile directory (`secretkey.json`) when +# CS_CLIENT_ID / CS_CLIENT_KEY are not set — the same place `AutoStrategy` +# finds the token. stack-kms = { path = "../stack-kms", version = "0.2.0", default-features = false, features = ["profile"] } # `StackCipher::new()` builds a ZeroKMS client from the environment, so its # return type names the auto-detected auth strategy. Only needed with `http`. diff --git a/packages/stack-encrypt/examples/encrypted_record.rs b/packages/stack-encrypt/examples/encrypted_record.rs index 24bc9a86cd..edc45275fd 100644 --- a/packages/stack-encrypt/examples/encrypted_record.rs +++ b/packages/stack-encrypt/examples/encrypted_record.rs @@ -98,7 +98,7 @@ async fn main() -> Result<(), Box> { // The cipher seals each value under its own ZeroKMS data key. `new` also // loads the keyset's index key. The index key derives the terms. Data keys // and terms always come from the same keyset. - let cipher = StackCipher::new().await?; + let cipher = StackCipher::with_detected_credentials().await?; // The client's default keyset. let keyset = cipher.default_keyset(); @@ -158,7 +158,7 @@ async fn main() -> Result<(), Box> { // A second client. Any process with the same ZeroKMS credentials and // keyset can decrypt what this one wrote. - let decryptor = StackCipher::new().await?; + let decryptor = StackCipher::with_detected_credentials().await?; // Decrypting the matching rows together makes one batched // `retrieve_keys` call, however many rows match. Each field opens under diff --git a/packages/stack-encrypt/examples/mixed_user.rs b/packages/stack-encrypt/examples/mixed_user.rs index 1e13f629e1..6723e1e014 100644 --- a/packages/stack-encrypt/examples/mixed_user.rs +++ b/packages/stack-encrypt/examples/mixed_user.rs @@ -93,7 +93,7 @@ fn describe(ciphertext: &StackCipherText, indent: usize) { #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box> { - let cipher = StackCipher::new().await?; + let cipher = StackCipher::with_detected_credentials().await?; let users = vec![ User { diff --git a/packages/stack-encrypt/examples/opaque_blob.rs b/packages/stack-encrypt/examples/opaque_blob.rs index a9690e0ca7..ed31bb5b4f 100644 --- a/packages/stack-encrypt/examples/opaque_blob.rs +++ b/packages/stack-encrypt/examples/opaque_blob.rs @@ -33,7 +33,7 @@ struct ProfileV2 { #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box> { - let cipher = StackCipher::new().await?; + let cipher = StackCipher::with_detected_credentials().await?; let keyset = cipher.default_keyset(); let profile = Profile { diff --git a/packages/stack-encrypt/examples/scalar.rs b/packages/stack-encrypt/examples/scalar.rs index 20b30c8d84..b418e546d2 100644 --- a/packages/stack-encrypt/examples/scalar.rs +++ b/packages/stack-encrypt/examples/scalar.rs @@ -5,7 +5,7 @@ use stack_encrypt::{Ciphertext, DecryptFrom, EncryptInto, StackCipher}; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box> { - let cipher = StackCipher::new().await?; + let cipher = StackCipher::with_detected_credentials().await?; let keyset = cipher.default_keyset(); let encrypted = keyset.encrypt(42i32).await?; diff --git a/packages/stack-encrypt/examples/search_terms.rs b/packages/stack-encrypt/examples/search_terms.rs index 579fee6c9d..29bd912406 100644 --- a/packages/stack-encrypt/examples/search_terms.rs +++ b/packages/stack-encrypt/examples/search_terms.rs @@ -25,9 +25,10 @@ use stack_encrypt::{nonempty, EncryptFrom, StackCipher, StackCipherText}; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box> { - // `StackCipher::new()` builds a ZeroKMS client from the environment and - // loads the keyset's index key once, during construction. - let cipher = StackCipher::new().await?; + // `StackCipher::with_detected_credentials()` builds a ZeroKMS client from + // the environment or the CLI's login, and loads the keyset's index key + // once, during construction. + let cipher = StackCipher::with_detected_credentials().await?; // Terms bind to a keyset: this handle derives every term under the // default keyset's index key. let terms = cipher.default_keyset(); diff --git a/packages/stack-encrypt/examples/zerokms_auth.rs b/packages/stack-encrypt/examples/zerokms_auth.rs index a114e6840f..193cb1ba4d 100644 --- a/packages/stack-encrypt/examples/zerokms_auth.rs +++ b/packages/stack-encrypt/examples/zerokms_auth.rs @@ -19,19 +19,19 @@ use stack_encrypt::StackCipher; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box> { - // --- The default: credentials from the environment ---------------------- + // --- Detected credentials: from the environment or the CLI's login ------- // - // `StackCipher::new()` is `StackKmsBuilder::auto()` plus a client key, - // plus a keyset resolution. Both credentials are looked up the same way — - // environment first, then the current workspace in the CLI's profile - // directory (`~/.cipherstash`, written by `npx stash auth login`): + // `StackCipher::with_detected_credentials()` is the one constructor that + // looks for credentials itself. Both credentials are looked up the same + // way: the environment first, then the CLI's profile directory + // (`~/.cipherstash`, written by `npx stash auth login`): // // access token: CS_CLIENT_ACCESS_KEY + CS_WORKSPACE_CRN, else auth.json // client key: CS_CLIENT_ID + CS_CLIENT_KEY, else secretkey.json // // So a logged-in developer machine needs nothing else; CI sets the four // variables. - let cipher = match StackCipher::new().await { + let cipher = match StackCipher::with_detected_credentials().await { Ok(cipher) => cipher, // Nothing to connect to: say so and exit cleanly, so the example is // safe to run anywhere. diff --git a/packages/stack-encrypt/src/cipher.rs b/packages/stack-encrypt/src/cipher.rs index 4c516a577e..75a3ba8cb8 100644 --- a/packages/stack-encrypt/src/cipher.rs +++ b/packages/stack-encrypt/src/cipher.rs @@ -528,24 +528,26 @@ impl From for Error { /// /// # Construction /// -// `new()` builds the ZeroKMS client from the environment, so it exists only -// with `http`; the builder path below works in either shape. +// `with_detected_credentials()` builds the ZeroKMS client from the +// environment, so it exists only with `http`; the builder path below works in +// either shape. #[cfg_attr( feature = "http", - doc = r#"[`new`](Self::new) is the default path — a ZeroKMS client from the -environment, on that client's default keyset: + doc = r#"[`with_detected_credentials`](Self::with_detected_credentials) +reads the credentials from the environment, or from the CLI's login if the +variables are not set: ```no_run # async fn example() -> Result<(), stack_encrypt::Error> { use stack_encrypt::StackCipher; -let cipher = StackCipher::new().await?; +let cipher = StackCipher::with_detected_credentials().await?; # Ok(()) # } ``` -Override with [`builder`](Self::builder) — a different keyset, or a -different data-key source entirely:"# +To name the credentials yourself, or to set other options, use +[`builder`](Self::builder):"# )] #[cfg_attr( not(feature = "http"), @@ -589,24 +591,77 @@ pub struct StackCipher { #[cfg(feature = "http")] impl StackCipher> { - /// Build a cipher over a ZeroKMS client configured from the environment, - /// on that client's default keyset. + /// Build a cipher with credentials read from the environment, or from + /// the CLI's login if the variables are not set. /// - /// Equivalent to `StackCipher::builder().init()`. For a different keyset - /// or a different data-key source, use [`builder`](StackCipher::builder). - pub async fn new() -> Result { - StackCipher::builder().init().await + /// This is the only way to build a cipher that reads credentials you did + /// not name. It reads both of the credentials that ZeroKMS needs: + /// + /// - **The token.** [`stack_auth::AutoStrategy`] uses + /// `CS_CLIENT_ACCESS_KEY` with `CS_WORKSPACE_CRN`. If + /// `CS_CLIENT_ACCESS_KEY` is not set, it uses the login that + /// `npx stash auth login` saved. + /// - **The client key.** `CS_CLIENT_ID` and `CS_CLIENT_KEY`. If they are + /// not set, the `secretkey.json` that `npx stash auth login` saved, for + /// the workspace `CS_WORKSPACE_CRN` names, or else the CLI's current + /// workspace. On wasm32 there is no profile, so only the variables are + /// read. + /// + /// The CLI saves its login in `~/.cipherstash`, unless `CS_CONFIG_PATH` + /// names another directory. So on a developer machine, logging in with + /// the CLI is enough. In CI, set the four variables. + /// + /// Use it where the environment is the program's own to configure. Where + /// it is not, name the credentials with + /// [`StackCipherBuilder::auth_strategy`] and + /// [`StackCipherBuilder::key_provider`]. That builder also takes the + /// other options, such as + /// [`keyset_cache_size`](StackCipherBuilder::keyset_cache_size). This + /// builds the same cipher as `with_detected_credentials`: + /// + /// ```no_run + /// # async fn example() -> Result<(), Box> { + /// use stack_auth::AutoStrategy; + /// use stack_encrypt::StackCipher; + /// use stack_encrypt::kms::{EnvKeyProvider, FallbackKeyProvider, ProfileKeyProvider}; + /// + /// let cipher = StackCipher::builder() + /// .auth_strategy(AutoStrategy::detect()?) + /// .key_provider(FallbackKeyProvider::new( + /// EnvKeyProvider, + /// ProfileKeyProvider::for_detected_workspace(), + /// )) + /// .init() + /// .await?; + /// # Ok(()) + /// # } + /// ``` + /// + /// The cipher uses the client's default keyset. + /// + /// # Errors + /// + /// - [`Error::Config`] if no token or no client key is configured, or if + /// `CS_WORKSPACE_CRN` is not a CRN. + /// - [`Error::Kms`] if ZeroKMS refuses the request that loads the default + /// keyset. + pub async fn with_detected_credentials() -> Result { + let kms = StackKmsBuilder::auto()? + .with_key_provider(client_key_provider()) + .build() + .await?; + StackCipher::builder().kms(kms).init().await } } -impl StackCipher { - /// Start building a cipher: pick a keyset, or supply a data-key source - /// other than the environment's ZeroKMS client. +impl StackCipher { + /// Start building a cipher: name its data-key source, and set its + /// options. /// /// A convenience alias for [`StackCipherBuilder::new`], which is the - /// canonical entry point. This one is anchored on `StackCipher` + /// canonical entry point. This one is anchored on `StackCipher` /// purely so `StackCipher::builder()` names a single concrete `K` and - /// resolves without a type annotation; `StackCipher` is never + /// resolves without a type annotation; `StackCipher` is never /// constructed. pub fn builder() -> StackCipherBuilder { StackCipherBuilder::new() @@ -822,9 +877,10 @@ async fn load_default_keyset(kms: &K) -> Result { key_provider: P, } -/// Returns the client key provider for the default -/// [`init`](StackCipherBuilder::init). +/// Returns the client key provider for +/// [`StackCipher::with_detected_credentials`]. /// /// The provider reads `CS_CLIENT_ID` and `CS_CLIENT_KEY` first. If they are /// not set, the provider reads `secretkey.json` in the profile directory. @@ -857,7 +913,7 @@ fn client_key_provider() -> EnvKeyProvider { /// Builder for a [`StackCipher`]. Start with [`StackCipherBuilder::new`] (or /// its alias [`StackCipher::builder`]). -pub struct StackCipherBuilder { +pub struct StackCipherBuilder { kms: K, cache_size: NonZeroUsize, name_ttl: Duration, @@ -865,15 +921,15 @@ pub struct StackCipherBuilder { json_seed: Option>, } -impl StackCipherBuilder { - /// Start building a cipher: pick a keyset, or supply a data-key source - /// other than the environment's ZeroKMS client. +impl StackCipherBuilder { + /// Start building a cipher: name its data-key source, and set its + /// options. /// - /// The `K = FromEnv` type default makes this resolve without a type + /// The `K = NoKms` type default makes this resolve without a type /// annotation whether or not the `http` feature is on. pub fn new() -> Self { Self { - kms: FromEnv, + kms: NoKms, cache_size: KeysetCache::DEFAULT_CAPACITY, name_ttl: DEFAULT_NAME_TTL, #[cfg(feature = "test-support")] @@ -882,7 +938,7 @@ impl StackCipherBuilder { } } -impl Default for StackCipherBuilder { +impl Default for StackCipherBuilder { fn default() -> Self { Self::new() } @@ -931,9 +987,8 @@ impl StackCipherBuilder { } } -impl StackCipherBuilder { - /// Use the data-key source `kms` instead of a ZeroKMS client built from - /// the environment. +impl StackCipherBuilder { + /// Use the data-key source `kms`. /// /// Pass a [`kms::StackKms`](crate::kms::StackKms) that you built yourself /// to choose the transport settings, such as the timeouts or the ZeroKMS @@ -951,12 +1006,9 @@ impl StackCipherBuilder { } } - /// Get ZeroKMS tokens from `strategy`, instead of detecting an access - /// key or a CLI login. + /// Get ZeroKMS tokens from `strategy`. /// - /// The default [`init`](Self::init) uses [`stack_auth::AutoStrategy`]. - /// `AutoStrategy` detects an access key or a CLI login. Pass any other - /// strategy here. For example: + /// Pass any strategy here. For example: /// /// - An [`OidcFederationStrategy`](stack_auth::OidcFederationStrategy) /// exchanges the JWT of a user signed in to your application for a @@ -1039,32 +1091,6 @@ impl StackCipherBuilder { key_provider: (), }) } - - /// Build a ZeroKMS client from the environment, then resolve the keyset - /// and load its index key. - /// - /// Credentials come from the same two places for both halves of the - /// client — the access token and the client key: - /// - /// 1. the environment (`CS_CLIENT_ACCESS_KEY` + `CS_WORKSPACE_CRN`; - /// `CS_CLIENT_ID` + `CS_CLIENT_KEY`), then - /// 2. the CLI's profile directory (`auth.json`; `secretkey.json`), which - /// `npx stash auth login` writes: the workspace `CS_WORKSPACE_CRN` - /// names if it is set (for both files), otherwise the current one. - /// - /// So on a developer machine, logging in with the CLI is sufficient; in - /// CI, the four variables are. - /// - /// To choose the auth strategy and the source of the client key - /// yourself, call [`auth_strategy`](Self::auth_strategy) first. - #[cfg(feature = "http")] - pub async fn init(self) -> Result>, Error> { - let kms = StackKmsBuilder::auto()? - .with_key_provider(client_key_provider()) - .build() - .await?; - self.kms(kms).init().await - } } #[cfg(feature = "http")] @@ -2176,12 +2202,12 @@ mod credential_tests { } } - mod default_init { + mod with_detected_credentials { use super::*; #[test] fn given_no_credentials_is_not_authenticated() { - let error = run_with_env(None, None, || StackCipher::builder().init()) + let error = run_with_env(None, None, StackCipher::with_detected_credentials) .map(|_| ()) .unwrap_err(); @@ -2190,15 +2216,19 @@ mod credential_tests { builder_error(&error), stack_kms::StackKmsBuilderError::Auth(AuthError::NotAuthenticated(_)) ), - "the default init detects no access key and no session, got: {error:?}" + "no access key and no session is detected, got: {error:?}" ); } #[test] fn given_an_unparseable_cs_workspace_crn_is_invalid_crn() { - let error = run_with_env(None, Some("not-a-crn"), || StackCipher::builder().init()) - .map(|_| ()) - .unwrap_err(); + let error = run_with_env( + None, + Some("not-a-crn"), + StackCipher::with_detected_credentials, + ) + .map(|_| ()) + .unwrap_err(); assert!( matches!( diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index 203840b3bc..222e80fd39 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -37,8 +37,8 @@ //! //! # Quick start //! -// `StackCipher::new()` builds a ZeroKMS client from the environment, so it -// only exists with `http`. Without it the entry point is +// `StackCipher::with_detected_credentials()` builds a ZeroKMS client from the +// environment, so it only exists with `http`. Without it the entry point is // `StackCipher::builder().kms(..)` over an explicit data-key source — the // shape the WASI/wazero guest builds against; see "Testing without ZeroKMS" // below for the same call over the in-memory stub. @@ -48,9 +48,10 @@ # async fn example() -> Result<(), Box> { use stack_encrypt::StackCipher; -// Credentials: `npx stash auth login` on a developer machine, or -// CS_CLIENT_ID / CS_CLIENT_KEY + CS_CLIENT_ACCESS_KEY / CS_WORKSPACE_CRN in CI. -let cipher = StackCipher::new().await?; +// Reads the credentials from CS_CLIENT_ID / CS_CLIENT_KEY and +// CS_CLIENT_ACCESS_KEY / CS_WORKSPACE_CRN, or else from the login that +// `npx stash auth login` saved. +let cipher = StackCipher::with_detected_credentials().await?; let keyset = cipher.default_keyset(); // Encryption consumes and wipes the owned plaintext. @@ -65,8 +66,9 @@ assert_eq!(plaintext, "secret message"); not(feature = "http"), doc = "Without the `http` feature a cipher is built over an explicit\ data-key source — `StackCipher::builder().kms(..).init()` — rather than from\ - the environment. Enable `http` for `StackCipher::new()`, which discovers\ - ZeroKMS credentials itself." + the environment. Enable `http` for\ + `StackCipher::with_detected_credentials()`, which reads ZeroKMS credentials\ + from the environment or the CLI's login." )] //! //! Encrypting binds to a keyset (every data key is minted under one); decrypting @@ -110,10 +112,12 @@ A cipher needs two credentials, resolved independently of each other: against; and - an **auth strategy** — whatever obtains a token ZeroKMS will accept. -Each is looked for in the environment first, then in the current workspace of -the CLI's profile directory (`~/.cipherstash`), which `npx stash auth login` -writes. A logged-in developer machine has both there, so -`StackCipher::new()` usually just works with nothing else set. +A cipher reads credentials only from where your code says. +[`StackCipher::with_detected_credentials`] is the one constructor that looks +for them itself. It looks in the environment first, then in the CLI's profile +directory (`~/.cipherstash`), which `npx stash auth login` writes. A +logged-in developer machine has both there, so it works with nothing else +set. Where there is no profile — CI, a container, wasm — the environment carries them. `CS_CLIENT_ID` + `CS_CLIENT_KEY` are the client key. @@ -650,7 +654,7 @@ pub mod value; #[cfg(feature = "http")] pub use cipher::WithAuthStrategy; pub use cipher::{ - Error, FromEnv, LeafBytesError, PendingStackCipherText, SealedValue, StackCipher, + Error, LeafBytesError, NoKms, PendingStackCipherText, SealedValue, StackCipher, StackCipherBuilder, StackCipherText, }; pub use contexts::{ diff --git a/packages/stack-encrypt/tests/ui/builder_init_without_a_source.rs b/packages/stack-encrypt/tests/ui/builder_init_without_a_source.rs new file mode 100644 index 0000000000..89efffbafd --- /dev/null +++ b/packages/stack-encrypt/tests/ui/builder_init_without_a_source.rs @@ -0,0 +1,13 @@ +//! A cipher reads credentials only from where the caller's code says. The +//! bare builder has no `init`: name a data-key source first, with `kms(..)` +//! or with `auth_strategy(..)` and `key_provider(..)`. The constructor that +//! detects credentials is named for it: +//! `StackCipher::with_detected_credentials()`. + +use stack_encrypt::StackCipher; + +async fn bare_builder() { + let _ = StackCipher::builder().init().await; +} + +fn main() {} diff --git a/packages/stack-encrypt/tests/ui/builder_init_without_a_source.stderr b/packages/stack-encrypt/tests/ui/builder_init_without_a_source.stderr new file mode 100644 index 0000000000..bd452b710d --- /dev/null +++ b/packages/stack-encrypt/tests/ui/builder_init_without_a_source.stderr @@ -0,0 +1,14 @@ +error[E0599]: the method `init` exists for struct `StackCipherBuilder`, but its trait bounds were not satisfied + --> tests/ui/builder_init_without_a_source.rs:10:36 + | +10 | let _ = StackCipher::builder().init().await; + | ^^^^ method cannot be called on `StackCipherBuilder` due to unsatisfied trait bounds + | + ::: src/cipher.rs + | + | pub struct NoKms; + | ---------------- doesn't satisfy `NoKms: DataKeySource` or `NoKms: IndexKeySource` + | + = note: the following trait bounds were not satisfied: + `NoKms: DataKeySource` + `NoKms: IndexKeySource` From f23b73a36611b604cfce841c9512e9a37ba11ed1 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 22 Nov 2026 21:04:05 +1100 Subject: [PATCH 2/3] fix(stack-encrypt): address the review of explicit credentials - The mutants exclusion for the equivalent `builder` mutant names `StackCipher`, the state's new name. - The upgrade step in the CHANGELOG and the builder form in the `with_detected_credentials` docs say they build the same cipher on a native target. `ProfileKeyProvider` is native-only, so on wasm32 the same cipher takes `.key_provider(EnvKeyProvider)`. - The crate docs, the `key_provider` docs and the compile-fail test say that a builder given an auth strategy and a key provider still reads the ZeroKMS endpoint from `CS_ZEROKMS_HOST`, and how to choose it in code. - `Error::Config` no longer says "from the environment", and its help names the variables as what `with_detected_credentials` reads. - The Cargo.toml and tests-golang.yml comments name `with_detected_credentials()` in place of `new()`. --- .cargo/mutants.toml | 2 +- .github/workflows/tests-golang.yml | 5 ++-- packages/stack-encrypt/CHANGELOG.md | 7 ++++- packages/stack-encrypt/Cargo.toml | 16 ++++++----- packages/stack-encrypt/src/cipher.rs | 27 ++++++++++++++----- packages/stack-encrypt/src/lib.rs | 5 ++++ .../tests/ui/builder_init_without_a_source.rs | 5 ++-- .../ui/builder_init_without_a_source.stderr | 4 +-- 8 files changed, 50 insertions(+), 21 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index d3362e2d2e..516fbc095b 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -93,7 +93,7 @@ exclude_re = [ 'stack-encrypt/src/op(/mod)?\.rs:\d+:\d+: replace >::clone -> Self with Default::default\(\)$', 'stack-encrypt/src/op(/mod)?\.rs:\d+:\d+: replace Matches::case_sensitive -> Matches with Default::default\(\)$', 'stack-encrypt/src/target/index\.rs:\d+:\d+: replace >::clone -> Self with Default::default\(\)$', - 'stack-encrypt/src/cipher\.rs:\d+:\d+: replace StackCipher::builder -> StackCipherBuilder with Default::default\(\)$', + 'stack-encrypt/src/cipher\.rs:\d+:\d+: replace StackCipher::builder -> StackCipherBuilder with Default::default\(\)$', 'stack-encrypt/src/sem/mod\.rs:\d+:\d+: replace ::options -> MatchOptions with Default::default\(\)$', # `Orderable`'s default `check_query` refuses nothing: its body is # `Ok(())`, so the replacement is the body. Text overrides it with diff --git a/.github/workflows/tests-golang.yml b/.github/workflows/tests-golang.yml index bf0533fe4b..16e740a75f 100644 --- a/.github/workflows/tests-golang.yml +++ b/.github/workflows/tests-golang.yml @@ -562,8 +562,9 @@ jobs: # Round trips through real ZeroKMS. The Go live tests skip without their # STACK_ENCRYPT_TEST_* variables, so the secrets pre-flight runs first and # turns a missing credential into a failure rather than a silent skip. The - # stack-encrypt examples read CS_* through `StackCipher::new()`; tests-crates - # builds them, and this job runs them. + # stack-encrypt examples read CS_* through + # `StackCipher::with_detected_credentials()`; tests-crates builds them, and + # this job runs them. live: name: Go live tests and stack-encrypt examples needs: wasi-check diff --git a/packages/stack-encrypt/CHANGELOG.md b/packages/stack-encrypt/CHANGELOG.md index 78569d2d93..e7f2854de1 100644 --- a/packages/stack-encrypt/CHANGELOG.md +++ b/packages/stack-encrypt/CHANGELOG.md @@ -452,9 +452,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 options such as `keyset_cache_size`, write `.auth_strategy(AutoStrategy::detect()?)` and `.key_provider(FallbackKeyProvider::new(EnvKeyProvider, ProfileKeyProvider::for_detected_workspace()))` - before `init()`. That builds the same cipher. + before `init()`. That builds the same cipher on a native target. + `ProfileKeyProvider` exists on native targets only, so on wasm32 write + `.key_provider(EnvKeyProvider)`. - The builder state `FromEnv` is renamed `NoKms`, since the builder no longer reads the environment in it. + - `Error::Config` reads "could not build a ZeroKMS client", without + "from the environment": a builder given an auth strategy and a key + provider reports its errors there too. - **A key source of your own states its kind.** `kms::DataKeySource`, `kms::IndexKeySource` and `kms::CredentialKeySource` each require diff --git a/packages/stack-encrypt/Cargo.toml b/packages/stack-encrypt/Cargo.toml index b8330f3f59..01531ff4f5 100644 --- a/packages/stack-encrypt/Cargo.toml +++ b/packages/stack-encrypt/Cargo.toml @@ -19,8 +19,9 @@ license-file = "LICENSE" # CS_CLIENT_ID / CS_CLIENT_KEY are not set — the same place `AutoStrategy` # finds the token. stack-kms = { path = "../stack-kms", version = "0.2.0", default-features = false, features = ["profile"] } -# `StackCipher::new()` builds a ZeroKMS client from the environment, so its -# return type names the auto-detected auth strategy. Only needed with `http`. +# `StackCipher::with_detected_credentials()` builds a ZeroKMS client from the +# environment, so its return type names the auto-detected auth strategy. Only +# needed with `http`. stack-auth = { workspace = true, optional = true } # `#[derive(EncryptTarget)]` / `#[derive(DecryptSource)]`, re-exported from `target`. stack-encrypt-derive = { path = "../stack-encrypt-derive", version = "0.3.0" } @@ -107,11 +108,12 @@ zeroize = { workspace = true } [features] default = ["http", "jiff", "rust_decimal"] -# `StackCipher::new()` / `StackCipher::builder().init()` from the environment: -# the default HTTP transport in stack-kms and the auto-detected auth strategy -# in stack-auth. Off, a cipher is built over an explicit `DataKeySource` -# (`StackCipher::builder().kms(..)`) and no HTTP client or TLS stack is in -# the dependency graph — the shape the WASI/wazero guest builds against. +# A cipher over ZeroKMS: `StackCipher::with_detected_credentials()`, or +# `StackCipher::builder().auth_strategy(..)`. It brings the default HTTP +# transport in stack-kms and the auth strategies in stack-auth. Off, a cipher +# is built over an explicit `DataKeySource` (`StackCipher::builder().kms(..)`) +# and no HTTP client or TLS stack is in the dependency graph — the shape the +# WASI/wazero guest builds against. http = ["dep:stack-auth", "stack-auth/http", "stack-kms/http"] # `stack_encrypt::dynamic`: encrypt and decrypt values whose types are known # only at runtime, as an FFI binding's are. Off by default — it is only of diff --git a/packages/stack-encrypt/src/cipher.rs b/packages/stack-encrypt/src/cipher.rs index 476feda96a..9081825e4a 100644 --- a/packages/stack-encrypt/src/cipher.rs +++ b/packages/stack-encrypt/src/cipher.rs @@ -254,8 +254,8 @@ pub enum Error { ) )] DescriptorTooLong { len: usize }, - /// Building a ZeroKMS client from the environment failed: credentials or - /// client key missing or malformed. + /// Building a ZeroKMS client failed: a credential or the client key is + /// missing or malformed, or `CS_ZEROKMS_HOST` cannot be used. /// /// Boxed rather than naming `stack_encrypt::kms::StackKmsBuilderError` directly: /// that type only exists with `http`, and a variant whose presence tracks @@ -268,10 +268,10 @@ pub enum Error { /// /// Its payload is the builder error's (the variable at fault, say). Its /// code stays this one; the builder error's own is on the source. - #[error("could not build a ZeroKMS client from the environment: {0}")] + #[error("could not build a ZeroKMS client: {0}")] #[diagnostic( code(stack_encrypt::config), - help("The message says which setting failed. Check `CS_WORKSPACE_CRN`, `CS_CLIENT_ID`, `CS_CLIENT_KEY`, `CS_CLIENT_ACCESS_KEY` and `CS_ZEROKMS_HOST`, or log in with `stash auth login`.") + help("The message says which setting failed. Check the auth strategy and key provider you named, and `CS_ZEROKMS_HOST` if it is set. `with_detected_credentials` reads `CS_WORKSPACE_CRN`, `CS_CLIENT_ID`, `CS_CLIENT_KEY` and `CS_CLIENT_ACCESS_KEY`, or the login `stash auth login` saved.") )] Config(#[source] Box), /// An index term failed to derive. @@ -667,8 +667,9 @@ impl StackCipher> { /// [`StackCipherBuilder::auth_strategy`] and /// [`StackCipherBuilder::key_provider`]. That builder also takes the /// other options, such as - /// [`keyset_cache_size`](StackCipherBuilder::keyset_cache_size). This - /// builds the same cipher as `with_detected_credentials`: + /// [`keyset_cache_size`](StackCipherBuilder::keyset_cache_size). On a + /// native target, this builds the same cipher as + /// `with_detected_credentials`: /// /// ```no_run /// # async fn example() -> Result<(), Box> { @@ -688,6 +689,13 @@ impl StackCipher> { /// # } /// ``` /// + /// `ProfileKeyProvider` exists on native targets only. On wasm32 there is + /// no profile, so the same cipher is `.key_provider(EnvKeyProvider)`. + /// + /// Both forms take the ZeroKMS endpoint from `CS_ZEROKMS_HOST` if it is + /// set. To choose it in code, see + /// [`auth_strategy`](StackCipherBuilder::auth_strategy). + /// /// The cipher uses the client's default keyset. /// /// # Errors @@ -1284,6 +1292,13 @@ impl StackCipherBuilder> { /// /// The client key must belong to the workspace that the strategy's /// tokens are for. + /// + /// The builder still reads one setting from the environment: the + /// ZeroKMS endpoint, from `CS_ZEROKMS_HOST`, if it is set. The token and + /// the client key go to that endpoint. To choose the endpoint in code, + /// build a [`StackKms`] with + /// [`with_base_url`](crate::kms::StackKmsBuilder::with_base_url) and pass + /// it to [`kms`](StackCipherBuilder::kms). pub fn key_provider( self, provider: P, diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index a89ecda4a8..f0db396409 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -120,6 +120,11 @@ directory (`~/.cipherstash`), which `npx stash auth login` writes. A logged-in developer machine has both there, so it works with nothing else set. +The ZeroKMS endpoint is a setting, not a credential, and every cipher over +ZeroKMS reads it from `CS_ZEROKMS_HOST` if that is set. The credentials go to +that endpoint. To choose it in code, pass [`kms`](StackCipherBuilder::kms) a +`StackKms` built with `with_base_url`. + Where there is no profile — CI, a container, wasm — the environment carries them. `CS_CLIENT_ID` + `CS_CLIENT_KEY` are the client key. `CS_CLIENT_ACCESS_KEY` is the auth strategy `AutoStrategy` detects, and it diff --git a/packages/stack-encrypt/tests/ui/builder_init_without_a_source.rs b/packages/stack-encrypt/tests/ui/builder_init_without_a_source.rs index 89efffbafd..5c7072e586 100644 --- a/packages/stack-encrypt/tests/ui/builder_init_without_a_source.rs +++ b/packages/stack-encrypt/tests/ui/builder_init_without_a_source.rs @@ -1,5 +1,6 @@ -//! A cipher reads credentials only from where the caller's code says. The -//! bare builder has no `init`: name a data-key source first, with `kms(..)` +//! A cipher reads credentials only from where the caller's code says. (The +//! ZeroKMS endpoint, `CS_ZEROKMS_HOST`, is a setting and still comes from +//! the environment when set.) The bare builder has no `init`: name a data-key source first, with `kms(..)` //! or with `auth_strategy(..)` and `key_provider(..)`. The constructor that //! detects credentials is named for it: //! `StackCipher::with_detected_credentials()`. diff --git a/packages/stack-encrypt/tests/ui/builder_init_without_a_source.stderr b/packages/stack-encrypt/tests/ui/builder_init_without_a_source.stderr index 7c932abed1..e022313b08 100644 --- a/packages/stack-encrypt/tests/ui/builder_init_without_a_source.stderr +++ b/packages/stack-encrypt/tests/ui/builder_init_without_a_source.stderr @@ -1,7 +1,7 @@ error[E0599]: no method named `init` found for struct `StackCipherBuilder` in the current scope - --> tests/ui/builder_init_without_a_source.rs:10:36 + --> tests/ui/builder_init_without_a_source.rs:11:36 | -10 | let _ = StackCipher::builder().init().await; +11 | let _ = StackCipher::builder().init().await; | ^^^^ method not found in `StackCipherBuilder` | = note: the method was found for From e781419a83fc82dc246b8284dd1387a2bdbca0a0 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sun, 22 Nov 2026 21:16:09 +1100 Subject: [PATCH 3/3] docs(stack-encrypt): say that only the token goes to the ZeroKMS endpoint The client key never leaves the program: a request sends the token and the client id, and the key material that comes back is combined with the client key locally. --- packages/stack-encrypt/src/cipher.rs | 6 +++--- packages/stack-encrypt/src/lib.rs | 7 ++++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/stack-encrypt/src/cipher.rs b/packages/stack-encrypt/src/cipher.rs index 9081825e4a..8dd8ea24c3 100644 --- a/packages/stack-encrypt/src/cipher.rs +++ b/packages/stack-encrypt/src/cipher.rs @@ -1294,9 +1294,9 @@ impl StackCipherBuilder> { /// tokens are for. /// /// The builder still reads one setting from the environment: the - /// ZeroKMS endpoint, from `CS_ZEROKMS_HOST`, if it is set. The token and - /// the client key go to that endpoint. To choose the endpoint in code, - /// build a [`StackKms`] with + /// ZeroKMS endpoint, from `CS_ZEROKMS_HOST`, if it is set. Each request + /// sends the token to that endpoint. The client key stays in your + /// program. To choose the endpoint in code, build a [`StackKms`] with /// [`with_base_url`](crate::kms::StackKmsBuilder::with_base_url) and pass /// it to [`kms`](StackCipherBuilder::kms). pub fn key_provider( diff --git a/packages/stack-encrypt/src/lib.rs b/packages/stack-encrypt/src/lib.rs index f0db396409..db538bcf80 100644 --- a/packages/stack-encrypt/src/lib.rs +++ b/packages/stack-encrypt/src/lib.rs @@ -121,9 +121,10 @@ logged-in developer machine has both there, so it works with nothing else set. The ZeroKMS endpoint is a setting, not a credential, and every cipher over -ZeroKMS reads it from `CS_ZEROKMS_HOST` if that is set. The credentials go to -that endpoint. To choose it in code, pass [`kms`](StackCipherBuilder::kms) a -`StackKms` built with `with_base_url`. +ZeroKMS reads it from `CS_ZEROKMS_HOST` if that is set. Each request sends the +token to that endpoint; the client key stays in your program. To choose it in +code, pass [`kms`](StackCipherBuilder::kms) a `StackKms` built with +`with_base_url`. Where there is no profile — CI, a container, wasm — the environment carries them. `CS_CLIENT_ID` + `CS_CLIENT_KEY` are the client key.