From 55c7745894667061c967af7d9a72d92bfe2aca44 Mon Sep 17 00:00:00 2001 From: atlas Date: Sat, 21 Nov 2026 13:43:52 +0100 Subject: [PATCH] swarm-secret-client: log in with a service-account token under BAO_AUTH=jwt --- swarm-secret-client/src/client.rs | 291 +++++++++++++++++++++++++++--- swarm-secret-client/src/lib.rs | 3 +- 2 files changed, 272 insertions(+), 22 deletions(-) diff --git a/swarm-secret-client/src/client.rs b/swarm-secret-client/src/client.rs index 81510b00b..317657afd 100644 --- a/swarm-secret-client/src/client.rs +++ b/swarm-secret-client/src/client.rs @@ -6,7 +6,7 @@ use rustify_derive::Endpoint; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use vaultrs::{ api::{ - auth::cert::requests::CreateCaCertificateRoleRequest, + auth::{cert::requests::CreateCaCertificateRoleRequest, oidc::requests::JWTLoginRequest}, pki::{requests::GenerateCertificateRequest, responses::GenerateCertificateResponse}, }, client::{Client, VaultClient, VaultClientSettings, VaultClientSettingsBuilder}, @@ -25,6 +25,20 @@ pub const ENV_CLIENT_KEY: &str = "BAO_CLIENT_KEY"; /// real CA wants and what a self-signed one must not be left with. pub const ENV_CACERT: &str = "BAO_CACERT"; +/// Which login the client uses: `cert` (the default) or `jwt`. +pub const ENV_AUTH: &str = "BAO_AUTH"; +/// File holding the service-account token a `jwt` login presents. Optional: +/// absent means [`DEFAULT_JWT_FILE`]. Read again at every login, because the +/// kubelet rotates a projected token in place. +pub const ENV_JWT_FILE: &str = "BAO_JWT_FILE"; +/// The role on the `jwt` mount that a `jwt` login asks for. +pub const ENV_JWT_ROLE: &str = "BAO_JWT_ROLE"; +/// The auth mount a `jwt` login goes through. +pub const ENV_JWT_MOUNT: &str = "BAO_JWT_MOUNT"; + +/// Where a pod's projected service-account token for the store is mounted. +pub const DEFAULT_JWT_FILE: &str = "/var/run/secrets/hyperhive/bao/token"; + /// The auth mount a cert login goes through, unless a caller says otherwise. pub const DEFAULT_CERT_MOUNT: &str = "cert"; @@ -69,11 +83,23 @@ pub struct Version { #[derive(Debug, PartialEq, Eq)] pub struct Settings { address: String, - cert_path: String, - key_path: String, + auth: Auth, ca_path: Option, } +/// How the client proves who it is, chosen by [`ENV_AUTH`]. +#[derive(Debug, PartialEq, Eq)] +enum Auth { + /// The certificate and key the store's listener verifies. + Cert { cert_path: String, key_path: String }, + /// A service-account token, exchanged for a store token at `mount`. + Jwt { + jwt_file: String, + role: String, + mount: String, + }, +} + impl Settings { /// The vaultrs settings for this store, presenting `identity`. fn client_settings( @@ -94,7 +120,8 @@ impl Settings { /// Read the `BAO_*` variables from the process environment. /// /// # Errors - /// [`Error::MissingEnv`] naming the first variable that is unset or empty. + /// [`Error::MissingEnv`] naming the first variable that is unset or empty, + /// and [`Error::Settings`] when [`ENV_AUTH`] names neither login. pub fn from_env() -> Result { Self::from_lookup(|k| std::env::var(k).ok()) } @@ -107,24 +134,47 @@ impl Settings { /// defaults yields a client with **no identity**, which fails at the TLS /// handshake rather than anywhere that names the cause. /// + /// [`ENV_AUTH`] picks the login. Unset or empty is `cert`, which needs + /// [`ENV_CLIENT_CERT`] and [`ENV_CLIENT_KEY`]; `jwt` needs + /// [`ENV_JWT_ROLE`] and [`ENV_JWT_MOUNT`], reads the token from + /// [`ENV_JWT_FILE`] (default [`DEFAULT_JWT_FILE`]) and ignores the + /// certificate variables. + /// /// # Errors - /// [`Error::MissingEnv`] naming the first variable that is unset or empty. + /// [`Error::MissingEnv`] naming the first variable that is unset or empty, + /// and [`Error::Settings`] when [`ENV_AUTH`] names neither login. pub fn from_lookup(get: impl Fn(&str) -> Option) -> Result { + let present = |var: &str| get(var).filter(|v| !v.is_empty()); let required = |var: &'static str| -> Result { - get(var) - .filter(|v| !v.is_empty()) - .ok_or(Error::MissingEnv(var)) + present(var).ok_or(Error::MissingEnv(var)) + }; + let address = required(ENV_ADDR)?; + let auth = match present(ENV_AUTH).as_deref() { + None | Some("cert") => Auth::Cert { + cert_path: required(ENV_CLIENT_CERT)?, + key_path: required(ENV_CLIENT_KEY)?, + }, + Some("jwt") => Auth::Jwt { + jwt_file: present(ENV_JWT_FILE).unwrap_or_else(|| DEFAULT_JWT_FILE.to_owned()), + role: required(ENV_JWT_ROLE)?, + mount: required(ENV_JWT_MOUNT)?, + }, + Some(other) => { + return Err(Error::Settings(format!( + "{ENV_AUTH} is {other:?}; it is \"cert\" or \"jwt\"" + ))); + } }; Ok(Self { - address: required(ENV_ADDR)?, - cert_path: required(ENV_CLIENT_CERT)?, - key_path: required(ENV_CLIENT_KEY)?, - ca_path: get(ENV_CACERT).filter(|v| !v.is_empty()), + address, + auth, + ca_path: present(ENV_CACERT), }) } } -/// A client that has already exchanged its certificate for a token. +/// A client that has already exchanged its certificate or service-account +/// token for a store token. pub struct SecretStore { inner: VaultClient, } @@ -137,12 +187,41 @@ fn read_file(var: &'static str, path: &str) -> Result, Error> { }) } +/// The token in the file [`ENV_JWT_FILE`] names, read now: the kubelet +/// rewrites a projected token before it expires, so a login never reuses an +/// earlier read. +fn read_jwt(path: &str) -> Result { + let raw = read_file(ENV_JWT_FILE, path)?; + let token = String::from_utf8(raw) + .map_err(|_| Error::Settings(format!("{path} (from {ENV_JWT_FILE}) is not text")))?; + let token = token.trim(); + if token.is_empty() { + return Err(Error::Settings(format!( + "{path} (from {ENV_JWT_FILE}) is empty" + ))); + } + Ok(token.to_owned()) +} + +/// The login a `jwt` client sends: `token` for `role`, at the mount `mount`. +fn jwt_login_request(mount: &str, token: &str, role: &str) -> JWTLoginRequest { + JWTLoginRequest::builder() + .mount(mount) + .jwt(token) + .role(role) + .build() + .expect("every field the builder needs is set") +} + impl SecretStore { - /// Connect using the `BAO_*` environment and log in with the certificate - /// auth method, returning a handle that already holds a token. + /// Connect using the `BAO_*` environment and log in, returning a handle + /// that already holds a token. [`ENV_AUTH`] picks the method: the + /// certificate auth method by default, a service-account token under + /// `jwt` (see [`Settings::from_lookup`]). /// /// `cert_role` is the role configured on the store's `cert` mount; it - /// selects which policy the returned token carries. + /// selects which policy the returned token carries. A `jwt` client names + /// its role in [`ENV_JWT_ROLE`] instead. /// /// # Errors /// As [`SecretStore::connect`], plus [`Error::MissingEnv`]. @@ -151,27 +230,58 @@ impl SecretStore { } /// Present `settings`' identity to the store and log in at `cert_mount`. + /// Under `jwt` the login is at the mount [`ENV_JWT_MOUNT`] names, as the + /// role [`ENV_JWT_ROLE`] names, and `cert_role` and `cert_mount` are not + /// used. /// /// # Errors /// [`Error::Identity`] when a named file cannot be read, [`Error::Tls`] /// when the cert/key pair does not form a usable identity, - /// [`Error::Settings`] when the address will not parse, and - /// [`Error::Vault`] when the store refuses the login — which is what an - /// unconfigured `cert` mount looks like from here. + /// [`Error::Settings`] when the address will not parse or the token file + /// holds no token, and [`Error::Vault`] when the store refuses the + /// login — which is what an unconfigured `cert` or `jwt` mount looks like + /// from here. pub async fn connect( settings: &Settings, cert_role: &str, cert_mount: &str, ) -> Result { + let (cert_path, key_path) = match &settings.auth { + Auth::Cert { + cert_path, + key_path, + } => (cert_path, key_path), + Auth::Jwt { + jwt_file, + role, + mount, + } => return Self::connect_jwt(settings, jwt_file, role, mount).await, + }; // One PEM blob holding both, which is the shape `Identity::from_pem` // wants; the two stay separate on disk because the key is the half // that gets `0600`. - let mut pem = read_file(ENV_CLIENT_CERT, &settings.cert_path)?; + let mut pem = read_file(ENV_CLIENT_CERT, cert_path)?; pem.push(b'\n'); - pem.extend_from_slice(&read_file(ENV_CLIENT_KEY, &settings.key_path)?); + pem.extend_from_slice(&read_file(ENV_CLIENT_KEY, key_path)?); Self::connect_with_identity(settings, &pem, cert_role, cert_mount).await } + /// Log in at the `jwt` mount `mount` as `role`, with the token `jwt_file` + /// holds now. No client certificate is presented. + async fn connect_jwt( + settings: &Settings, + jwt_file: &str, + role: &str, + mount: &str, + ) -> Result { + let token = read_jwt(jwt_file)?; + let built = settings.client_settings(None)?; + let mut inner = VaultClient::new(built)?; + let auth = vaultrs::api::auth(&inner, jwt_login_request(mount, &token, role)).await?; + inner.set_token(&auth.client_token); + Ok(Self { inner }) + } + /// Log in at the store `settings` names, presenting an identity the caller /// is already holding rather than one named by the environment. /// @@ -1154,6 +1264,145 @@ mod tests { } } + /// A lookup standing in for a pod's environment under `jwt`: no + /// certificate variables at all. + fn jwt_env(k: &str) -> Option { + match k { + ENV_ADDR => Some("https://store.invalid:8208".to_owned()), + ENV_AUTH => Some("jwt".to_owned()), + ENV_JWT_ROLE => Some("swarm-notify-router".to_owned()), + ENV_JWT_MOUNT => Some("jwt-k8s".to_owned()), + _ => None, + } + } + + /// The default is the certificate login, with the paths the environment + /// names, whether `BAO_AUTH` is absent, empty or `cert`. + #[test] + fn the_certificate_login_is_the_default() { + let expected = Auth::Cert { + cert_path: "/run/c.pem".to_owned(), + key_path: "/run/k.pem".to_owned(), + }; + let with_auth = |value: Option<&'static str>| { + Settings::from_lookup(move |k| match (k, value) { + (ENV_AUTH, Some(v)) => Some(v.to_owned()), + _ => full(k), + }) + .expect("the certificate variables are set") + }; + for value in [None, Some(""), Some("cert")] { + assert_eq!(with_auth(value).auth, expected, "BAO_AUTH = {value:?}"); + } + } + + #[test] + fn a_jwt_environment_needs_no_certificate_and_defaults_the_token_file() { + let s = Settings::from_lookup(jwt_env).expect("role and mount are set"); + assert_eq!(s.address, "https://store.invalid:8208"); + assert_eq!( + s.auth, + Auth::Jwt { + jwt_file: DEFAULT_JWT_FILE.to_owned(), + role: "swarm-notify-router".to_owned(), + mount: "jwt-k8s".to_owned(), + } + ); + + let named = Settings::from_lookup(|k| { + if k == ENV_JWT_FILE { + Some("/run/t".to_owned()) + } else { + jwt_env(k) + } + }) + .expect("a named token file is accepted"); + assert!(matches!(named.auth, Auth::Jwt { jwt_file, .. } if jwt_file == "/run/t")); + } + + #[test] + fn each_jwt_variable_is_named_when_it_is_the_missing_one() { + for var in [ENV_ADDR, ENV_JWT_ROLE, ENV_JWT_MOUNT] { + for blank in [None, Some(String::new())] { + let e = + Settings::from_lookup(|k| if k == var { blank.clone() } else { jwt_env(k) }) + .expect_err("one required variable is absent"); + assert!( + matches!(e, Error::MissingEnv(v) if v == var), + "dropping {var} should name {var}, got {e:?}" + ); + } + } + } + + #[test] + fn an_unknown_auth_method_is_refused_by_name() { + let e = Settings::from_lookup(|k| { + if k == ENV_AUTH { + Some("kubernetes".to_owned()) + } else { + full(k) + } + }) + .expect_err("neither cert nor jwt"); + assert!( + matches!(&e, Error::Settings(m) if m.contains(ENV_AUTH) && m.contains("kubernetes")), + "got {e:?}" + ); + } + + #[test] + fn the_jwt_login_posts_the_token_and_role_to_the_mount() { + use rustify::Endpoint as _; + let r = jwt_login_request("jwt-k8s", "a.b.c", "swarm-notify-router") + .request("http://store.invalid") + .expect("builds"); + assert_eq!(r.method(), "POST"); + assert_eq!(r.uri().path(), "/auth/jwt-k8s/login"); + let body: serde_json::Value = serde_json::from_slice(r.body()).expect("json body"); + assert_eq!( + body, + serde_json::json!({"jwt": "a.b.c", "role": "swarm-notify-router"}) + ); + } + + /// A path of this process's own under the temp directory. + fn temp_token(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("swarm-secret-client-{}-{name}", std::process::id())) + } + + /// Each login reads the file again, so a token the kubelet has rotated is + /// the one sent. + #[test] + fn the_token_file_is_read_afresh_each_time_and_trimmed() { + let path = temp_token("rotating"); + let p = path.to_str().expect("a temp path is text"); + std::fs::write(&path, "first\n").expect("write"); + assert_eq!(read_jwt(p).expect("reads"), "first"); + std::fs::write(&path, "second\n").expect("write"); + assert_eq!(read_jwt(p).expect("reads again"), "second"); + std::fs::remove_file(&path).expect("remove"); + } + + #[test] + fn a_missing_or_empty_token_file_is_an_error_naming_the_file() { + let e = read_jwt("/nonexistent/token").expect_err("the file does not exist"); + assert!( + matches!(&e, Error::Identity { var, path, .. } + if *var == ENV_JWT_FILE && path == "/nonexistent/token"), + "got {e:?}" + ); + + let path = temp_token("empty"); + std::fs::write(&path, " \n").expect("write"); + let e = read_jwt(path.to_str().expect("text")).expect_err("no token in it"); + std::fs::remove_file(&path).expect("remove"); + assert!( + matches!(&e, Error::Settings(m) if m.contains(ENV_JWT_FILE)), + "got {e:?}" + ); + } + /// The defect this pins: the store gates `sys/policy/` and /// `sys/policies/acl/` separately, so a client on the first is /// refused by a grant naming the second — and nothing else in the tree diff --git a/swarm-secret-client/src/lib.rs b/swarm-secret-client/src/lib.rs index c16b45e45..de5cd3793 100644 --- a/swarm-secret-client/src/lib.rs +++ b/swarm-secret-client/src/lib.rs @@ -89,7 +89,8 @@ pub enum Error { #[error("{0} is unset or empty")] MissingEnv(&'static str), - /// A client-certificate file named by the environment could not be read. + /// A client-certificate, key or service-account-token file named by the + /// environment could not be read. #[error("reading {path} (from {var}): {source}")] Identity { /// The variable that named the file.