Skip to main content

agentmux_srv_core/identity/resolver/
secret.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! [`resolve_secret`]: turning a `SecretRef` into a plaintext credential.
5//!
6//! Split out of the single ~2193-line `resolver.rs` (pure relocation, no
7//! behavior change).
8
9use std::collections::BTreeMap;
10use std::sync::{Mutex, PoisonError};
11use std::time::{Duration, Instant};
12
13use zeroize::Zeroizing;
14
15use crate::backend::storage::store::{SecretRef, Store};
16use crate::backend::vault::aws_import::{self, Source};
17use crate::identity::aws_broker::mint::{HostRunner, Runner};
18
19use super::errors::ResolverError;
20
21/// Resolve a `SecretRef` to the plaintext credential string. Each
22/// backend has a distinct path:
23///
24/// - **Env**: read `env_var` from the srv process's own environment.
25///   Caller is expected to have set this in their shell or a
26///   .env-style loader before launching AgentMux.
27/// - **PlaintextDev**: return the literal stored string. **Debug
28///   builds only** โ€” guarded behind `cfg(debug_assertions)`. In
29///   release builds, the same call returns
30///   [`ResolverError::PlaintextDevDisabledInRelease`] so a forgotten
31///   dev-secret never leaks into a packaged binary. Reagent P1 on
32///   PR #751 caught the missing guard. Phase 3's encrypted vault is
33///   the production path.
34/// - **SecretsManager**: read from AWS Secrets Manager with the host's own AWS login, the whole secret or the
35///   field `sm_json_path` names. A failed read is [`ResolverError::SecretsManagerRead`].
36///
37/// The value is the credential to use: an account connected with OAuth
38/// stores a JSON token blob, of which only its `access_token` is the
39/// credential (`oauth_tokens::bearer_value`). A plain key is unchanged.
40pub fn resolve_secret(secret_ref: &SecretRef) -> Result<String, ResolverError> {
41    resolve_stored(secret_ref).map(crate::identity::oauth_tokens::bearer_value)
42}
43
44/// An account connected with OAuth (GitHub's tokens last hours) is refreshed before its token goes
45/// into an agent's environment, so a launch after the expiry doesn't hand out a dead token. Best
46/// effort: if it can't be refreshed, the stored token is used as it was, and a grant the provider
47/// no longer accepts marks the account as needing to be connected again (`oauth_tokens`). Runs on
48/// the blocking thread the injection already uses; with no runtime (a test), nothing happens.
49fn refresh_oauth_token_if_due(account: &crate::backend::storage::store::IdentityAccount, id_store: &std::sync::Arc<Store>, identity_store: &std::sync::Arc<Store>) {
50    if account.kind != "oauth" || !matches!(account.secret_ref, SecretRef::Keychain { .. }) {
51        return;
52    }
53    let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
54    let result = runtime.block_on(crate::identity::oauth_tokens::access_token_for(
55        &crate::identity::oauth_tokens::LiveHttp,
56        &crate::identity::oauth_tokens::KeychainSecrets,
57        id_store,
58        identity_store,
59        account,
60        Some(id_store),
61    ));
62    if let Err(e) = result {
63        tracing::info!(target: "identity", account_id = %account.id, error = %e, "identity.oauth: the token couldn't be refreshed before launch; using the stored one");
64    }
65}
66
67/// [`resolve_secret`] for an account about to go into an agent's environment: an OAuth token that is
68/// due is refreshed first.
69pub fn resolve_account_secret(
70    account: &crate::backend::storage::store::IdentityAccount,
71    id_store: &std::sync::Arc<Store>,
72    identity_store: &std::sync::Arc<Store>,
73) -> Result<String, ResolverError> {
74    refresh_oauth_token_if_due(account, id_store, identity_store);
75    if matches!(account.secret_ref, SecretRef::Vault { .. }) {
76        return crate::backend::vault::account_key::read(identity_store, &account.id, &account.secret_ref)
77            .map(|key| crate::identity::oauth_tokens::bearer_value(key.to_string())).map_err(ResolverError::VaultError);
78    }
79    resolve_stored(&account.secret_ref).map(crate::identity::oauth_tokens::bearer_value)
80}
81
82/// An AWS Secrets Manager secret's text (or the field `json_path` names in a JSON one), read with the host's own AWS
83/// login by the reader the Vault's backed entries use (`vault::aws_import::read_value_blocking`). On the blocking thread
84/// the injection already runs on.
85///
86/// The model gateway asks for an account's key on every request, and each ask here is a run of the AWS CLI and a
87/// billed Secrets Manager call, so a value read is kept for [`SM_CACHE_TTL`]: a rotation reaches the next request
88/// within that time. A failed read is not kept. (A Vault backed entry reads at each use and keeps nothing.)
89fn secrets_manager_value<R: Runner>(runner: &R, path: &str, json_path: Option<&str>) -> Result<String, ResolverError> {
90    secrets_manager_value_at(runner, path, json_path, Instant::now())
91}
92
93/// How long a value read from Secrets Manager is reused by the resolver.
94const SM_CACHE_TTL: Duration = Duration::from_secs(30);
95
96type SmCache = BTreeMap<(String, Option<String>), (Instant, Zeroizing<String>)>;
97static SM_CACHE: Mutex<SmCache> = Mutex::new(BTreeMap::new());
98
99fn secrets_manager_value_at<R: Runner>(runner: &R, path: &str, json_path: Option<&str>, now: Instant) -> Result<String, ResolverError> {
100    let place = (path.to_string(), json_path.map(str::to_string));
101    if let Some((read_at, value)) = SM_CACHE.lock().unwrap_or_else(PoisonError::into_inner).get(&place) {
102        if now.saturating_duration_since(*read_at) < SM_CACHE_TTL {
103            return Ok(value.to_string());
104        }
105    }
106    let source = Source { aws_secret_id: path.to_string(), key: json_path.map(str::to_string), ..Default::default() };
107    let source = aws_import::check_source(&source).map_err(ResolverError::SecretsManagerRead)?;
108    let value = aws_import::read_value_blocking(runner, &source).map_err(ResolverError::SecretsManagerRead)?;
109    let mut cache = SM_CACHE.lock().unwrap_or_else(PoisonError::into_inner);
110    cache.retain(|_, (read_at, _)| now.saturating_duration_since(*read_at) < SM_CACHE_TTL);
111    cache.insert(place, (now, value.clone()));
112    Ok(value.to_string())
113}
114
115fn resolve_stored(secret_ref: &SecretRef) -> Result<String, ResolverError> {
116    match secret_ref {
117        SecretRef::Env { env_var } => std::env::var(env_var)
118            .map_err(|_| ResolverError::EnvVarMissing(env_var.clone())),
119        SecretRef::PlaintextDev { plaintext_dev } => {
120            #[cfg(debug_assertions)]
121            {
122                Ok(plaintext_dev.clone())
123            }
124            #[cfg(not(debug_assertions))]
125            {
126                let _ = plaintext_dev;
127                Err(ResolverError::PlaintextDevDisabledInRelease)
128            }
129        }
130        SecretRef::SecretsManager { sm_path, sm_json_path } => secrets_manager_value(&HostRunner, sm_path, sm_json_path.as_deref()),
131        SecretRef::OAuthConfigDir { dir } => {
132            // Read but ignored โ€” the resolver doesn't consume the
133            // pointer; PR B's oauth-class dispatch in
134            // `inject_identity_env` reads `dir` and sets the
135            // provider's config-dir env var directly, bypassing
136            // `resolve_secret` entirely.
137            let _ = dir;
138            Err(ResolverError::OAuthConfigDirNotASecret)
139        }
140        SecretRef::Keychain { account, .. } => {
141            // Account API keys: pull the plaintext from the OS
142            // keychain at spawn time. The account string is
143            // `acct:<account_id>`; secret_store reconstructs the key
144            // from the id, so strip the namespace prefix here.
145            let account_id = account.strip_prefix("acct:").unwrap_or(account);
146            crate::identity::secret_store::get(account_id)
147                .map(|z| z.to_string())
148                .map_err(ResolverError::KeychainError)
149        }
150        SecretRef::Vault { .. } => Err(ResolverError::VaultError("an account is required to read a Vault key".into())),
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    // PlaintextDev-using tests are gated behind cfg(debug_assertions)
159    // because release builds reject PlaintextDev with
160    // ResolverError::PlaintextDevDisabledInRelease, so the assertions
161    // below would fail under `cargo test --release`. Reagent P2
162    // (PR #751). The Env / SecretsManager / unknown-provider paths
163    // are tested separately and have no debug-only dependency.
164
165    #[cfg(debug_assertions)]
166    #[test]
167    fn resolve_plaintext_dev() {
168        let s = resolve_secret(&SecretRef::PlaintextDev {
169            plaintext_dev: "ghp_test123".to_string(),
170        })
171        .unwrap();
172        assert_eq!(s, "ghp_test123");
173    }
174
175    /// An OAuth-connected GitHub account stores a JSON blob; the agent's
176    /// `GH_TOKEN` is its access token, not the blob (spec ยง2.3's bug).
177    #[cfg(debug_assertions)]
178    #[test]
179    fn resolve_an_oauth_token_blob_to_its_access_token() {
180        let s = resolve_secret(&SecretRef::PlaintextDev {
181            plaintext_dev: r#"{"access_token":"gho_oauth","refresh_token":null,"expires_at":0}"#.to_string(),
182        })
183        .unwrap();
184        assert_eq!(s, "gho_oauth");
185    }
186
187    #[test]
188    fn resolve_env_var_blob_and_plain_values() {
189        let var = "AGENTMUX_TEST_RESOLVE_SECRET_BLOB_Q7Z";
190        std::env::set_var(var, r#"{"access_token":"gho_env"}"#);
191        assert_eq!(resolve_secret(&SecretRef::Env { env_var: var.to_string() }).unwrap(), "gho_env");
192        std::env::set_var(var, "ghp_plain_env");
193        assert_eq!(resolve_secret(&SecretRef::Env { env_var: var.to_string() }).unwrap(), "ghp_plain_env");
194        std::env::remove_var(var);
195    }
196
197    #[test]
198    fn resolve_env_var_missing() {
199        let res = resolve_secret(&SecretRef::Env {
200            env_var: "AGENTMUX_TEST_NEVER_SET_X9Q".to_string(),
201        });
202        assert!(matches!(res, Err(ResolverError::EnvVarMissing(_))));
203    }
204
205    /// A secret in AWS Secrets Manager resolves through the reader the Vault's backed entries use (the AWS CLI is a
206    /// stand-in, the secret invented): the whole text, or the field `sm_json_path` names.
207    #[test]
208    fn resolve_secrets_manager_reads_the_secret_or_a_field_of_it() {
209        use crate::backend::vault::backed::tests::Aws;
210        let aws = Aws::with(&[("svc/example-key", Ok(r#"{"db": {"password": "pw-from-aws"}}"#)), ("svc/plain", Ok("plain-from-aws"))]);
211        assert_eq!(secrets_manager_value(&aws, "svc/example-key", Some("db.password")).unwrap(), "pw-from-aws");
212        assert_eq!(secrets_manager_value(&aws, "svc/plain", None).unwrap(), "plain-from-aws");
213        let missing = secrets_manager_value(&aws, "svc/absent", None);
214        assert!(matches!(&missing, Err(ResolverError::SecretsManagerRead(why)) if why.contains("AWS has no secret")), "{missing:?}");
215        // The id goes to the CLI as an argument: one that isn't a secret's name never gets there.
216        assert!(matches!(secrets_manager_value(&aws, "--query x", None), Err(ResolverError::SecretsManagerRead(_))));
217    }
218
219    /// The model gateway asks for a key on every request: a value read is reused for 30 s, then read again, and a
220    /// failed read is not kept.
221    #[test]
222    fn resolve_secrets_manager_reuses_a_read_for_a_short_while() {
223        use crate::backend::vault::backed::tests::Aws;
224        let aws = Aws::with(&[("svc/rotating-key", Ok("first-from-aws"))]);
225        let t0 = Instant::now();
226        assert_eq!(secrets_manager_value_at(&aws, "svc/rotating-key", None, t0).unwrap(), "first-from-aws");
227        aws.change("svc/rotating-key", "second-from-aws");
228        assert_eq!(secrets_manager_value_at(&aws, "svc/rotating-key", None, t0 + Duration::from_secs(10)).unwrap(), "first-from-aws");
229        assert_eq!(aws.reads(), 1, "a second ask within the time costs no call");
230        assert_eq!(secrets_manager_value_at(&aws, "svc/rotating-key", None, t0 + Duration::from_secs(31)).unwrap(), "second-from-aws");
231        assert_eq!(aws.reads(), 2);
232
233        let down = Aws::with(&[]);
234        assert!(secrets_manager_value_at(&down, "svc/not-yet-there", None, t0).is_err());
235        assert_eq!(down.reads(), 1);
236        assert!(secrets_manager_value_at(&down, "svc/not-yet-there", None, t0).is_err());
237        assert_eq!(down.reads(), 2, "a failed read is asked again, not kept");
238    }
239
240    #[test]
241    fn resolve_oauth_config_dir_is_not_a_secret() {
242        // OAuthConfigDir is a pointer to a CLI-managed token directory,
243        // not a resolvable secret string. PR B's oauth-class dispatch
244        // in `inject_identity_env` reads `dir` and sets the provider's
245        // config-dir env var directly, bypassing `resolve_secret`. The
246        // error here is a guard against a caller forgetting that
247        // dispatch โ€” pre-PR-B nothing produces this variant, but the
248        // arm has to exist for the match to be exhaustive.
249        let res = resolve_secret(&SecretRef::OAuthConfigDir {
250            dir: "/path/to/bundle/claude".to_string(),
251        });
252        assert!(matches!(res, Err(ResolverError::OAuthConfigDirNotASecret)));
253    }
254}