agentmux_srv_core/identity/resolver/
secret.rs1use 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
21pub fn resolve_secret(secret_ref: &SecretRef) -> Result<String, ResolverError> {
41 resolve_stored(secret_ref).map(crate::identity::oauth_tokens::bearer_value)
42}
43
44fn 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
67pub 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
82fn 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
93const 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 let _ = dir;
138 Err(ResolverError::OAuthConfigDirNotASecret)
139 }
140 SecretRef::Keychain { account, .. } => {
141 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 #[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 #[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 #[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 assert!(matches!(secrets_manager_value(&aws, "--query x", None), Err(ResolverError::SecretsManagerRead(_))));
217 }
218
219 #[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 let res = resolve_secret(&SecretRef::OAuthConfigDir {
250 dir: "/path/to/bundle/claude".to_string(),
251 });
252 assert!(matches!(res, Err(ResolverError::OAuthConfigDirNotASecret)));
253 }
254}