From 78256f7b21a02d1b8c47960ce2c58b299eba6973 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 21 Nov 2026 17:30:39 +1100 Subject: [PATCH 1/3] feat(stack-auth)!: take the JWT of a call from the call, with `CredentialAuthStrategy` 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. --- .changeset/auth-credential-per-call.md | 5 + languages/typescript/packages/auth/src/lib.rs | 57 +++-- .../packages/stack-auth-wasm/src/lib.rs | 56 +++-- packages/stack-auth/CHANGELOG.md | 30 ++- packages/stack-auth/src/lib.rs | 89 +++++++- .../src/oidc_federation_strategy.rs | 215 ++++++++++++------ packages/stack-auth/src/oidc_refresher.rs | 62 +++++ packages/stack-auth/src/strategy_kind.rs | 134 +++++++++++ 8 files changed, 521 insertions(+), 127 deletions(-) create mode 100644 .changeset/auth-credential-per-call.md create mode 100644 packages/stack-auth/src/strategy_kind.rs diff --git a/.changeset/auth-credential-per-call.md b/.changeset/auth-credential-per-call.md new file mode 100644 index 0000000000..55eb529ca7 --- /dev/null +++ b/.changeset/auth-credential-per-call.md @@ -0,0 +1,5 @@ +--- +'@cipherstash/auth': patch +--- + +Rebuild on a `stack-auth` whose Rust API can issue the token for a credential passed with the call. The JavaScript API is unchanged: `getToken` and `getTokenForJwt` behave as before, and share one token cache. In Rust, `CredentialAuthStrategy` is the trait for a credential passed with the call, and an `OidcFederationStrategy` can be built with no provider callback (`OidcFederationStrategy::credential_per_call`). Such a strategy has no `get_token`, so a call that brings no credential does not compile. A Rust strategy built with a provider callback takes no JWT from its caller. The Node and wasm bindings therefore build the Rust strategy with `credential_per_call`, keep the `getJwt` callback themselves, and pass a JWT with each call. diff --git a/languages/typescript/packages/auth/src/lib.rs b/languages/typescript/packages/auth/src/lib.rs index 3e5dff27bf..c83ff8a92a 100644 --- a/languages/typescript/packages/auth/src/lib.rs +++ b/languages/typescript/packages/auth/src/lib.rs @@ -7,8 +7,9 @@ use napi::threadsafe_function::{ErrorStrategy, ThreadsafeFunction, ThreadsafeFun use napi::tokio::sync::oneshot; use napi_derive::napi; use stack_auth::{ - AlreadyConsumed, AuthError, AuthStrategy, DeviceClientError, DeviceCodeStrategy, InternalError, - OidcProvider, PendingDeviceCode, SecretToken, ServerError, ServiceToken, Token, TokenStore, + AlreadyConsumed, AuthError, AuthStrategy, CredentialAuthStrategy, CredentialPerCall, + DeviceClientError, DeviceCodeStrategy, InternalError, OidcProvider, PendingDeviceCode, + SecretToken, ServerError, ServiceToken, Token, TokenStore, }; use vitaminc_protected::OpaqueDebug; use zeroize::Zeroizing; @@ -226,6 +227,12 @@ impl DeviceSessionStrategy { /// Bridges a JS `getJwt` callback into a Rust [`OidcProvider`]. /// +/// The binding keeps this provider itself, and does not give it to the Rust +/// strategy. A Rust strategy with a provider takes no JWT from its caller, +/// and `getTokenForJwt` has to hand one in. So the Rust strategy is built +/// with [`CredentialPerCall`], and each entry passes it a JWT: `getToken` +/// the one this provider returns, `getTokenForJwt` the one it was given. +/// /// `getJwt` is a JS function returning `Promise` — the current /// third-party OIDC JWT. The threadsafe function lets the Rust refresh engine /// (running on napi's tokio pool) schedule the call onto the Node event-loop @@ -318,14 +325,25 @@ impl TokenStore for NapiTokenStore { } enum OidcFederationStrategyInner { - NoStore(stack_auth::OidcFederationStrategy), - WithStore(stack_auth::OidcFederationStrategy), + NoStore(stack_auth::OidcFederationStrategy), + WithStore(stack_auth::OidcFederationStrategy), +} + +impl OidcFederationStrategyInner { + /// The CTS token for `jwt`: the one cached for it, or a fresh exchange. + async fn token_for(&self, jwt: SecretToken) -> std::result::Result { + match self { + Self::NoStore(s) => s.get_token_with_credential(jwt).await, + Self::WithStore(s) => s.get_token_with_credential(jwt).await, + } + } } /// An auth strategy that federates a third-party OIDC JWT (Clerk, Supabase, …) /// into a CipherStash CTS service token via `/api/authorise`. #[napi] pub struct OidcFederationStrategy { + provider: NapiOidcProvider, inner: OidcFederationStrategyInner, } @@ -376,15 +394,15 @@ impl OidcFederationStrategy { cache_capacity: Option, ) -> Result { let crn = parse_workspace_crn(&workspace_crn)?; - let mut builder = - stack_auth::OidcFederationStrategy::builder(crn, NapiOidcProvider { get_jwt }) - .maybe_base_url(base_url) - .map_err(to_napi_error)?; + let mut builder = stack_auth::OidcFederationStrategy::builder(crn, CredentialPerCall) + .maybe_base_url(base_url) + .map_err(to_napi_error)?; if let Some(capacity) = cache_capacity { builder = builder.cache_capacity(capacity as usize); } let inner = builder.build().map_err(to_napi_error)?; Ok(Self { + provider: NapiOidcProvider { get_jwt }, inner: OidcFederationStrategyInner::NoStore(inner), }) } @@ -416,10 +434,9 @@ impl OidcFederationStrategy { load: load_token, save: save_token, }; - let mut builder = - stack_auth::OidcFederationStrategy::builder(crn, NapiOidcProvider { get_jwt }) - .maybe_base_url(base_url) - .map_err(to_napi_error)?; + let mut builder = stack_auth::OidcFederationStrategy::builder(crn, CredentialPerCall) + .maybe_base_url(base_url) + .map_err(to_napi_error)?; if let Some(capacity) = cache_capacity { builder = builder.cache_capacity(capacity as usize); } @@ -428,6 +445,7 @@ impl OidcFederationStrategy { .build() .map_err(to_napi_error)?; Ok(Self { + provider: NapiOidcProvider { get_jwt }, inner: OidcFederationStrategyInner::WithStore(inner), }) } @@ -442,11 +460,10 @@ impl OidcFederationStrategy { /// `getJwt` needs no request context. #[napi] pub async fn get_token(&self) -> Result { - let token = match &self.inner { - OidcFederationStrategyInner::NoStore(s) => s.get_token().await, - OidcFederationStrategyInner::WithStore(s) => s.get_token().await, - } - .map_err(to_napi_error)?; + // Ask who this call is for before anything else, as a Rust strategy + // with a provider does. + let jwt = self.provider.fetch().await.map_err(to_napi_error)?; + let token = self.inner.token_for(jwt).await.map_err(to_napi_error)?; token_result_from(token) } @@ -459,11 +476,7 @@ impl OidcFederationStrategy { #[napi] pub async fn get_token_for_jwt(&self, jwt: String) -> Result { let jwt = SecretToken::new(jwt); - let token = match &self.inner { - OidcFederationStrategyInner::NoStore(s) => s.get_token_for_jwt(jwt).await, - OidcFederationStrategyInner::WithStore(s) => s.get_token_for_jwt(jwt).await, - } - .map_err(to_napi_error)?; + let token = self.inner.token_for(jwt).await.map_err(to_napi_error)?; token_result_from(token) } } diff --git a/languages/typescript/packages/stack-auth-wasm/src/lib.rs b/languages/typescript/packages/stack-auth-wasm/src/lib.rs index 68e4d82727..8e5581591d 100644 --- a/languages/typescript/packages/stack-auth-wasm/src/lib.rs +++ b/languages/typescript/packages/stack-auth-wasm/src/lib.rs @@ -16,7 +16,9 @@ use serde::Serialize; use serde_wasm_bindgen::Serializer; use stack_auth::{AuthError, AuthStrategy, ServiceToken}; #[cfg(target_arch = "wasm32")] -use stack_auth::{OidcProvider, SecretToken, Token, TokenStore}; +use stack_auth::{ + CredentialAuthStrategy, CredentialPerCall, OidcProvider, SecretToken, Token, TokenStore, +}; use wasm_bindgen::prelude::*; #[cfg(target_arch = "wasm32")] use wasm_bindgen_futures::JsFuture; @@ -196,6 +198,12 @@ fn js_error_detail(err: &JsValue) -> String { /// `OidcProvider` adapter over a JS callback. /// +/// The binding keeps this provider itself, and does not give it to the Rust +/// strategy. A Rust strategy with a provider takes no JWT from its caller, +/// and `getTokenForJwt` has to hand one in. So the Rust strategy is built +/// with [`CredentialPerCall`], and each entry passes it a JWT: `getToken` +/// the one this provider returns, `getTokenForJwt` the one it was given. +/// /// `getJwt` is called with no arguments and is expected to return /// `Promise` — the current third-party OIDC JWT to federate. Unlike /// [`JsTokenStore`], a failure here is fatal: federation can't proceed without @@ -331,30 +339,24 @@ impl AccessKeyStrategy { } } -/// Cfg-gated to wasm32: `OidcFederationStrategy` is generic over the JWT provider, and -/// the only provider the bindings offer (`JsOidcProvider`) wraps a +/// Cfg-gated to wasm32: the JWT provider (`JsOidcProvider`) and the token +/// store (`JsTokenStore`) the binding pairs with the strategy each wrap a /// `js_sys::Function`, which exists only on wasm32. The native build of this /// crate (used for `cargo clippy` / host `cargo test`) therefore has no /// `OidcFederationStrategy` — there is nothing native-testable about a JS-callback type. #[cfg(target_arch = "wasm32")] enum OidcFederationStrategyInner { - NoStore(stack_auth::OidcFederationStrategy), - WithStore(stack_auth::OidcFederationStrategy), + NoStore(stack_auth::OidcFederationStrategy), + WithStore(stack_auth::OidcFederationStrategy), } #[cfg(target_arch = "wasm32")] impl OidcFederationStrategyInner { - async fn get_token(&self) -> Result { - match self { - Self::NoStore(s) => s.get_token().await, - Self::WithStore(s) => s.get_token().await, - } - } - - async fn get_token_for_jwt(&self, jwt: SecretToken) -> Result { + /// The CTS token for `jwt`: the one cached for it, or a fresh exchange. + async fn token_for(&self, jwt: SecretToken) -> Result { match self { - Self::NoStore(s) => s.get_token_for_jwt(jwt).await, - Self::WithStore(s) => s.get_token_for_jwt(jwt).await, + Self::NoStore(s) => s.get_token_with_credential(jwt).await, + Self::WithStore(s) => s.get_token_with_credential(jwt).await, } } } @@ -364,6 +366,7 @@ impl OidcFederationStrategyInner { #[cfg(target_arch = "wasm32")] #[wasm_bindgen] pub struct OidcFederationStrategy { + provider: JsOidcProvider, inner: OidcFederationStrategyInner, } @@ -406,15 +409,15 @@ impl OidcFederationStrategy { cache_capacity: Option, ) -> Result { let crn = parse_workspace_crn(&workspace_crn)?; - let mut builder = - stack_auth::OidcFederationStrategy::builder(crn, JsOidcProvider { get_jwt }) - .maybe_base_url(base_url) - .map_err(to_js_error)?; + let mut builder = stack_auth::OidcFederationStrategy::builder(crn, CredentialPerCall) + .maybe_base_url(base_url) + .map_err(to_js_error)?; if let Some(capacity) = cache_capacity { builder = builder.cache_capacity(capacity as usize); } let inner = builder.build().map_err(to_js_error)?; Ok(OidcFederationStrategy { + provider: JsOidcProvider { get_jwt }, inner: OidcFederationStrategyInner::NoStore(inner), }) } @@ -445,10 +448,9 @@ impl OidcFederationStrategy { load: load_token, save: save_token, }; - let mut builder = - stack_auth::OidcFederationStrategy::builder(crn, JsOidcProvider { get_jwt }) - .maybe_base_url(base_url) - .map_err(to_js_error)?; + let mut builder = stack_auth::OidcFederationStrategy::builder(crn, CredentialPerCall) + .maybe_base_url(base_url) + .map_err(to_js_error)?; if let Some(capacity) = cache_capacity { builder = builder.cache_capacity(capacity as usize); } @@ -457,6 +459,7 @@ impl OidcFederationStrategy { .build() .map_err(to_js_error)?; Ok(OidcFederationStrategy { + provider: JsOidcProvider { get_jwt }, inner: OidcFederationStrategyInner::WithStore(inner), }) } @@ -464,8 +467,11 @@ impl OidcFederationStrategy { /// Retrieve a valid CTS service token, federating or re-federating as needed. #[wasm_bindgen(js_name = getToken)] pub async fn get_token(&self) -> Result { + // Ask who this call is for before anything else, as a Rust strategy + // with a provider does. + let jwt = self.provider.fetch().await.map_err(to_js_error)?; self.inner - .get_token() + .token_for(jwt) .await .map_err(to_js_error) .and_then(token_result_from) @@ -478,7 +484,7 @@ impl OidcFederationStrategy { #[wasm_bindgen(js_name = getTokenForJwt)] pub async fn get_token_for_jwt(&self, jwt: String) -> Result { self.inner - .get_token_for_jwt(SecretToken::new(jwt)) + .token_for(SecretToken::new(jwt)) .await .map_err(to_js_error) .and_then(token_result_from) diff --git a/packages/stack-auth/CHANGELOG.md b/packages/stack-auth/CHANGELOG.md index 7fab50f306..71e724e998 100644 --- a/packages/stack-auth/CHANGELOG.md +++ b/packages/stack-auth/CHANGELOG.md @@ -13,9 +13,6 @@ ### Features -- `OidcFederationStrategy::get_token_for_jwt`, the exchange for a JWT the - caller already holds. `get_token` is the provider fetch followed by it, and - both share one cache. - Every error carries a path-style miette code (`stack_auth::invalid_crn`) beside its unchanged frozen code, and implements stack-profile's `ErrorPayload`. `ERROR_CODES` lists every code. Re-exports `diagnostic` and @@ -32,6 +29,33 @@ a builder whose `build()` detects the workspace in the same way. Use it to set other options, such as a token store, without naming the workspace. `OidcFederationStrategy::builder(crn, provider)` is unchanged. +- `CredentialAuthStrategy::get_token_with_credential(credential)` issues the + token for a credential handed in with the call. A strategy implements it + or `AuthStrategy`, never both. So a call cannot forget its credential, and + a credential is never ignored: either mistake does not compile. +- `StrategyKind` says which of the two kinds a strategy is, and is what + stops a type from being both. Its `Kind` is `OwnIdentity` or + `CredentialPerCall`. Every `AuthStrategy` has the kind `OwnIdentity` + already, so an existing strategy needs no change. `CredentialAuthStrategy` + requires the kind `CredentialPerCall`: a strategy that implements it also + implements `StrategyKind`, with `type Kind = CredentialPerCall`. A type + that implements both strategy traits does not compile. +- `OidcFederationStrategy::credential_per_call(crn)` builds a strategy that + takes its JWT with each call and has no provider callback. It implements + `CredentialAuthStrategy`, and has no `get_token`. `CredentialPerCall` + stands where its provider would be: pass it to `with_detected_workspace` + or to a builder for the other ways to build one. Both kinds of strategy + use one cache and one exchange. +- An `OidcFederationStrategy` has one source for the JWT of a call. Built + with an `OidcProvider`, it implements `AuthStrategy` and asks the + provider: it has no `get_token_with_credential`, and no other method that + takes a JWT from the caller. Built with `credential_per_call`, it takes + the JWT with the call. Code built on these two traits, such as Stack KMS + and Stack Encrypt, gets this rule from them. +- The constructors of `OidcFederationStrategy`, and + `OidcFederationStrategyBuilder::build`, no longer require the provider + type to be an `OidcProvider`, so that they also build a strategy with + `CredentialPerCall`. ### Fixes diff --git a/packages/stack-auth/src/lib.rs b/packages/stack-auth/src/lib.rs index 11adc7bb85..c5285a11c5 100644 --- a/packages/stack-auth/src/lib.rs +++ b/packages/stack-auth/src/lib.rs @@ -57,6 +57,7 @@ mod auth_strategy_fn; mod clock; mod error; mod service_token; +mod strategy_kind; mod token; mod token_store; mod transport; @@ -117,10 +118,11 @@ pub use auth_strategy_fn::AuthStrategyFn; pub use auto_strategy::{AutoStrategy, AutoStrategyBuilder}; pub use device_session_strategy::{DeviceSessionStrategy, DeviceSessionStrategyBuilder}; pub use oidc_federation_strategy::{OidcFederationStrategy, OidcFederationStrategyBuilder}; -pub use oidc_refresher::{OidcProvider, OidcProviderFn}; +pub use oidc_refresher::{CredentialPerCall, OidcProvider, OidcProviderFn}; pub use service_token::ServiceToken; #[cfg(any(test, feature = "test-utils"))] pub use static_token_strategy::StaticTokenStrategy; +pub use strategy_kind::{OwnIdentity, StrategyKind}; pub use token::Token; pub use token_store::{InMemoryTokenStore, NoStore, TokenStore, TokenStoreFn}; #[cfg(feature = "http")] @@ -179,8 +181,9 @@ pub use cts_common::Crn; /// All items in this module are also re-exported at the crate root. pub mod auth { pub use crate::{ - AccessKey, AuthError, AuthStrategy, AuthStrategyBounds, AuthStrategyFn, HttpRequest, - HttpResponse, HttpTransport, InvalidAccessKey, SecretToken, ServiceToken, + AccessKey, AuthError, AuthStrategy, AuthStrategyBounds, AuthStrategyFn, + CredentialAuthStrategy, HttpRequest, HttpResponse, HttpTransport, InvalidAccessKey, + OwnIdentity, SecretToken, ServiceToken, StrategyKind, }; #[cfg(feature = "http")] @@ -188,8 +191,8 @@ pub mod auth { pub use crate::{ AccessKeyStrategy, AccessKeyStrategyBuilder, AutoStrategy, AutoStrategyBuilder, - DeviceSessionStrategy, DeviceSessionStrategyBuilder, OidcFederationStrategy, - OidcFederationStrategyBuilder, OidcProvider, OidcProviderFn, + CredentialPerCall, DeviceSessionStrategy, DeviceSessionStrategyBuilder, + OidcFederationStrategy, OidcFederationStrategyBuilder, OidcProvider, OidcProviderFn, }; #[cfg(not(target_arch = "wasm32"))] @@ -331,6 +334,82 @@ pub trait AuthStrategy { fn get_token(self) -> impl Future>; } +/// A strategy that issues the token for a credential handed in with the +/// call. +/// +/// [`AuthStrategy::get_token`] takes no argument. A strategy that issues a +/// different token for each caller therefore has to find the caller itself, +/// from a callback and whatever ambient state the callback reads. This trait +/// is the direct route: the caller hands the credential over with the +/// request, and the token it gets back is the one for that credential. +/// +/// The credential is whatever the strategy exchanges for a token. For +/// [`OidcFederationStrategy`] it is a JWT from an identity provider, most +/// often that of the end user who signed in. It can also be the JWT of a +/// service or a job. +/// +/// A strategy implements this trait or [`AuthStrategy`], never both. +/// [`StrategyKind`] holds that: this trait requires the kind +/// [`CredentialPerCall`], and every `AuthStrategy` has the kind +/// [`OwnIdentity`]. A type that implements both does not compile. +/// +/// - A strategy that takes a credential with each call implements this +/// trait. It has no token for a call that brings no credential, so it has +/// no `get_token`. Code that forgets the credential does not compile. +/// [`OidcFederationStrategy::credential_per_call`] builds one. +/// - A strategy with an identity of its own implements [`AuthStrategy`] +/// ([`AccessKeyStrategy`], [`DeviceSessionStrategy`], [`AutoStrategy`], and +/// an [`OidcFederationStrategy`] built with an [`OidcProvider`]). It has +/// no `get_token_with_credential`, so code that passes a credential does +/// not compile against one. A credential is never ignored. +/// +/// Like [`AuthStrategy`], it is implemented for `&T`. +/// +// The example builds a strategy over the bundled HTTP transport, so it is +// in the docs only with `http`. Without it, a strategy is given a transport. +#[cfg_attr( + feature = "http", + doc = r#"# Example + +``` +use stack_auth::{CredentialAuthStrategy, OidcFederationStrategy, SecretToken}; + +# fn main() -> Result<(), Box> { +let crn = "crn:ap-southeast-2.aws:ZVATKW3VHMFG27DY".parse()?; +// Built once, at startup. No request is made. +let strategy = OidcFederationStrategy::credential_per_call(crn)?; + +// A request handler passes the JWT of the user who signed in. Awaiting +// this future exchanges the JWT at the auth server for that user's token. +let jwt = SecretToken::new("header.payload.signature"); +let token = (&strategy).get_token_with_credential(jwt); +# drop(token); +# Ok(()) +# } +```"# +)] +#[cfg(not(target_arch = "wasm32"))] +pub trait CredentialAuthStrategy: StrategyKind + Send { + /// Retrieve a valid access token for `credential`, refreshing or + /// re-authenticating as needed. + fn get_token_with_credential( + self, + credential: SecretToken, + ) -> impl Future> + Send; +} + +/// Wasm32 variant of [`CredentialAuthStrategy`]: drops the `Send` bound, as +/// [`AuthStrategy`] does. +#[cfg(target_arch = "wasm32")] +pub trait CredentialAuthStrategy: StrategyKind { + /// Retrieve a valid access token for `credential`, refreshing or + /// re-authenticating as needed. + fn get_token_with_credential( + self, + credential: SecretToken, + ) -> impl Future>; +} + /// Marker trait alias for the bounds an owned `AuthStrategy`-providing /// credential type `C` must satisfy when held inside a long-lived client /// (e.g. `cipherstash_client::ZeroKMS` shared across requests). diff --git a/packages/stack-auth/src/oidc_federation_strategy.rs b/packages/stack-auth/src/oidc_federation_strategy.rs index 191a4fc793..c02e734c1a 100644 --- a/packages/stack-auth/src/oidc_federation_strategy.rs +++ b/packages/stack-auth/src/oidc_federation_strategy.rs @@ -12,7 +12,10 @@ use crate::oidc_refresher::{JwtDigest, JwtRefresher, OidcFederation, OidcProvide use crate::token_store::{NoStore, TokenStore}; use crate::transport::{self, SharedTransport}; use crate::HttpTransport; -use crate::{ensure_trailing_slash, AuthError, AuthStrategy, SecretToken, ServiceToken, Token}; +use crate::{ + ensure_trailing_slash, AuthError, AuthStrategy, CredentialAuthStrategy, SecretToken, + ServiceToken, Token, +}; use cache::JwtCache; /// How many distinct provider JWTs a strategy keeps a CTS token for unless @@ -34,14 +37,34 @@ pub(crate) const DEFAULT_CACHE_CAPACITY: usize = 1024; /// strategy helps encrypt under a lock context is bound to the identity in /// *that caller's* JWT, not to whichever user federated first. /// +/// A server whose request handlers already hold the JWT needs no provider. +/// It builds the strategy with +/// [`credential_per_call`](OidcFederationStrategy::credential_per_call), and +/// hands the JWT in with each call: +/// [`CredentialAuthStrategy::get_token_with_credential`], which Stack KMS +/// and Stack Encrypt use to make a key request with one caller's credential. +/// +/// A strategy is built one way or the other, and has one source for the +/// JWT of a call: +/// +/// - A strategy with a provider asks the provider. It has no method that +/// takes a JWT from the caller, so the JWT of a call is never one of two. +/// - A strategy built with `credential_per_call` takes the JWT with the +/// call. It has no `get_token`, so a call cannot forget its JWT. +/// +/// This type holds that rule. Code built on it, such as Stack KMS and +/// Stack Encrypt, gets the rule from the two traits and adds no check of +/// its own. +/// /// How the provider names the caller is the host's affair. In Rust it reads /// the caller from whatever carries it (a task-local, a request extension); -/// the Go binding passes the provider the `ctx` of the `Token` call; the -/// JavaScript wrappers call `getJwt` on their own side of the boundary, in -/// the `getToken()` caller's async context, and hand the JWT to -/// [`get_token_for_jwt`](Self::get_token_for_jwt) — because a callback run -/// through a napi `ThreadsafeFunction` would execute in the async context of -/// the call that created the strategy instead, and lose the request. +/// the Go binding passes the provider the `ctx` of the `Token` call. The +/// JavaScript bindings have no provider on the Rust side: they build the +/// strategy with `credential_per_call`, call `getJwt` on their own side of +/// the boundary, in the `getToken()` caller's async context, and hand the +/// JWT in with the call. A callback run through a napi `ThreadsafeFunction` +/// would execute in the async context of the call that created the strategy +/// instead, and lose the request. /// /// The cache is keyed on the whole JWT, never on claims read from it (the /// client cannot verify a JWT, so a forged one naming another user's `sub` @@ -99,6 +122,25 @@ pub(crate) const DEFAULT_CACHE_CAPACITY: usize = 1024; /// }); /// let strategy = OidcFederationStrategy::new(crn, provider).unwrap(); /// ``` +/// +/// A strategy with a provider takes no JWT from the caller. This does not +/// compile: +/// +/// ```compile_fail,E0599 +/// use stack_auth::{ +/// AuthError, CredentialAuthStrategy, OidcFederationStrategy, OidcProviderFn, SecretToken, +/// }; +/// use cts_common::Crn; +/// +/// let crn: Crn = "crn:ap-southeast-2.aws:ZVATKW3VHMFG27DY".parse().unwrap(); +/// let provider = OidcProviderFn::new(|| async { +/// Ok::<_, AuthError>(SecretToken::new("header.payload.signature".to_string())) +/// }); +/// let strategy = OidcFederationStrategy::new(crn, provider).unwrap(); +/// +/// let jwt = SecretToken::new("another.users.jwt".to_string()); +/// let token = (&strategy).get_token_with_credential(jwt); +/// ``` pub struct OidcFederationStrategy { provider: P, federation: Arc, @@ -173,7 +215,10 @@ impl TokenStore for BoundStore { } } -impl OidcFederationStrategy

{ +// No bound on `P`: these constructors also build a strategy with no provider +// ([`CredentialPerCall`](crate::CredentialPerCall)). What a strategy can do +// follows from `P`, in the two trait impls below. +impl

OidcFederationStrategy

{ /// Create a new `OidcFederationStrategy` for the given workspace CRN and /// OIDC provider. /// @@ -297,6 +342,28 @@ impl OidcFederationStrategy

{ } } +impl OidcFederationStrategy { + /// Create an `OidcFederationStrategy` that takes its JWT with each + /// call, and has no provider callback. + /// + /// Use this constructor when the caller holds the JWT, as a request + /// handler holds the JWT of the user who signed in. Each call hands + /// its JWT in + /// ([`CredentialAuthStrategy::get_token_with_credential`](crate::CredentialAuthStrategy::get_token_with_credential)). + /// The strategy has no [`get_token`](AuthStrategy::get_token), so a + /// call that brings no JWT does not compile. + /// + /// The workspace CRN is used as [`new`](Self::new) uses it. This is + /// `new` with [`CredentialPerCall`](crate::CredentialPerCall) where the + /// provider would be, and that type has an example. For the other + /// constructors, such as + /// [`with_detected_workspace`](Self::with_detected_workspace), pass + /// `CredentialPerCall` as the provider. + pub fn credential_per_call(workspace_crn: Crn) -> Result { + Self::new(workspace_crn, crate::CredentialPerCall) + } +} + impl OidcFederationStrategy { /// The refresh engine for `jwt`: the cached one, or a new one over this /// strategy's federation endpoint and store, bound to `jwt`. @@ -448,18 +515,16 @@ impl Drop for InFlight<'_, P, S> { impl OidcFederationStrategy { /// The CTS token for `jwt`: the one cached for it, or a fresh exchange. /// - /// This is [`get_token`](AuthStrategy::get_token) without the provider - /// call — the entry for a caller that already holds the user's JWT. The - /// language bindings use it so the JWT can be fetched on the caller's own - /// side of the boundary: a Node callback run through a napi - /// `ThreadsafeFunction` executes in the async context of the call that - /// created the strategy, not of the `getToken()` caller, so a `getJwt` - /// that reads the request from `AsyncLocalStorage` cannot run there; run - /// from the JavaScript wrapper and handed in here, it can. Both entries - /// share one cache: the same JWT reaches the same engine either way. + /// Private, so that each kind of strategy has one source for `jwt`. + /// A strategy with a provider reaches this from + /// [`get_token`](AuthStrategy::get_token), with the JWT its provider + /// returned. A strategy with no provider reaches it from + /// [`get_token_with_credential`](CredentialAuthStrategy::get_token_with_credential), + /// with the JWT of the call. No caller can hand a JWT to a strategy + /// that has a provider. /// /// The token is checked against the strategy's workspace like every other. - pub async fn get_token_for_jwt(&self, jwt: SecretToken) -> Result { + async fn token_for_jwt(&self, jwt: SecretToken) -> Result { let engine = self.engine_for(jwt)?; let in_flight = InFlight { strategy: self, @@ -486,7 +551,32 @@ impl AuthStrategy for &OidcFederationStrategy crate::StrategyKind for &OidcFederationStrategy { + type Kind = crate::CredentialPerCall; +} + +/// The credential is a provider JWT, and it comes with the call. This is the +/// cache and the exchange that [`get_token`](AuthStrategy::get_token) uses +/// for a strategy with a provider, for the JWT handed in. +/// +/// Only a strategy with no provider has it, and it is the only way to hand +/// a JWT to a strategy. A strategy with a provider would otherwise have two +/// sources for one call's JWT, and a call that forgot its own would be made +/// with the provider's. +impl CredentialAuthStrategy + for &OidcFederationStrategy +{ + async fn get_token_with_credential( + self, + credential: SecretToken, + ) -> Result { + self.token_for_jwt(credential).await } } @@ -603,7 +693,7 @@ impl OidcFederationStrategyBuilder { } } -impl OidcFederationStrategyBuilder { +impl OidcFederationStrategyBuilder { /// Build the [`OidcFederationStrategy`]. /// /// Resolves the base URL in priority order: an explicit [`base_url`] @@ -1547,10 +1637,7 @@ mod tests { } } - fn strategy_over( - cts: &CountingCts, - provider: P, - ) -> OidcFederationStrategyBuilder

{ + fn strategy_over

(cts: &CountingCts, provider: P) -> OidcFederationStrategyBuilder

{ OidcFederationStrategy::builder(crn_with_workspace(WS), provider) .transport(cts.clone()) .base_url("https://cts.example.com/".parse().expect("url")) @@ -1578,59 +1665,43 @@ mod tests { assert_eq!(strategy.pending_jwts(), 0, "promoted into the cache"); } - /// `get_token_for_jwt` is `get_token` minus the provider call, and the two - /// share one cache: each JWT handed in gets its own token, and a JWT the - /// provider later names finds the engine the direct call created (and - /// vice versa), so neither entry exchanges a JWT the other has cached. + /// A strategy with no provider issues the token for the JWT handed in + /// with the call. Two callers interleaved each get their own token, and + /// each JWT is exchanged once. #[tokio::test] - async fn get_token_for_jwt_serves_each_jwt_and_shares_the_cache_with_get_token() { + async fn a_strategy_with_no_provider_issues_the_token_of_the_jwt_handed_in() { let cts = CountingCts::new(); - let (current, calls, provider) = switchable_provider(); - let strategy = strategy_over(&cts, provider).build().expect("builder"); + let strategy = strategy_over(&cts, crate::CredentialPerCall) + .build() + .expect("builder"); - let a = strategy - .get_token_for_jwt(SecretToken::new("jwt-a")) - .await - .expect("A"); - let b = strategy - .get_token_for_jwt(SecretToken::new("jwt-b")) - .await - .expect("B"); - assert_eq!(subject(&a), "CS|jwt-a"); - assert_eq!(subject(&b), "CS|jwt-b"); - assert_eq!(cts.exchanges(), 2); - assert_eq!(strategy.cached_jwts(), 2); - assert_eq!( - calls.load(Ordering::SeqCst), - 0, - "the provider is not consulted when the caller holds the JWT" - ); + for (jwt, expected) in [ + ("jwt-a", "CS|jwt-a"), + ("jwt-b", "CS|jwt-b"), + ("jwt-a", "CS|jwt-a"), + ("jwt-b", "CS|jwt-b"), + ] { + let token = (&strategy) + .get_token_with_credential(SecretToken::new(jwt)) + .await + .expect("the token for this JWT"); + assert_eq!(subject(&token), expected); + } + assert_eq!(cts.exchanges(), 2, "one exchange per JWT"); + } - // The provider path finds the engines the direct calls created ... - act_as(¤t, "jwt-a"); - assert_eq!( - subject(&(&strategy).get_token().await.expect("A via provider")), - "CS|jwt-a" - ); - assert_eq!(cts.exchanges(), 2, "served from the shared cache"); + /// `credential_per_call` builds the strategy from a workspace CRN alone, + /// and makes no request. That a call with no JWT does not compile is + /// shown in the docs of `CredentialPerCall`. + #[cfg(feature = "http")] + #[tokio::test] + async fn credential_per_call_builds_a_strategy_with_no_provider() { + let crn: Crn = format!("crn:ap-southeast-2.aws:{WS}").parse().expect("crn"); + let strategy: OidcFederationStrategy = + OidcFederationStrategy::credential_per_call(crn).expect("no request is made"); - // ... and the direct path finds one the provider path created. - act_as(¤t, "jwt-c"); - assert_eq!( - subject(&(&strategy).get_token().await.expect("C via provider")), - "CS|jwt-c" - ); - assert_eq!( - subject( - &strategy - .get_token_for_jwt(SecretToken::new("jwt-c")) - .await - .expect("C directly") - ), - "CS|jwt-c" - ); - assert_eq!(cts.exchanges(), 3, "C was exchanged once"); - assert_eq!(strategy.cached_jwts(), 3); + assert_eq!(strategy.cached_jwts(), 0); + assert_eq!(strategy.pending_jwts(), 0); } /// A refused exchange leaves nothing in the cache: a caller presenting diff --git a/packages/stack-auth/src/oidc_refresher.rs b/packages/stack-auth/src/oidc_refresher.rs index 779e89d486..9c2ea4572e 100644 --- a/packages/stack-auth/src/oidc_refresher.rs +++ b/packages/stack-auth/src/oidc_refresher.rs @@ -103,6 +103,68 @@ where } } +/// Stands where the [`OidcProvider`] would be, in a strategy that takes its +/// JWT with each call and has no callback to find one. +/// +/// A server that makes each request as the end user who signed in already +/// holds that user's JWT in the request handler. It passes the JWT with the +/// call +/// ([`CredentialAuthStrategy::get_token_with_credential`](crate::CredentialAuthStrategy::get_token_with_credential)). +/// The strategy then needs no callback to find the JWT, and the application +/// needs no task-local variable for a callback to read. +/// +/// You rarely name this type. +/// [`OidcFederationStrategy::credential_per_call`](crate::OidcFederationStrategy::credential_per_call) +/// builds the strategy from a workspace CRN alone. Name the type to use +/// another constructor, such as +/// [`with_detected_workspace`](crate::OidcFederationStrategy::with_detected_workspace). +/// +/// `CredentialPerCall` is not an [`OidcProvider`]. So a strategy built with +/// it has no [`get_token`](crate::AuthStrategy::get_token): a call that +/// brings no JWT does not compile. The strategy never falls back to the JWT +/// of another call. +/// +// The examples build a strategy over the bundled HTTP transport, so they +// are in the docs only with `http`. Without it, a strategy is given a +// transport. +#[cfg_attr( + feature = "http", + doc = r#"# Example + +``` +use stack_auth::{CredentialAuthStrategy, OidcFederationStrategy, SecretToken}; + +# fn main() -> Result<(), Box> { +let crn = "crn:ap-southeast-2.aws:ZVATKW3VHMFG27DY".parse()?; +// Built once, at startup. No request is made, and no JWT is needed. +let strategy = OidcFederationStrategy::credential_per_call(crn)?; + +// A request handler passes the JWT of the user who signed in. +let jwt = SecretToken::new("header.payload.signature"); +let token = (&strategy).get_token_with_credential(jwt); +# drop(token); +# Ok(()) +# } +``` + +A call with no JWT does not compile: + +```compile_fail,E0599 +use stack_auth::{AuthStrategy, OidcFederationStrategy}; + +# fn main() -> Result<(), Box> { +let crn = "crn:ap-southeast-2.aws:ZVATKW3VHMFG27DY".parse()?; +let strategy = OidcFederationStrategy::credential_per_call(crn)?; + +let token = (&strategy).get_token(); +# drop(token); +# Ok(()) +# } +```"# +)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct CredentialPerCall; + /// The identity of a provider JWT inside /// [`OidcFederationStrategy`](crate::OidcFederationStrategy): the SHA-256 of /// the whole token. diff --git a/packages/stack-auth/src/strategy_kind.rs b/packages/stack-auth/src/strategy_kind.rs new file mode 100644 index 0000000000..2ed10b0a43 --- /dev/null +++ b/packages/stack-auth/src/strategy_kind.rs @@ -0,0 +1,134 @@ +//! The two kinds of strategy, and the trait that keeps a type to one of +//! them. +//! +//! This is a module of its own because the crate root re-exports +//! `stack_profile::diagnostic`. There, that name hides the compiler's +//! `#[diagnostic::..]` attributes. + +use crate::AuthStrategy; +// Named in the docs only. +#[cfg(doc)] +use crate::{CredentialAuthStrategy, CredentialPerCall}; + +/// The identity of a strategy, or of a key source, that has one of its own: +/// an access key, a saved login, or a provider that names the caller. +/// +/// Every request it makes is made as that identity, so a call through it +/// takes no credential. It is the [`Kind`](StrategyKind::Kind) of every +/// [`AuthStrategy`]. The other kind is [`CredentialPerCall`]. +/// +/// You rarely name this type. The compiler works it out from the strategy. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OwnIdentity; + +mod kind { + /// The two kinds of strategy, and no other. It is `pub` in a private + /// module, so that it can bound a public associated type and still not + /// be implemented outside this crate. + #[allow(unreachable_pub)] + pub trait Sealed {} + impl Sealed for super::OwnIdentity {} + impl Sealed for crate::CredentialPerCall {} +} + +/// Which of the two kinds a strategy is. +/// +/// A strategy makes every request as itself, or as the caller whose +/// credential comes with the call. It is never both: a strategy that had +/// both would make a call that forgot its credential as itself, and nobody +/// would know. This trait is what stops a type from being both. A type +/// implements it once, so it has one [`Kind`](Self::Kind): +/// +/// - [`OwnIdentity`], for a strategy with an identity of its own. Every +/// [`AuthStrategy`] has this kind already. You do not implement +/// `StrategyKind` for one. +/// - [`CredentialPerCall`], for a strategy that takes a credential with +/// each call. [`CredentialAuthStrategy`] requires this kind, so you +/// implement `StrategyKind` beside it. +/// +/// Code built on a strategy, such as Stack KMS and Stack Encrypt, reads the +/// kind from which of the two traits the strategy has. It adds no rule of +/// its own. +/// +/// # Example +/// +/// A strategy of your own that takes a credential with each call: +/// +/// ``` +/// use stack_auth::{ +/// AuthError, CredentialAuthStrategy, CredentialPerCall, SecretToken, ServiceToken, +/// StrategyKind, +/// }; +/// +/// struct Exchange; +/// +/// impl StrategyKind for &Exchange { +/// type Kind = CredentialPerCall; +/// } +/// +/// impl CredentialAuthStrategy for &Exchange { +/// async fn get_token_with_credential( +/// self, +/// credential: SecretToken, +/// ) -> Result { +/// // A real strategy exchanges `credential` for a token of its own. +/// Ok(ServiceToken::new(credential)) +/// } +/// } +/// +/// # async fn example() -> Result<(), AuthError> { +/// let strategy = Exchange; +/// let token = (&strategy) +/// .get_token_with_credential(SecretToken::new("header.payload.signature")) +/// .await?; +/// # drop(token); +/// # Ok(()) +/// # } +/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(example()).unwrap(); +/// ``` +/// +/// A type that is both kinds does not compile. The second impl collides +/// with the one every `AuthStrategy` has: +/// +/// ```compile_fail,E0119 +/// use stack_auth::{ +/// AuthError, AuthStrategy, CredentialAuthStrategy, CredentialPerCall, SecretToken, +/// ServiceToken, StrategyKind, +/// }; +/// +/// struct Both; +/// +/// impl AuthStrategy for &Both { +/// async fn get_token(self) -> Result { +/// Ok(ServiceToken::new(SecretToken::new("its.own.token"))) +/// } +/// } +/// +/// impl StrategyKind for &Both { +/// type Kind = CredentialPerCall; +/// } +/// +/// impl CredentialAuthStrategy for &Both { +/// async fn get_token_with_credential( +/// self, +/// credential: SecretToken, +/// ) -> Result { +/// Ok(ServiceToken::new(credential)) +/// } +/// } +/// ``` +#[diagnostic::on_unimplemented( + message = "`{Self}` does not say which kind of strategy it is", + label = "this strategy has no `StrategyKind`", + note = "a strategy that takes a credential with each call implements `StrategyKind` with `type Kind = CredentialPerCall`, beside `CredentialAuthStrategy`", + note = "a strategy with an identity of its own implements `AuthStrategy`, which gives it `Kind = OwnIdentity`. It does not implement `CredentialAuthStrategy`" +)] +pub trait StrategyKind { + /// [`OwnIdentity`] or [`CredentialPerCall`]. + type Kind: kind::Sealed; +} + +/// Every [`AuthStrategy`] has an identity of its own. +impl StrategyKind for T { + type Kind = OwnIdentity; +} From 793a11080d777a0fac15866cd210c9ae61cd2b09 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 21 Nov 2026 17:30:39 +1100 Subject: [PATCH 2/3] feat(stack-kms): make key requests with a credential, with `CredentialKeySource` 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. --- packages/stack-kms/CHANGELOG.md | 22 + packages/stack-kms/src/builder.rs | 5 +- packages/stack-kms/src/client.rs | 298 ++++++++++++- .../stack-kms/src/client/test_connection.rs | 18 +- packages/stack-kms/src/key_source.rs | 392 +++++++++++++++++- packages/stack-kms/src/lib.rs | 16 +- 6 files changed, 716 insertions(+), 35 deletions(-) diff --git a/packages/stack-kms/CHANGELOG.md b/packages/stack-kms/CHANGELOG.md index 2edb15020a..e554f75185 100644 --- a/packages/stack-kms/CHANGELOG.md +++ b/packages/stack-kms/CHANGELOG.md @@ -29,6 +29,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `DeterministicSource` (behind `test-support`), a key source whose keys are a function of a seed and the descriptor, for fixtures that hold real sealed bytes. It refuses a wrong context as ZeroKMS does, as `Forbidden`. +- `CredentialKeySource`, a key source that makes each request with a + credential handed in with the call: `generate_keys_with_credential`, + `retrieve_keys_with_credential` and `load_index_key_with_credential`. + ZeroKMS then serves and logs the request as that caller. Re-exports + `SecretToken`, the type of a credential, and `OwnIdentity`, the identity + of a key source that has one of its own. Both are stack-auth's types. +- A key source is one kind or the other. One with an identity of its own + implements `DataKeySource` and `IndexKeySource`. One that takes a + credential with each call implements `CredentialKeySource`, and has no + request without one. So code that forgets a credential does not compile, + and neither does code that passes one to a key source that would ignore + it. `StackKms` is the first kind over a `stack_auth::AuthStrategy`, and + the second over a `stack_auth::CredentialAuthStrategy`, where it has the + inherent methods `generate_keys_with_credential`, + `retrieve_keys_with_credential` and `load_keyset_with_credential` + instead of the plain ones. +- `StackKmsBuilder` and `StackKms::connect` no longer require the auth + strategy to be an `AuthStrategy`, so that they also build a client over + a `CredentialAuthStrategy`. +- `FakeCredentialKeySource` (behind `test-support`), the test double of a + `CredentialKeySource`. It records the credential of each request, and + `credentials_seen()` lists them. `FakeDataKeySource` is unchanged. ### Fixes diff --git a/packages/stack-kms/src/builder.rs b/packages/stack-kms/src/builder.rs index 7d1bca2583..3e9ce42c42 100644 --- a/packages/stack-kms/src/builder.rs +++ b/packages/stack-kms/src/builder.rs @@ -5,7 +5,7 @@ use crate::connection::HttpConnectionOpts; use crate::endpoint::{InvalidEndpoint, ZeroKmsEndpoint}; use crate::key::ClientKey; use crate::key_provider::{KeyProvider, KeyProviderError}; -use stack_auth::{AuthStrategy, AuthStrategyBounds}; +use stack_auth::AuthStrategyBounds; use thiserror::Error; /// Error type for [`StackKmsBuilder`] operations. @@ -125,7 +125,6 @@ impl StackKmsBuilder { impl StackKmsBuilder where C: AuthStrategyBounds, - for<'a> &'a C: AuthStrategy, { /// Create a new [`StackKmsBuilder`]. /// @@ -264,7 +263,6 @@ impl StackKmsBuilder { impl StackKmsBuilder where C: AuthStrategyBounds, - for<'a> &'a C: AuthStrategy, { /// Build a [`StackKms`] client. pub fn build(self) -> Result, StackKmsBuilderError> { @@ -282,7 +280,6 @@ pub struct WithKeyProvider(K); impl StackKmsBuilder> where C: AuthStrategyBounds, - for<'a> &'a C: AuthStrategy, K: KeyProvider, { /// Build a [`StackKms`] client by loading the key from the provider. diff --git a/packages/stack-kms/src/client.rs b/packages/stack-kms/src/client.rs index 6b8d0bc6dc..8a4a1c188a 100644 --- a/packages/stack-kms/src/client.rs +++ b/packages/stack-kms/src/client.rs @@ -7,7 +7,7 @@ use zerokms_protocol::{ }; use recipher::key::Iv; -use stack_auth::{AuthStrategy, AuthStrategyBounds}; +use stack_auth::{AuthStrategy, AuthStrategyBounds, CredentialAuthStrategy, SecretToken}; use vitaminc::random::{Generatable, SafeRand}; #[cfg(feature = "http")] @@ -426,7 +426,6 @@ pub struct StackKms { impl StackKms where C: AuthStrategyBounds, - for<'a> &'a C: AuthStrategy, Conn: ZeroKMSConnection + Send + Sync, { /// Build a client over an explicit transport. @@ -456,11 +455,10 @@ where }) } - /// Fetch a token from the credentials provider and ensure the ZeroKMS base - /// URL has been resolved on the connection (from the token's `services` - /// claim). The URL is only resolved once; subsequent calls skip resolution. - async fn get_token(&self) -> Result { - let token = (&self.credentials).get_token().await?; + /// Ensure the ZeroKMS base URL has been resolved on the connection, from + /// `token`'s `services` claim. Resolved once: every token of a workspace + /// names the same endpoint, whichever caller it was issued for. + fn resolve_endpoint(&self, token: &stack_auth::ServiceToken) -> Result<(), Error> { if !self.client.connection().has_base_url() { let endpoint = crate::endpoint::ZeroKmsEndpoint::try_from(token.zerokms_url()?)?; tracing::debug!( @@ -470,13 +468,38 @@ where ); self.client.connection().ensure_base_url(endpoint); } - Ok(token) + Ok(()) } /// The [`ClientKey`] this client uses to derive data keys. pub fn client_key(&self) -> &ClientKey { &self.client_key } +} + +/// Key requests made as the auth strategy's own identity +/// ([`AuthStrategy`]): an access key, a saved login, or the caller that an +/// [`OidcFederationStrategy`]'s provider names. +/// +/// A client over a strategy that takes a credential with each call has none +/// of these methods, so a request cannot be made without one. It has the +/// `_with_credential` methods instead. +/// +/// [`OidcFederationStrategy`]: stack_auth::OidcFederationStrategy +impl StackKms +where + C: AuthStrategyBounds, + for<'a> &'a C: AuthStrategy, + Conn: ZeroKMSConnection + Send + Sync, +{ + /// Fetch a token from the credentials provider and ensure the ZeroKMS base + /// URL has been resolved on the connection (from the token's `services` + /// claim). The URL is only resolved once; subsequent calls skip resolution. + async fn get_token(&self) -> Result { + let token = (&self.credentials).get_token().await?; + self.resolve_endpoint(&token)?; + Ok(token) + } /// Generate multiple data keys for an iterator of [`GenerateKeyPayload`]. pub async fn generate_keys<'a>( @@ -564,6 +587,102 @@ where } } +/// Key requests made with a credential that comes with the call, for an auth +/// strategy that issues a token per credential +/// ([`CredentialAuthStrategy`]): an [`OidcFederationStrategy`] built with +/// `credential_per_call`, whose credential is the JWT of an end user. Each +/// method is its plain counterpart with one difference: the access token is +/// the one the strategy issues for `credential`, so ZeroKMS serves and logs +/// the request as that caller. +/// +/// A client whose strategy has an identity of its own has none of these +/// methods, so a credential is never dropped on the way to a request. +/// +/// [`OidcFederationStrategy`]: stack_auth::OidcFederationStrategy +impl StackKms +where + C: AuthStrategyBounds, + for<'a> &'a C: CredentialAuthStrategy, + Conn: ZeroKMSConnection + Send + Sync, +{ + /// The access token the strategy issues for `credential`, with the + /// ZeroKMS endpoint resolved from it on first use. + async fn get_token_with_credential( + &self, + credential: &SecretToken, + ) -> Result { + // The strategy takes the credential by value, and keys its cache on + // it. The copy wipes itself when the strategy drops it. + let token = (&self.credentials) + .get_token_with_credential(credential.clone()) + .await?; + self.resolve_endpoint(&token)?; + Ok(token) + } + + /// [`generate_keys`](Self::generate_keys), made with `credential`. + pub async fn generate_keys_with_credential<'a>( + &self, + credential: &SecretToken, + payloads: impl IntoIterator>, + keyset_id: Option, + unverified_context: Option>, + ) -> Result, Error> { + let token = self.get_token_with_credential(credential).await?; + + self.client + .generate_keys( + payloads, + &self.client_key, + keyset_id, + token.as_str(), + unverified_context, + ) + .await + .map_err(Error::from) + } + + /// [`retrieve_keys`](Self::retrieve_keys), made with `credential`. + pub async fn retrieve_keys_with_credential( + &self, + credential: &SecretToken, + payloads: impl IntoIterator>, + keyset_id: Option, + unverified_context: Option<&UnverifiedContext>, + ) -> Result, Error> { + let token = self.get_token_with_credential(credential).await?; + + self.client + .retrieve_keys( + payloads, + &self.client_key, + keyset_id, + token.as_str(), + unverified_context, + ) + .await + .map_err(Error::from) + } + + /// [`load_keyset`](Self::load_keyset), made with `credential`. + pub async fn load_keyset_with_credential( + &self, + credential: &SecretToken, + keyset_id: Option, + ) -> Result<(Keyset, IndexKey), Error> { + let token = self.get_token_with_credential(credential).await?; + + let (keyset, index_key) = self + .client + .load_keyset(&self.client_key, keyset_id, token.as_str()) + .await?; + + tracing::debug!(target: "stack_kms::load_keyset", "loaded keyset: [{}]({})", keyset.id, keyset.name); + + Ok((keyset, index_key)) + } +} + #[cfg(test)] mod test_connection; @@ -708,6 +827,169 @@ mod tests { } } + /// Key requests that carry a credential: the access token on each + /// request is the one the strategy issued for that request's credential. + mod with_credential { + use super::*; + use crate::key_source::CredentialKeySource; + use stack_auth::{ + AuthError, CredentialAuthStrategy, CredentialPerCall, SecretToken, ServiceToken, + StrategyKind, + }; + use std::sync::Mutex; + + /// A strategy with no identity of its own. It issues a token that + /// names the credential it was handed, and records each credential. + #[derive(Default)] + struct PerCredential { + asked_for: Mutex>, + } + + impl PerCredential { + fn asked_for(&self) -> Vec { + self.asked_for.lock().unwrap().clone() + } + } + + impl StrategyKind for &PerCredential { + type Kind = CredentialPerCall; + } + + impl CredentialAuthStrategy for &PerCredential { + async fn get_token_with_credential( + self, + credential: SecretToken, + ) -> Result { + self.asked_for + .lock() + .unwrap() + .push(credential.as_str().to_string()); + Ok(ServiceToken::new(SecretToken::new(format!( + "token-for-{}", + credential.as_str() + )))) + } + } + + fn load_keyset_response() -> LoadKeysetResponse { + LoadKeysetResponse { + partial_index_key: RetrievedKey { + key_material: key_material(), + }, + keyset: Keyset { + id: uuid!("11111111-1111-1111-1111-111111111111"), + name: "default".to_string(), + description: String::new(), + is_disabled: false, + is_default: true, + }, + } + } + + fn kms(builder: TestConnectionBuilder) -> StackKms { + StackKms::connect( + ClientOpts::new(builder), + PerCredential::default(), + random_client_key(), + ) + .expect("connect over a test connection") + } + + fn credential(name: &str) -> SecretToken { + SecretToken::new(name) + } + + /// Two callers interleaved on one client. Every kind of key request + /// goes out under the token of the credential it was made with. + #[tokio::test] + async fn each_request_is_sent_with_the_token_of_its_own_credential() { + let kms = kms(TestConnectionBuilder::new() + .add_success_response::(load_keyset_response()) + .add_success_response::(GenerateKeyResponse { + keys: vec![generated_key(vec![1])], + }) + .add_success_response::(RetrieveKeyResponse { + keys: vec![RetrievedKey { + key_material: key_material(), + }], + }) + .add_success_response::(GenerateKeyResponse { + keys: vec![generated_key(vec![2])], + }) + .add_success_response::(RetrieveKeyResponse { + keys: vec![RetrievedKey { + key_material: key_material(), + }], + })); + let (alice, bob) = (credential("alice"), credential("bob")); + let generate = || vec![GenerateKeyPayload::new("a", Cow::Owned(vec![]))]; + let retrieve = || vec![RetrieveKeyPayload::new(Iv::default(), "a", &[1])]; + + // Through the trait, as Stack Encrypt calls it. + let _ = kms + .load_index_key_with_credential(&alice, None) + .await + .expect("alice loads the keyset"); + let _ = CredentialKeySource::generate_keys_with_credential( + &kms, + &bob, + generate(), + None, + None, + ) + .await + .expect("bob generates"); + let _ = CredentialKeySource::retrieve_keys_with_credential( + &kms, + &alice, + retrieve(), + None, + None, + ) + .await + .expect("alice retrieves"); + let _ = CredentialKeySource::generate_keys_with_credential( + &kms, + &alice, + generate(), + None, + None, + ) + .await + .expect("alice generates"); + let _ = CredentialKeySource::retrieve_keys_with_credential( + &kms, + &bob, + retrieve(), + None, + None, + ) + .await + .expect("bob retrieves"); + + let sent = kms.client.connection().sent().await; + let sent: Vec<(&str, &str)> = sent + .iter() + .map(|(endpoint, token)| (endpoint.as_str(), token.as_str())) + .collect(); + assert_eq!( + sent, + vec![ + (LoadKeysetRequest::ENDPOINT, "token-for-alice"), + (GenerateKeyRequest::ENDPOINT, "token-for-bob"), + (RetrieveKeyRequest::ENDPOINT, "token-for-alice"), + (GenerateKeyRequest::ENDPOINT, "token-for-alice"), + (RetrieveKeyRequest::ENDPOINT, "token-for-bob"), + ] + ); + assert_eq!( + kms.credentials.asked_for(), + ["alice", "bob", "alice", "alice", "bob"], + "the strategy is asked once per request, for that request's credential" + ); + } + } + mod count_mismatch { use super::*; diff --git a/packages/stack-kms/src/client/test_connection.rs b/packages/stack-kms/src/client/test_connection.rs index 17560b4719..5647d3843c 100644 --- a/packages/stack-kms/src/client/test_connection.rs +++ b/packages/stack-kms/src/client/test_connection.rs @@ -67,6 +67,7 @@ impl TestConnectionBuilder { TestConnection { handlers: Mutex::new(self.handlers), effects: Mutex::new(self.effects), + sent: Mutex::new(Vec::new()), } } } @@ -80,6 +81,16 @@ impl Default for TestConnectionBuilder { pub(crate) struct TestConnection { handlers: Mutex, effects: Mutex, + /// The endpoint and the access token of every request sent, in order. + sent: Mutex>, +} + +impl TestConnection { + /// The endpoint and the access token of every request sent so far, in + /// the order they were sent. + pub(crate) async fn sent(&self) -> Vec<(String, String)> { + self.sent.lock().await.clone() + } } impl ZeroKMSConnectionInit for TestConnection { @@ -98,10 +109,15 @@ impl ZeroKMSConnection for TestConnection { async fn send( &self, request: Request, - _access_token: &str, + access_token: &str, ) -> Result { let endpoint = Request::ENDPOINT; + self.sent + .lock() + .await + .push((endpoint.to_string(), access_token.to_string())); + let mut effect_guard = self.effects.lock().await; let effect_position = effect_guard.iter().position(|(x, _)| x == endpoint); diff --git a/packages/stack-kms/src/key_source.rs b/packages/stack-kms/src/key_source.rs index 844301eadb..757034587d 100644 --- a/packages/stack-kms/src/key_source.rs +++ b/packages/stack-kms/src/key_source.rs @@ -10,6 +10,7 @@ use std::borrow::Cow; use std::future::Future; +use stack_auth::SecretToken; use uuid::Uuid; use zerokms_protocol::{IdentifiedBy, UnverifiedContext}; @@ -28,6 +29,16 @@ use crate::payload::{GenerateKeyPayload, RetrieveKeyPayload}; /// The returned futures are bounded by [`MaybeSend`]: `Send` on native targets /// so callers can drive them on a multi-threaded runtime, unbounded on wasm32 /// (see [`MaybeSend`] for why). +/// +/// A source that implements this trait has an identity of its own, and +/// makes every request as that identity. A source that takes a credential +/// with each call implements [`CredentialKeySource`] instead, and not this +/// trait. +#[diagnostic::on_unimplemented( + message = "`{Self}` is not a key source with an identity of its own", + label = "this makes a key request with no credential", + note = "if `{Self}` takes a credential with each call (`CredentialKeySource`), pass one: in Stack Encrypt, call `.with_credential(..)` before `.await`" +)] pub trait DataKeySource { /// Generate one fresh data key per payload, in payload order. fn generate_keys( @@ -56,7 +67,13 @@ pub trait DataKeySource { /// separately: record encryption needs data keys, term generation needs the /// index key. Production implementations provide both. /// -/// As with [`DataKeySource`], the returned future is bounded by [`MaybeSend`]. +/// As with [`DataKeySource`], the returned future is bounded by [`MaybeSend`], +/// and a source that implements this trait has an identity of its own. +#[diagnostic::on_unimplemented( + message = "`{Self}` is not a key source with an identity of its own", + label = "this loads a keyset with no credential", + note = "if `{Self}` takes a credential with each call (`CredentialKeySource`), pass one: in Stack Encrypt, call `.with_credential(..)` before `.await`" +)] pub trait IndexKeySource { /// Load the index key for a keyset — identified by id or name, or the /// client's default keyset when `keyset_id` is `None`. Returns the @@ -72,6 +89,70 @@ pub trait IndexKeySource { ) -> impl Future> + MaybeSend; } +/// A key source that makes each request with a credential that comes with +/// the call, so ZeroKMS serves and logs the request as that caller. +/// +/// The credential is whatever the source's auth strategy exchanges for an +/// access token. For [`StackKms`](crate::StackKms) over an +/// [`OidcFederationStrategy`](stack_auth::OidcFederationStrategy) built +/// with `credential_per_call`, it is the JWT of an end user. One long-lived +/// source then serves every caller, and each request says which caller it +/// is for. +/// +/// Each method is the one of [`DataKeySource`] or [`IndexKeySource`] with +/// `credential` added. An implementation must make the request with that +/// credential, or fail. It must never fall back to another identity. +/// +/// A key source is one kind or the other, never both: +/// +/// - A source with an identity of its own (an access key, a saved login) +/// implements [`DataKeySource`] and [`IndexKeySource`], and not this +/// trait. Code that passes a credential does not compile against it, so +/// a credential is never ignored. +/// - A source that takes a credential with each call implements this +/// trait, and not the other two. Code that makes a request with no +/// credential does not compile against it, so a credential is never +/// forgotten. +/// +/// [`StackKms`](crate::StackKms) is the first kind over a +/// [`stack_auth::AuthStrategy`], and the second over a +/// [`stack_auth::CredentialAuthStrategy`]. A strategy is one of the two and +/// never both ([`stack_auth::StrategyKind`]), so a `StackKms` is one kind. +/// +/// As with [`DataKeySource`], the returned futures are bounded by +/// [`MaybeSend`]. +#[diagnostic::on_unimplemented( + message = "`{Self}` does not take a credential with each call", + label = "this passes a credential to a key source that has an identity of its own", + note = "a key source with an identity of its own makes every request as that identity. To make each request as its caller, build the key source over an auth strategy that takes a credential with each call, such as `OidcFederationStrategy::credential_per_call`" +)] +pub trait CredentialKeySource { + /// [`DataKeySource::generate_keys`], made with `credential`. + fn generate_keys_with_credential( + &self, + credential: &SecretToken, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option>, + ) -> impl Future, Error>> + MaybeSend; + + /// [`DataKeySource::retrieve_keys`], made with `credential`. + fn retrieve_keys_with_credential( + &self, + credential: &SecretToken, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option<&UnverifiedContext>, + ) -> impl Future, Error>> + MaybeSend; + + /// [`IndexKeySource::load_index_key`], made with `credential`. + fn load_index_key_with_credential( + &self, + credential: &SecretToken, + keyset_id: Option, + ) -> impl Future> + MaybeSend; +} + impl DataKeySource for crate::StackKms where C: stack_auth::AuthStrategyBounds, @@ -114,6 +195,59 @@ where } } +impl CredentialKeySource for crate::StackKms +where + C: stack_auth::AuthStrategyBounds, + for<'a> &'a C: stack_auth::CredentialAuthStrategy, + Conn: crate::ZeroKMSConnection + Send + Sync, +{ + async fn generate_keys_with_credential( + &self, + credential: &SecretToken, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option>, + ) -> Result, Error> { + // The inherent method of the same name, which takes `impl IntoIterator`. + crate::StackKms::generate_keys_with_credential( + self, + credential, + payloads, + keyset_id, + unverified_context, + ) + .await + } + + async fn retrieve_keys_with_credential( + &self, + credential: &SecretToken, + payloads: Vec>, + keyset_id: Option, + unverified_context: Option<&UnverifiedContext>, + ) -> Result, Error> { + crate::StackKms::retrieve_keys_with_credential( + self, + credential, + payloads, + keyset_id, + unverified_context, + ) + .await + } + + async fn load_index_key_with_credential( + &self, + credential: &SecretToken, + keyset_id: Option, + ) -> Result<(Uuid, IndexKey), Error> { + let (keyset, index_key) = self + .load_keyset_with_credential(credential, keyset_id) + .await?; + Ok((keyset.id, index_key)) + } +} + #[cfg(feature = "test-support")] mod fake { use super::*; @@ -150,11 +284,25 @@ mod fake { /// independently built stubs agree — search terms generated by one cipher /// must match terms generated by another, and known-answer tests can pin /// term bytes. That is plain determinism, not ZeroKMS's derivation. - #[derive(Debug, Default)] + /// + /// This stub has an identity of its own: no request takes a credential. + /// [`FakeCredentialKeySource`] is the stub that takes one with each + /// call. + #[derive(Default)] pub struct FakeDataKeySource { keys: Mutex), Key>>, } + /// The number of keys held. The keys are key material, so they are not + /// printed. + impl std::fmt::Debug for FakeDataKeySource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FakeDataKeySource") + .field("keys", &self.len()) + .finish() + } + } + /// UUID namespace for name resolution: `Uuid::new_v5` mints deterministic, /// RFC 4122-valid UUIDs that strict validation downstream accepts. const KEYSET_NAME_NAMESPACE: Uuid = Uuid::from_u128(0x8ff8_1a03_4b2d_4f0b_9d6e_5a1c_3f7e_2b41); @@ -195,11 +343,9 @@ mod fake { Ok(Generatable::random(rng).map_err(GenerateKeyError::GenerateIv)?) } - impl IndexKeySource for FakeDataKeySource { - async fn load_index_key( - &self, - keyset_id: Option, - ) -> Result<(Uuid, IndexKey), Error> { + impl FakeDataKeySource { + /// The index key of `keyset_id`, whoever asks. + fn index_key(&self, keyset_id: Option) -> (Uuid, IndexKey) { let resolved = match keyset_id { None => Uuid::nil(), Some(IdentifiedBy::Uuid(id)) => id, @@ -216,16 +362,13 @@ mod fake { hasher.update(b"stack-kms::FakeDataKeySource::index-key::v1"); hasher.update(resolved.as_bytes()); let key: Key = hasher.finalize().into(); - Ok((resolved, IndexKey::from(key))) + (resolved, IndexKey::from(key)) } - } - impl DataKeySource for FakeDataKeySource { - async fn generate_keys( + /// One fresh key for each payload, remembered, whoever asks. + fn generate( &self, payloads: Vec>, - _keyset_id: Option, - _unverified_context: Option>, ) -> Result, Error> { let mut rng = SafeRand::from_entropy().map_err(GenerateKeyError::GenerateIv)?; let mut keys = self.lock(); @@ -245,12 +388,8 @@ mod fake { .collect() } - async fn retrieve_keys( - &self, - payloads: Vec>, - _keyset_id: Option, - _unverified_context: Option<&UnverifiedContext>, - ) -> Result, Error> { + /// The remembered key of each payload, whoever asks. + fn retrieve(&self, payloads: Vec>) -> Result, Error> { let keys = self.lock(); payloads .iter() @@ -267,10 +406,165 @@ mod fake { .collect() } } + + impl IndexKeySource for FakeDataKeySource { + async fn load_index_key( + &self, + keyset_id: Option, + ) -> Result<(Uuid, IndexKey), Error> { + Ok(self.index_key(keyset_id)) + } + } + + impl DataKeySource for FakeDataKeySource { + async fn generate_keys( + &self, + payloads: Vec>, + _keyset_id: Option, + _unverified_context: Option>, + ) -> Result, Error> { + self.generate(payloads) + } + + async fn retrieve_keys( + &self, + payloads: Vec>, + _keyset_id: Option, + _unverified_context: Option<&UnverifiedContext>, + ) -> Result, Error> { + self.retrieve(payloads) + } + } + + /// An in-memory stub [`CredentialKeySource`], for tests and examples of + /// code that makes each key request as its caller. + /// + /// It is [`FakeDataKeySource`] with a credential on every request: it + /// generates, retrieves and loads as that stub does, takes any + /// credential, and records it. + /// [`credentials_seen`](Self::credentials_seen) lists the credential of + /// each request, in order. A test of a request handler reads the list + /// to check that the handler's key requests carried its own caller's + /// credential. + /// + /// Like every [`CredentialKeySource`], it has no request without a + /// credential. A test of a request handler built on it does not + /// compile if the handler makes a key request without one. + /// + /// The stub exchanges nothing and refuses no credential, so it says + /// nothing about whether ZeroKMS would accept one. Its index keys are + /// those of [`FakeDataKeySource`], so the terms of one stub match the + /// terms of the other. + /// + /// # Example + /// + /// ``` + /// use stack_kms::{CredentialKeySource, FakeCredentialKeySource, SecretToken}; + /// + /// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async { + /// let source = FakeCredentialKeySource::new(); + /// let alice = SecretToken::new("alice.jwt"); + /// + /// let (keyset_id, _index_key) = source.load_index_key_with_credential(&alice, None).await?; + /// assert!(keyset_id.is_nil(), "the stub's default keyset"); + /// assert_eq!(source.credentials_seen(), ["alice.jwt"]); + /// # Ok::<(), stack_kms::Error>(()) + /// # }).unwrap(); + /// ``` + /// + /// A request with no credential does not compile: + /// + /// ```compile_fail,E0599 + /// use stack_kms::{FakeCredentialKeySource, IndexKeySource}; + /// + /// let source = FakeCredentialKeySource::new(); + /// let _ = source.load_index_key(None); + /// ``` + #[derive(Default)] + pub struct FakeCredentialKeySource { + keys: FakeDataKeySource, + /// The credential of each request, in order. + credentials: Mutex>, + } + + /// The number of keys held, and of credentials seen. The keys are key + /// material and the credentials are secrets, so neither is printed. + impl std::fmt::Debug for FakeCredentialKeySource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("FakeCredentialKeySource") + .field("keys", &self.len()) + .field("credentials_seen", &lock(&self.credentials).len()) + .finish() + } + } + + impl FakeCredentialKeySource { + pub fn new() -> Self { + Self::default() + } + + /// Number of keys generated so far and available to retrieve. + pub fn len(&self) -> usize { + self.keys.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// The credential of each request, in the order the requests were + /// made. + /// + /// The credentials are returned as plain strings so that a test can + /// compare them. Use test values, never a real credential. + pub fn credentials_seen(&self) -> Vec { + lock(&self.credentials) + .iter() + .map(|credential| credential.as_str().to_string()) + .collect() + } + + fn saw(&self, credential: &SecretToken) { + lock(&self.credentials).push(credential.clone()); + } + } + + impl CredentialKeySource for FakeCredentialKeySource { + async fn generate_keys_with_credential( + &self, + credential: &SecretToken, + payloads: Vec>, + _keyset_id: Option, + _unverified_context: Option>, + ) -> Result, Error> { + self.saw(credential); + self.keys.generate(payloads) + } + + async fn retrieve_keys_with_credential( + &self, + credential: &SecretToken, + payloads: Vec>, + _keyset_id: Option, + _unverified_context: Option<&UnverifiedContext>, + ) -> Result, Error> { + self.saw(credential); + self.keys.retrieve(payloads) + } + + async fn load_index_key_with_credential( + &self, + credential: &SecretToken, + keyset_id: Option, + ) -> Result<(Uuid, IndexKey), Error> { + self.saw(credential); + Ok(self.keys.index_key(keyset_id)) + } + } } #[cfg(feature = "test-support")] -pub use fake::FakeDataKeySource; +pub use fake::{FakeCredentialKeySource, FakeDataKeySource}; /// The deterministic test source: every key derives from a seed and the /// descriptor, so a record sealed in one process opens in another built from @@ -461,6 +755,64 @@ mod tests { } } + /// The credential stub records the credential of each request, in + /// order, round-trips a key between two callers, agrees with the plain + /// stub on a keyset's index key, and keeps keys and credentials out of + /// `Debug`. + #[tokio::test] + async fn the_credential_fake_records_the_credential_of_each_request() { + let src = FakeCredentialKeySource::new(); + let (alice, bob) = (SecretToken::new("alice.jwt"), SecretToken::new("bob.jwt")); + assert!(src.is_empty()); + assert!(src.credentials_seen().is_empty()); + + let (default, index_key) = src + .load_index_key_with_credential(&alice, None) + .await + .unwrap(); + let (plain_default, plain_index_key) = + FakeDataKeySource::new().load_index_key(None).await.unwrap(); + assert_eq!(default, plain_default); + assert_eq!(index_key.key(), plain_index_key.key()); + + let generated = src + .generate_keys_with_credential( + &bob, + vec![GenerateKeyPayload::new("users/email", Cow::Owned(vec![]))], + None, + None, + ) + .await + .unwrap() + .remove(0); + assert_eq!(src.len(), 1); + assert!(!src.is_empty()); + let retrieved = src + .retrieve_keys_with_credential( + &alice, + vec![RetrieveKeyPayload::new( + generated.key.iv, + "users/email", + &generated.tag, + )], + None, + None, + ) + .await + .unwrap() + .remove(0); + assert_eq!(retrieved.key(), generated.key.key()); + + assert_eq!( + src.credentials_seen(), + ["alice.jwt", "bob.jwt", "alice.jwt"] + ); + let debug = format!("{src:?}"); + assert!(debug.contains("keys: 1"), "{debug}"); + assert!(debug.contains("credentials_seen: 3"), "{debug}"); + assert!(!debug.contains("alice.jwt"), "{debug}"); + } + /// The deterministic source refuses a key retrieved under another /// descriptor the way ZeroKMS does, as a forbidden request, so the Go /// hermetic suite and the live suite assert one error for a wrong diff --git a/packages/stack-kms/src/lib.rs b/packages/stack-kms/src/lib.rs index 84d5741891..2258eed3f3 100644 --- a/packages/stack-kms/src/lib.rs +++ b/packages/stack-kms/src/lib.rs @@ -128,15 +128,27 @@ pub use errors::{ /// `stack-kms` and `stack-encrypt`. pub use stack_auth::{diagnostic, ErrorPayload}; +/// The type of a credential that comes with a call +/// ([`CredentialKeySource`]): a secret string, wiped when it is dropped and +/// hidden from `Debug`. Re-exported so that a caller needs no direct +/// dependency on `stack-auth` to pass one. +pub use stack_auth::SecretToken; + +/// The identity of a key source that has one of its own +/// ([`DataKeySource`] and [`IndexKeySource`]). It is stack-auth's type, for +/// a strategy of that kind, re-exported so that code generic over the two +/// kinds of key source needs no direct dependency on `stack-auth`. +pub use stack_auth::OwnIdentity; + // Key material pub use key::{ClientKey, DataKey, DataKeyWithTag, IndexKey, V1KeySet}; // Key source abstractions (production = `StackKms`; tests = `FakeDataKeySource`) #[cfg(feature = "test-support")] pub use key_source::DeterministicSource; +pub use key_source::{CredentialKeySource, DataKeySource, IndexKeySource}; #[cfg(feature = "test-support")] -pub use key_source::FakeDataKeySource; -pub use key_source::{DataKeySource, IndexKeySource}; +pub use key_source::{FakeCredentialKeySource, FakeDataKeySource}; // Key providers #[cfg(all(feature = "profile", not(target_arch = "wasm32")))] From 01562493e4af0a091b3b456accd819736084fef4 Mon Sep 17 00:00:00 2001 From: Dan Draper Date: Sat, 21 Nov 2026 17:30:39 +1100 Subject: [PATCH 3/3] feat(stack-encrypt)!: attach a credential to a call, and load a keyset 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`), 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`. 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. --- .cargo/mutants.toml | 4 +- languages/golang/encrypt/guest/src/abi.rs | 54 +- languages/golang/encrypt/guest/src/ops.rs | 17 +- languages/golang/encrypt/guest/src/options.rs | 19 +- languages/golang/encrypt/guest/src/status.rs | 2 +- languages/golang/encrypt/guest/tests/leak.rs | 15 +- .../golang/encrypt/guest/tests/native_ops.rs | 15 +- .../eql/tests/encryption/tests/targets.rs | 4 +- packages/stack-encrypt/CHANGELOG.md | 114 ++ packages/stack-encrypt/CONTEXT.md | 54 +- packages/stack-encrypt/Cargo.toml | 5 +- .../stack-encrypt/examples/search_terms.rs | 2 +- .../stack-encrypt/examples/zerokms_auth.rs | 2 +- packages/stack-encrypt/src/audit.rs | 9 + packages/stack-encrypt/src/cipher.rs | 571 ++++-- packages/stack-encrypt/src/credential.rs | 420 +++++ .../stack-encrypt/src/dynamic/json_query.rs | 40 +- packages/stack-encrypt/src/dynamic/query.rs | 4 +- packages/stack-encrypt/src/dynamic/record.rs | 75 +- packages/stack-encrypt/src/dynamic/target.rs | 2 +- packages/stack-encrypt/src/json/derive.rs | 191 +- packages/stack-encrypt/src/json/inputs.rs | 99 +- packages/stack-encrypt/src/keyset.rs | 480 ++++- packages/stack-encrypt/src/lib.rs | 80 +- packages/stack-encrypt/src/sem/mod.rs | 163 +- packages/stack-encrypt/src/target/core.rs | 27 +- packages/stack-encrypt/src/target/mod.rs | 1 + .../stack-encrypt/src/target/operations.rs | 22 +- packages/stack-encrypt/src/target/pending.rs | 1444 ++++++++++++--- packages/stack-encrypt/src/target/request.rs | 44 +- packages/stack-encrypt/tests/audit.rs | 5 +- packages/stack-encrypt/tests/collections.rs | 5 +- packages/stack-encrypt/tests/combinators.rs | 21 +- packages/stack-encrypt/tests/credential.rs | 1544 +++++++++++++++++ packages/stack-encrypt/tests/heap_hygiene.rs | 74 + packages/stack-encrypt/tests/index.rs | 10 +- packages/stack-encrypt/tests/json_index.rs | 5 +- .../stack-encrypt/tests/json_operators.rs | 452 ++++- packages/stack-encrypt/tests/keysets.rs | 267 ++- packages/stack-encrypt/tests/op.rs | 5 +- .../stack-encrypt/tests/query_operators.rs | 2 +- .../stack-encrypt/tests/record_lowering.rs | 14 +- packages/stack-encrypt/tests/scalar.rs | 10 +- packages/stack-encrypt/tests/sem_terms.rs | 15 +- packages/stack-encrypt/tests/stored_rows.rs | 9 +- packages/stack-encrypt/tests/target.rs | 27 +- .../tests/ui/call_with_no_credential.rs | 40 + .../tests/ui/call_with_no_credential.stderr | 109 ++ ...ntial_on_a_source_with_its_own_identity.rs | 30 + ...l_on_a_source_with_its_own_identity.stderr | 43 + .../tests/ui/foreign_cipher_ref.rs | 6 +- .../tests/ui/foreign_cipher_ref.stderr | 30 +- .../tests/ui/pass/oidc_strategies.rs | 66 + packages/stack-encrypt/tests/value_kinds.rs | 7 +- 54 files changed, 5929 insertions(+), 846 deletions(-) create mode 100644 packages/stack-encrypt/src/credential.rs create mode 100644 packages/stack-encrypt/tests/credential.rs create mode 100644 packages/stack-encrypt/tests/ui/call_with_no_credential.rs create mode 100644 packages/stack-encrypt/tests/ui/call_with_no_credential.stderr create mode 100644 packages/stack-encrypt/tests/ui/credential_on_a_source_with_its_own_identity.rs create mode 100644 packages/stack-encrypt/tests/ui/credential_on_a_source_with_its_own_identity.stderr create mode 100644 packages/stack-encrypt/tests/ui/pass/oidc_strategies.rs diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index eb07653982..e0b85a8b93 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -57,7 +57,7 @@ exclude_globs = ["packages/stack-encrypt-derive/**"] # mutant does not compile, because `AutoStrategy` has no `Default`. So the # entry excludes no mutant that a test could catch. # -# The two wasm32 `into_future` entries in `pending.rs` match any line for the +# The four wasm32 `into_future` entries in `pending.rs` match any line for the # same reason. The future that a native `into_future` returns has no # `Default`, so the native mutant does not compile. exclude_re = [ @@ -80,6 +80,8 @@ exclude_re = [ 'stack-encrypt/src/cipher\.rs:\d+:\d+: replace client_key_provider -> EnvKeyProvider with Default::default\(\)$', 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace >::into_future -> Self::IntoFuture with Default::default\(\)$', 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace >>::into_future -> Self::IntoFuture with Default::default\(\)$', + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace >>::into_future -> Self::IntoFuture with Default::default\(\)$', + 'stack-encrypt/src/target/pending\.rs:\d+:\d+: replace >>>::into_future -> Self::IntoFuture with Default::default\(\)$', # stack-encrypt — equivalent. # An operator and an index are unit structs, whose `Default` is the value # `clone` and `case_sensitive` already return. diff --git a/languages/golang/encrypt/guest/src/abi.rs b/languages/golang/encrypt/guest/src/abi.rs index 09fa1f37ca..22deb2d323 100644 --- a/languages/golang/encrypt/guest/src/abi.rs +++ b/languages/golang/encrypt/guest/src/abi.rs @@ -100,7 +100,7 @@ use stack_guest_abi::step::{self, Operation, Step}; use crate::io; use crate::ops::{self, Bytes}; -use crate::options::{parse_options, parse_selector, scope_for, KeysetSelector, Side}; +use crate::options::{cipher_ref_for, parse_options, parse_selector, KeysetSelector, Side}; #[cfg(not(feature = "deterministic-kms"))] use crate::status::STATUS_INTERNAL; #[cfg(not(feature = "deterministic-kms"))] @@ -256,12 +256,12 @@ fn cipher_init(config: InitConfig) -> Result, u32> { let initialising = Initialising::begin(); run(Box::pin(async move { let _initialising = initialising; - install( - builder - .init() - .await - .map_err(|e| crate::status::fail_error(&e))?, - ) + let cipher = builder + .init() + .await + .map_err(|e| crate::status::fail_error(&e))?; + let default = default_keyset_id(&cipher).await?; + install(cipher, default) })) } @@ -278,12 +278,12 @@ fn cipher_init(seed: InitConfig) -> Result, u32> { let initialising = Initialising::begin(); run(Box::pin(async move { let _initialising = initialising; - install( - builder - .init() - .await - .map_err(|e| crate::status::fail_error(&e))?, - ) + let cipher = builder + .init() + .await + .map_err(|e| crate::status::fail_error(&e))?; + let default = default_keyset_id(&cipher).await?; + install(cipher, default) })) } @@ -318,14 +318,24 @@ fn init_out_of_order() -> u32 { out_of_order("the cipher is already initialised or initialising, or the instance is shut down") } -/// Install the built cipher as the instance's and return its default -/// keyset's id. -fn install(cipher: GuestCipher) -> Result, u32> { +/// The id of the cipher's default keyset. `init` loaded that keyset, so +/// this makes no request. +async fn default_keyset_id(cipher: &GuestCipher) -> Result, u32> { + let id = cipher + .default_keyset() + .keyset_id() + .await + .map_err(|e| crate::status::fail_error(&e))?; + Ok(id.as_bytes().to_vec()) +} + +/// Install the built cipher as the instance's and return `default`, its +/// default keyset's id. +fn install(cipher: GuestCipher, default: Vec) -> Result, u32> { // A shutdown that overtook a paused init installs nothing. if SHUT_DOWN.with(Cell::get) { return Err(init_out_of_order()); } - let default = cipher.default_keyset().keyset_id().as_bytes().to_vec(); CIPHER.with(|c| *c.borrow_mut() = Some(Rc::new(cipher))); Ok(default) } @@ -377,7 +387,11 @@ pub unsafe extern "C" fn se_keyset(sel_ptr: *const u8, sel_len: u32) -> u64 { let cipher = cipher()?; run(Box::pin(async move { let keyset = selector.resolve(&cipher).await?; - Ok(keyset.keyset_id().as_bytes().to_vec()) + let id = keyset + .keyset_id() + .await + .map_err(|e| crate::status::fail_error(&e))?; + Ok(id.as_bytes().to_vec()) })) }) } @@ -500,8 +514,8 @@ pub unsafe extern "C" fn se_decrypt_record( ops::validate::record_tree(&record, &plan, options.context.as_ref())?; let cipher = cipher()?; run(Box::pin(async move { - let scope = scope_for(&cipher, &options.keyset).await?; - ops::decrypt_record(scope, &record, &plan, options.context).await + let cipher_ref = cipher_ref_for(&cipher, &options.keyset).await?; + ops::decrypt_record(cipher_ref, &record, &plan, options.context).await })) }) } diff --git a/languages/golang/encrypt/guest/src/ops.rs b/languages/golang/encrypt/guest/src/ops.rs index 14ffe2e751..0ce52f6b28 100644 --- a/languages/golang/encrypt/guest/src/ops.rs +++ b/languages/golang/encrypt/guest/src/ops.rs @@ -216,7 +216,7 @@ where /// were sealed under. The output buffer contains plaintext — the ABI layer's /// ownership rules govern its wiping. pub async fn decrypt_record<'a, K>( - scope: impl Into>, + cipher_ref: impl Into>, record: &[u8], plan: &Bytes, expected: Option

: CredentialAuthStrategy` + which is required by `StackKms>: CredentialKeySource` diff --git a/packages/stack-encrypt/tests/ui/foreign_cipher_ref.rs b/packages/stack-encrypt/tests/ui/foreign_cipher_ref.rs index fdf391d502..e13689b949 100644 --- a/packages/stack-encrypt/tests/ui/foreign_cipher_ref.rs +++ b/packages/stack-encrypt/tests/ui/foreign_cipher_ref.rs @@ -3,12 +3,12 @@ //! names a keyset the cipher did not load from ZeroKMS. use stack_encrypt::{CipherRef, StackCipher}; -use uuid::Uuid; -fn any_keyset(cipher: &StackCipher, id: Uuid) -> CipherRef<'_, K> { +fn any_keyset(cipher: &StackCipher) -> CipherRef<'_, K> { CipherRef { cipher, - keyset: Some(id), + // Whatever the field is given: it cannot be named from here. + keyset: unimplemented!(), } } diff --git a/packages/stack-encrypt/tests/ui/foreign_cipher_ref.stderr b/packages/stack-encrypt/tests/ui/foreign_cipher_ref.stderr index 5817361e36..77c589603d 100644 --- a/packages/stack-encrypt/tests/ui/foreign_cipher_ref.stderr +++ b/packages/stack-encrypt/tests/ui/foreign_cipher_ref.stderr @@ -1,9 +1,31 @@ +warning: unreachable expression + --> tests/ui/foreign_cipher_ref.rs:8:5 + | + 8 | / CipherRef { + 9 | | cipher, +10 | | // Whatever the field is given: it cannot be named from here. +11 | | keyset: unimplemented!(), + | | ---------------- any code following this expression is unreachable +12 | | } + | |_____^ unreachable expression + | + = note: `#[warn(unreachable_code)]` (part of `#[warn(unused)]`) on by default + error[E0451]: fields `cipher` and `keyset` of struct `CipherRef` are private - --> tests/ui/foreign_cipher_ref.rs:10:9 + --> tests/ui/foreign_cipher_ref.rs:9:9 | - 9 | CipherRef { + 8 | CipherRef { | --------- in this type -10 | cipher, + 9 | cipher, | ^^^^^^ private field -11 | keyset: Some(id), +10 | // Whatever the field is given: it cannot be named from here. +11 | keyset: unimplemented!(), | ^^^^^^ private field + +error: type `target::pending::KeysetSelector` is private + --> tests/ui/foreign_cipher_ref.rs:11:17 + | +11 | keyset: unimplemented!(), + | ^^^^^^^^^^^^^^^^ private type + | + = note: this error originates in the macro `unimplemented` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/packages/stack-encrypt/tests/ui/pass/oidc_strategies.rs b/packages/stack-encrypt/tests/ui/pass/oidc_strategies.rs new file mode 100644 index 0000000000..75325570e9 --- /dev/null +++ b/packages/stack-encrypt/tests/ui/pass/oidc_strategies.rs @@ -0,0 +1,66 @@ +//! The two kinds of OIDC strategy, and the calls that must compile over +//! each. +//! +//! Which kind takes a credential is stack-auth's rule, held by its two +//! strategy traits. Stack Encrypt adds no check of its own. These cases +//! show that the rule reaches a call, through Stack KMS. +//! +//! A strategy with a provider asks the provider who each request is for. +//! A call through it is awaited as it is: a pending, an audited call, a +//! value sealed under a context and a zipped call. It has no +//! `with_credential`, and +//! `tests/ui/credential_on_a_source_with_its_own_identity.rs` holds that +//! refusal. +//! +//! A strategy built with `credential_per_call` has no provider. A call +//! through it is awaited once it has a credential, and +//! `tests/ui/call_with_no_credential.rs` holds the refusal of a call with +//! none. +use stack_auth::{CredentialPerCall, OidcFederationStrategy, OidcProvider}; +use stack_encrypt::kms::{SecretToken, StackKms}; +use stack_encrypt::{ + nonempty, AuditMetadata, Ciphertext, EncryptInto, Error, Pending, StackCipher, + StackCipherText, +}; + +type WithProvider

= StackKms>; +type PerCall = StackKms>; + +async fn with_a_provider( + cipher: &StackCipher>, +) -> Result<(), Error> { + let keyset = cipher.default_keyset(); + let email = String::from("bob@example.com"); + let seal = || -> Pending<'_, Ciphertext, WithProvider

> { keyset.encrypt(1i64) }; + + let stored = seal().await?; + let _: i64 = keyset.decrypt(stored).await?; + let _ = seal().audit(AuditMetadata::new()).await?; + let _: StackCipherText = email + .encrypt_into_with_context(&keyset, nonempty!("users/email")) + .await?; + let _ = seal().zip(seal()).await?; + Ok(()) +} + +async fn with_a_credential_per_call(cipher: &StackCipher) -> Result<(), Error> { + let keyset = cipher.default_keyset(); + let email = String::from("bob@example.com"); + let jwt = || SecretToken::new("header.payload.signature"); + let seal = || -> Pending<'_, Ciphertext, PerCall> { keyset.encrypt(1i64) }; + + let stored = seal().with_credential(jwt()).await?; + let _: i64 = keyset.decrypt(stored).with_credential(jwt()).await?; + let _ = seal() + .audit(AuditMetadata::new()) + .with_credential(jwt()) + .await?; + let _: StackCipherText = email + .encrypt_into_with_context(&keyset, nonempty!("users/email")) + .with_credential(jwt()) + .await?; + let _ = seal().zip(seal()).with_credential(jwt()).await?; + Ok(()) +} + +fn main() {} diff --git a/packages/stack-encrypt/tests/value_kinds.rs b/packages/stack-encrypt/tests/value_kinds.rs index 2f7a610e31..06a7ecdcf2 100644 --- a/packages/stack-encrypt/tests/value_kinds.rs +++ b/packages/stack-encrypt/tests/value_kinds.rs @@ -487,7 +487,7 @@ async fn the_committed_fixture_opens_and_its_terms_are_todays() { let fixture = json!({ "_comment": "One field of each value kind added in #1144, sealed by the data-plan lowering under a deterministic key source, with each value's transport frame and the equality queries vitaminc-normalize folds onto a stored term. Read by tests/value_kinds.rs and the Go SDK's encrypt tests; the schema is in README.md beside this file. Regenerate with STACK_ENCRYPT_UPDATE_FIXTURES=1; do not edit by hand.", "key_source": { "kind": "deterministic-sha256", "seed": hex(&SEED) }, - "keyset_id": keyset.keyset_id().to_string(), + "keyset_id": keyset.keyset_id().await.unwrap().to_string(), "plan": data_plan_json(), "values": values(), "record": record, @@ -502,7 +502,10 @@ async fn the_committed_fixture_opens_and_its_terms_are_todays() { serde_json::from_str(&std::fs::read_to_string(&path).expect("the fixture is committed")) .expect("the fixture is JSON"); assert_eq!(fixture["key_source"]["seed"], json!(hex(&SEED))); - assert_eq!(fixture["keyset_id"], json!(keyset.keyset_id().to_string())); + assert_eq!( + fixture["keyset_id"], + json!(keyset.keyset_id().await.unwrap().to_string()) + ); assert_eq!( fixture["plan"], data_plan_json(),