//! Where an agent's backend secrets live in the store, apart from the rest of //! its backend environment. //! //! [`crate::backend_env`] holds the configuration an operator may read back //! (the base URL, a model name). The credentials sit in this leaf, so the //! controller never has to hand one back: it writes the leaf and says only //! whether it holds anything. Both objects hold the text of a systemd //! `EnvironmentFile`. The agent's own `hive-agent-backend-env` unit //! (`nix/agent-modules/backend-env.nix`) reads both under the agent's //! certificate and writes one file, the configuration first and the secrets //! after it, so a variable named in both takes the secret's value. //! //! The agent's read stanza ([`crate::policy::render_shared_agent`]) covers the //! leaf like any other under its prefix. Only the controller writes it. use serde::{Deserialize, Serialize}; use crate::{ Error, path::{Kind, principal_prefix}, }; /// The last segment of the path. pub(crate) const LEAF: &str = "backend-secrets"; /// The path holding `agent`'s backend secrets. /// /// # Errors /// [`Error::PathSegment`] when `agent` contains anything but `[A-Za-z0-9_-]`, /// which is what keeps one agent's name from addressing another agent's secret. pub fn secrets_path(agent: &str) -> Result { let prefix = principal_prefix(Kind::Agent, agent)?; Ok(format!("{prefix}/{LEAF}")) } /// What a [`secrets_path`] holds. /// /// No `Debug` derive: `env` carries live credentials, and a derived `Debug` is /// one `{:?}` away from a log line. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct BackendSecrets { /// The file text, `NAME=value` per line. `backend-env.nix` reads it with /// `bao kv get -field=env`, so this name is load-bearing for a reader this /// crate does not control. pub env: String, } impl std::fmt::Debug for BackendSecrets { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("BackendSecrets") .field("env", &"") .finish() } } #[cfg(test)] mod tests { use super::*; #[test] fn the_secrets_land_under_the_agent_prefix() { // Spelled out: `backend-env.nix` spells the same string. assert_eq!( secrets_path("atlas").expect("a plain name is legal"), "swarm/agents/atlas/backend-secrets" ); } #[test] fn a_traversal_in_the_agent_name_is_refused() { for bad in ["../argus", "a/b", "atlas/../argus", "a.b", ""] { let e = secrets_path(bad).expect_err("a traversal is not legal"); assert!(matches!(e, Error::PathSegment { kind: "agent", .. }), "{e}"); } assert!(secrets_path("a-b_C9").is_ok()); } #[test] fn the_stored_field_is_env() { let stored: BackendSecrets = serde_json::from_str(r#"{"env":"A=b\n"}"#).expect("the documented shape decodes"); assert_eq!(stored.env, "A=b\n"); } #[test] fn debug_hides_the_credentials() { let shown = format!( "{:?}", BackendSecrets { env: "ANTHROPIC_API_KEY=sk-live".to_owned() } ); assert!(!shown.contains("sk-live"), "{shown}"); assert!(shown.contains(""), "{shown}"); } }