1use std::sync::Arc;
8
9use super::{merge_json_object, reject_ambient_home_dir_binding, AccountKeyVerifyResult, VerifyKeyReq};
10use crate::backend::mps::Broker;
11use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
12
13pub(super) async fn list_identity_accounts(
16 mstore: Arc<Store>,
17 identity_store: Arc<Store>,
18 provider: Option<String>,
19) -> Result<Vec<IdentityAccount>, String> {
20 tokio::task::spawn_blocking(move || list_with_numbers(&mstore, &identity_store, provider.as_deref()))
21 .await
22 .map_err(|e| format!("listidentityaccounts: task: {e}"))?
23}
24
25fn list_with_numbers(mstore: &Store, identity_store: &Store, provider: Option<&str>) -> Result<Vec<IdentityAccount>, String> {
26 let mut accounts = mstore.identity_list(provider).map_err(|e| format!("listidentityaccounts: {e}"))?;
27 backfill_emails(&mut accounts, mstore, identity_store);
28 allocate_numbers(mstore, identity_store);
29 let numbered = mstore.identity_list(None).unwrap_or_default();
31 copy_stored_numbers(&mut accounts, &numbered);
32 Ok(accounts)
33}
34
35fn backfill_emails(accounts: &mut [IdentityAccount], mstore: &Store, identity_store: &Store) {
41 for account in accounts {
42 let before = account.context.get("email").and_then(|e| e.as_str()).unwrap_or("").to_string();
43 if let Some(email) = crate::identity::account_email::refresh_account_email(account) {
44 if !crate::identity::account_numbering::same_email(&before, &email) {
46 if let Some(ctx) = account.context.as_object_mut() {
47 ctx.remove("seq");
48 ctx.remove("seqmax");
49 }
50 }
51 for store in [mstore, identity_store] {
52 if let Err(e) = store.identity_set_context_email(&account.id, &email) {
53 tracing::warn!(target: "identity", account_id = %account.id, error = %e, "listidentityaccounts: email backfill write failed");
54 }
55 }
56 }
57 }
58}
59
60fn allocate_numbers(mstore: &Store, identity_store: &Store) {
65 static NUMBERING: std::sync::Mutex<()> = std::sync::Mutex::new(());
66 let _numbering = NUMBERING.lock().unwrap_or_else(|e| e.into_inner());
67 let all = mstore.identity_list(None).unwrap_or_default();
68 for u in crate::identity::account_numbering::numbering_updates(&all) {
69 for store in [mstore, identity_store] {
70 if let Err(e) = store.identity_set_context_numbering(&u.id, u.seq, u.high) {
71 tracing::warn!(target: "identity", account_id = %u.id, error = %e, "listidentityaccounts: number write failed");
72 }
73 }
74 }
75}
76
77fn copy_stored_numbers(accounts: &mut [IdentityAccount], numbered: &[IdentityAccount]) {
79 for a in accounts {
80 let Some(stored) = numbered.iter().find(|n| n.id == a.id) else { continue };
81 for key in ["seq", "seqmax"] {
82 match stored.context.get(key) {
83 Some(v) => {
84 if !a.context.is_object() {
85 a.context = serde_json::json!({});
86 }
87 a.context[key] = v.clone();
88 }
89 None => {
90 if let Some(ctx) = a.context.as_object_mut() {
91 ctx.remove(key);
92 }
93 }
94 }
95 }
96 }
97}
98
99pub(super) fn get_identity_account(mstore: &Store, id: &str) -> Result<IdentityAccount, String> {
100 match mstore.identity_get(id).map_err(|e| format!("getidentityaccount: {e}"))? {
101 Some(a) => Ok(a),
102 None => Err(format!("getidentityaccount: not found id={id}")),
103 }
104}
105
106pub(super) fn upsert_identity_account(
109 mstore: &Store,
110 identity_store: &Store,
111 broker: &Broker,
112 data: serde_json::Value,
113) -> Result<IdentityAccount, String> {
114 let mut account: IdentityAccount = serde_json::from_value(data).map_err(|e| format!("upsertidentityaccount: {e}"))?;
115 reject_ambient_home_dir_binding(&account)?;
116 if account.id.is_empty() {
117 account.id = uuid::Uuid::new_v4().to_string();
118 }
119 let now = agentmux_common::time::now_ms();
120 if account.created_at == 0 {
121 account.created_at = now;
122 }
123 account.updated_at = now;
124 mstore
125 .identity_upsert_with_mirror(identity_store, &account)
126 .map_err(|e| format!("upsertidentityaccount: {e}"))?;
127 broker.publish_event::<crate::backend::mps_events::IdentityAccountsChanged>(&(), vec![], 0);
128 Ok(account)
129}
130
131struct KeyProbe {
133 status: String,
134 metadata: serde_json::Value,
135 masked_tail: String,
136 valid: bool,
137}
138
139pub(super) async fn verify_account_key(
144 mstore: Arc<Store>,
145 identity_store: Arc<Store>,
146 broker: Arc<Broker>,
147 data: serde_json::Value,
148) -> Result<AccountKeyVerifyResult, String> {
149 let req: VerifyKeyReq = serde_json::from_value(data).map_err(|e| format!("account.key.verify: {e}"))?;
151
152 let is_new = req.account_id.is_empty();
154 let account_id = if is_new { uuid::Uuid::new_v4().to_string() } else { req.account_id.clone() };
155
156 let probe = match probe_key(&req).await {
157 Ok(probe) => probe,
158 Err(rejected) => return Ok(rejected),
160 };
161 let existing = mstore.identity_get(&account_id).ok().flatten();
163 let StoredSecret { secret_ref, created: made_here } = store_secret(&identity_store, &account_id, &req, existing.as_ref()).await?;
164 let account = key_account_row(&req, &account_id, existing.as_ref(), secret_ref, probe.status, probe.metadata, &probe.masked_tail);
165 if let Err(e) = mstore.identity_upsert_with_mirror(&identity_store, &account) {
166 if made_here {
171 drop_orphaned_secret(&identity_store, &account.secret_ref, &account_id).await;
172 }
173 return Err(format!("account.key.verify: {e}"));
174 }
175 broker.publish_event::<crate::backend::mps_events::IdentityAccountsChanged>(&(), vec![], 0);
176 if matches!(account.secret_ref, SecretRef::Vault { .. }) {
177 crate::server::vault_handlers::publish_change(&broker);
178 }
179 if probe.valid {
181 crate::server::account_episodes::after_sign_in(&account_id);
182 }
183 Ok(AccountKeyVerifyResult {
184 valid: probe.valid,
185 error: None,
186 account_id: Some(account_id),
187 masked_tail: Some(account.context.get("masked_tail").cloned().unwrap_or_default()),
188 status: Some(account.status),
189 metadata: Some(account.context),
190 })
191}
192
193async fn probe_key(req: &VerifyKeyReq) -> Result<KeyProbe, AccountKeyVerifyResult> {
196 if !req.validate {
197 return Ok(KeyProbe {
198 status: "unknown".to_string(),
199 metadata: serde_json::json!({}),
200 masked_tail: crate::identity::key_validator::masked_tail(&req.api_key),
201 valid: false,
202 });
203 }
204 let outcome = crate::identity::key_validator::validate(&req.provider, &req.api_key).await;
205 if !outcome.valid {
206 return Err(AccountKeyVerifyResult {
207 valid: false,
208 error: Some(outcome.error.unwrap_or_else(|| "validation failed".to_string())),
209 account_id: None,
210 masked_tail: None,
211 status: None,
212 metadata: None,
213 });
214 }
215 Ok(KeyProbe { status: "valid".to_string(), metadata: outcome.metadata, masked_tail: outcome.masked_tail, valid: true })
216}
217
218struct StoredSecret {
219 secret_ref: SecretRef,
220 created: bool,
221}
222
223async fn store_secret(identity_store: &Arc<Store>, account_id: &str, req: &VerifyKeyReq, existing: Option<&IdentityAccount>) -> Result<StoredSecret, String> {
228 let (vault, aid, key) = (identity_store.clone(), account_id.to_string(), req.api_key.clone());
229 let (provider, name) = (req.provider.clone(), req.name.clone());
230 let current = existing.map(|a| a.secret_ref.clone());
231 tokio::task::spawn_blocking(move || match current {
232 Some(SecretRef::Keychain { service, account }) => {
233 crate::identity::secret_store::put(&aid, &key)?;
234 Ok(StoredSecret { secret_ref: SecretRef::Keychain { service, account }, created: false })
235 }
236 Some(reference @ SecretRef::Vault { .. }) => crate::backend::vault::account_key::replace(&vault, &aid, &reference, &key)
237 .map(|secret_ref| StoredSecret { secret_ref, created: false })
238 .or_else(|_| crate::backend::vault::account_key::create(&vault, &aid, &provider, &name, &key)
239 .map(|secret_ref| StoredSecret { secret_ref, created: true })),
240 _ => crate::backend::vault::account_key::create(&vault, &aid, &provider, &name, &key)
241 .map(|secret_ref| StoredSecret { secret_ref, created: true }),
242 })
243 .await
244 .map_err(|e| format!("account.key.verify: key task: {e}"))?
245 .map_err(|e| format!("account.key.verify: {e}"))
246}
247
248async fn drop_orphaned_secret(identity_store: &Arc<Store>, secret_ref: &SecretRef, account_id: &str) {
250 let (vault, secret_ref, aid) = (identity_store.clone(), secret_ref.clone(), account_id.to_string());
251 let gone = tokio::task::spawn_blocking(move || match &secret_ref {
252 SecretRef::Vault { .. } => crate::backend::vault::account_key::remove(&vault, &aid, &secret_ref),
253 _ => crate::identity::secret_store::delete(&aid),
254 })
255 .await
256 .unwrap_or_else(|je| Err(format!("join: {je}")));
257 if let Err(de) = gone {
258 tracing::warn!(target: "identity", "rollback of orphaned key for {account_id} failed: {de}");
259 }
260}
261
262fn key_account_row(
265 req: &VerifyKeyReq,
266 account_id: &str,
267 existing: Option<&IdentityAccount>,
268 secret_ref: SecretRef,
269 status: String,
270 metadata: serde_json::Value,
271 masked_tail: &str,
272) -> IdentityAccount {
273 let mut context = existing.map(|a| a.context.clone()).unwrap_or_else(|| serde_json::json!({}));
274 if !context.is_object() {
275 context = serde_json::json!({});
276 }
277 merge_json_object(&mut context, &req.context);
278 merge_json_object(&mut context, &metadata);
279 if let serde_json::Value::Object(ref mut m) = context {
280 m.insert("masked_tail".to_string(), serde_json::json!(masked_tail));
281 }
282 let now = agentmux_common::time::now_ms();
283 let created_at = existing.map(|a| a.created_at).filter(|&c| c != 0).unwrap_or(now);
284 IdentityAccount {
285 id: account_id.to_string(),
286 name: req.name.clone(),
287 provider: req.provider.clone(),
288 kind: if req.kind.is_empty() { "api_key".to_string() } else { req.kind.clone() },
289 display_name: req.display_name.clone(),
290 secret_ref,
291 context,
292 status,
293 created_at,
294 updated_at: now,
295 }
296}
297
298#[cfg(test)]
299mod tests {
300 use serde_json::json;
301
302 use super::*;
303
304 fn account(id: &str, context: serde_json::Value) -> IdentityAccount {
305 serde_json::from_value(json!({
306 "id": id, "name": id, "provider": "anthropic", "kind": "api_key",
307 "secret_ref": { "backend": "env", "env_var": "K" }, "context": context,
308 }))
309 .unwrap()
310 }
311
312 fn key_req(extra: serde_json::Value) -> VerifyKeyReq {
313 let mut base = json!({ "provider": "openai", "name": "work", "apiKey": "sk-secret-1234" });
314 base.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
315 serde_json::from_value(base).unwrap()
316 }
317
318 #[test]
319 fn a_stored_keys_context_is_the_old_then_the_users_then_the_probes_then_the_tail() {
320 let mut existing = account("acct-1", json!({ "note": "kept", "scopes": "old" }));
321 existing.created_at = 42;
322 let req = key_req(json!({ "context": { "note": "from the user", "extra": 1 } }));
323 let row = key_account_row(&req, "acct-1", Some(&existing), SecretRef::Vault { entry: "e1".into(), link_id: Some("link-1".into()) }, "valid".to_string(), json!({ "scopes": "from the probe" }), "••••1234");
324 assert_eq!(row.context, json!({ "note": "from the user", "extra": 1, "scopes": "from the probe", "masked_tail": "••••1234" }));
325 assert_eq!((row.created_at, row.status.as_str(), row.kind.as_str()), (42, "valid", "api_key"));
326 assert_eq!(row.secret_ref, SecretRef::Vault { entry: "e1".into(), link_id: Some("link-1".into()) }, "the DB keeps a pointer, never the key");
327 }
328
329 #[test]
330 fn a_new_keys_row_has_its_own_time_and_the_kind_the_caller_gave() {
331 let before = agentmux_common::time::now_ms();
332 let row = key_account_row(&key_req(json!({ "kind": "pat", "displayName": "Work" })), "acct-2", None, SecretRef::Vault { entry: "e2".into(), link_id: None }, "unknown".to_string(), json!({}), "tail");
333 assert!(row.created_at >= before && row.created_at == row.updated_at);
334 assert_eq!((row.kind.as_str(), row.display_name.as_str(), row.id.as_str()), ("pat", "Work", "acct-2"));
335 }
336
337 fn vault() -> Arc<Store> {
338 crate::backend::vault::seal::use_test_key();
339 let store = Store::open_in_memory().unwrap();
340 store.apply_identity_schema_for_tests().unwrap();
341 Arc::new(store)
342 }
343
344 #[tokio::test]
345 async fn a_key_added_to_a_new_account_is_a_vault_entry_the_account_reads() {
346 let vault = vault();
347 let req = key_req(json!({ "provider": "anthropic", "name": "work" }));
348 let StoredSecret { secret_ref, created } = store_secret(&vault, "acct-1", &req, None).await.unwrap();
349 assert!(created);
350 let SecretRef::Vault { entry, .. } = &secret_ref else { panic!("expected a Vault pointer") };
351 let row = vault.vault_get(entry).unwrap().expect("the entry exists");
352 assert_eq!((row.kind.as_str(), row.label.as_str()), ("api-key", "anthropic account key: work"));
353 let mut account = key_account_row(&req, "acct-1", None, secret_ref.clone(), "valid".into(), json!({}), "tail");
354 account.provider = "anthropic".into();
355 let key = crate::identity::resolver::secret::resolve_account_secret(&account, &vault, &vault).unwrap();
356 assert_eq!(key, "sk-secret-1234");
357 assert!(!serde_json::to_string(&account).unwrap().contains("sk-secret"), "the row never holds the key");
358 }
359
360 #[tokio::test]
361 async fn a_replaced_key_goes_into_the_same_entry_and_a_missing_entry_is_made_again() {
362 let vault = vault();
363 let first = store_secret(&vault, "acct-1", &key_req(json!({})), None).await.unwrap().secret_ref;
364 let mut existing = account("acct-1", json!({}));
365 existing.secret_ref = first.clone();
366 let StoredSecret { secret_ref: again, created } = store_secret(&vault, "acct-1", &key_req(json!({ "apiKey": "sk-new-5678" })), Some(&existing)).await.unwrap();
367 assert!(!created);
368 assert_eq!(again, first, "the same entry");
369 assert_eq!(&**crate::backend::vault::account_key::read(&vault, "acct-1", &first).unwrap(), "sk-new-5678");
370 crate::backend::vault::account_key::remove(&vault, "acct-1", &first).unwrap();
371 let StoredSecret { secret_ref: remade, created } = store_secret(&vault, "acct-1", &key_req(json!({ "apiKey": "sk-newer-9012" })), Some(&existing)).await.unwrap();
372 assert!(created);
373 assert_eq!(&**crate::backend::vault::account_key::read(&vault, "acct-1", &remade).unwrap(), "sk-newer-9012");
374 }
375
376 #[tokio::test]
377 async fn a_new_accounts_entry_is_removed_when_the_row_could_not_be_saved() {
378 let vault = vault();
379 let secret_ref = store_secret(&vault, "acct-1", &key_req(json!({})), None).await.unwrap().secret_ref;
380 drop_orphaned_secret(&vault, &secret_ref, "acct-1").await;
381 let SecretRef::Vault { entry, .. } = &secret_ref else { panic!("expected a Vault pointer") };
382 assert!(vault.vault_get(entry).unwrap().is_none());
383 }
384
385 #[tokio::test]
386 async fn a_reused_or_unowned_entry_gets_a_new_pointer_when_the_account_key_is_saved() {
387 for legacy in [false, true] {
388 let vault = vault();
389 let req = key_req(json!({}));
390 let first = store_secret(&vault, "acct-1", &req, None).await.unwrap().secret_ref;
391 let SecretRef::Vault { entry, .. } = &first else { panic!("expected a Vault pointer") };
392 crate::backend::vault::delete(&vault, entry).unwrap();
393 let second = store_secret(&vault, "acct-2", &req, None).await.unwrap().secret_ref;
394 let mut previous = account("acct-1", json!({}));
395 previous.secret_ref = if legacy { SecretRef::Vault { entry: entry.clone(), link_id: None } } else { first };
396 vault.identity_upsert(&previous).unwrap();
397 let StoredSecret { secret_ref: remade, created } = store_secret(&vault, "acct-1", &key_req(json!({ "apiKey": "new-test-value" })), Some(&previous)).await.unwrap();
398 assert!(created);
399 assert!(remade != second, "saving the previous account creates its own entry");
400 assert!(crate::backend::vault::account_key::read(&vault, "acct-2", &second).is_ok_and(|value| &**value == "sk-secret-1234"));
401 assert!(crate::backend::vault::account_key::read(&vault, "acct-1", &remade).is_ok_and(|value| &**value == "new-test-value"));
402 }
403 }
404
405 fn refuse_account_saves(store: &Store) {
406 store.hold_for_tests().execute_batch(
407 "CREATE TRIGGER refuse_account_save BEFORE INSERT ON db_accounts BEGIN SELECT RAISE(ABORT, 'forced account save failure'); END;",
408 ).unwrap();
409 }
410
411 async fn failed_legacy_save_keeps_entry(already_bound: bool) {
412 let primary = vault();
413 let vault = vault();
414 let current = store_secret(&vault, "acct-1", &key_req(json!({})), None).await.unwrap().secret_ref;
415 let SecretRef::Vault { entry, .. } = ¤t else { panic!("expected a Vault pointer") };
416 let mut previous = account("acct-1", json!({}));
417 previous.secret_ref = SecretRef::Vault { entry: entry.clone(), link_id: None };
418 primary.identity_upsert_with_mirror(&vault, &previous).unwrap();
419 if already_bound {
420 assert!(crate::backend::vault::account_key::read(&vault, "acct-1", &previous.secret_ref).is_ok());
421 }
422 refuse_account_saves(&primary);
423 let result = verify_account_key(primary.clone(), vault.clone(), Arc::new(Broker::new()), json!({
424 "accountId": "acct-1", "provider": "openai", "name": "work", "apiKey": "replacement-test-value", "validate": false,
425 })).await;
426 assert!(matches!(result, Err(ref error) if error.contains("forced account save failure")));
427 assert!(primary.identity_get("acct-1").unwrap().unwrap().secret_ref == previous.secret_ref);
428 assert!(vault.identity_get("acct-1").unwrap().unwrap().secret_ref == current);
429 assert!(crate::backend::vault::account_key::read(&vault, "acct-1", &previous.secret_ref)
430 .is_ok_and(|value| &**value == "replacement-test-value"), "a failed row save must not delete the existing credential");
431 }
432
433 #[tokio::test]
434 async fn a_legacy_pointer_bound_during_replace_survives_a_failed_account_save() {
435 failed_legacy_save_keeps_entry(false).await;
436 }
437
438 #[tokio::test]
439 async fn a_legacy_pointer_bound_only_in_the_mirror_survives_a_failed_account_save() {
440 failed_legacy_save_keeps_entry(true).await;
441 }
442
443 #[tokio::test]
444 async fn a_new_or_recreated_entry_is_rolled_back_after_a_failed_account_save() {
445 for existing_account in [false, true] {
446 let primary = vault();
447 let vault = vault();
448 if existing_account {
449 let current = store_secret(&vault, "acct-1", &key_req(json!({})), None).await.unwrap().secret_ref;
450 let mut previous = account("acct-1", json!({}));
451 previous.secret_ref = current;
452 primary.identity_upsert_with_mirror(&vault, &previous).unwrap();
453 crate::backend::vault::account_key::remove(&vault, "acct-1", &previous.secret_ref).unwrap();
454 }
455 refuse_account_saves(&primary);
456 let result = verify_account_key(primary, vault.clone(), Arc::new(Broker::new()), json!({
457 "accountId": "acct-1", "provider": "openai", "name": "work", "apiKey": "replacement-test-value", "validate": false,
458 })).await;
459 assert!(matches!(result, Err(ref error) if error.contains("forced account save failure")));
460 assert!(vault.vault_count().unwrap() == 0, "only an entry created by this operation is rolled back");
461 }
462 }
463
464 #[test]
465 fn a_listed_account_takes_the_numbers_as_stored_or_loses_them() {
466 let mut listed = vec![account("a", json!({ "seq": 9 })), account("b", json!({})), account("c", json!({ "seq": 1 }))];
467 let stored = vec![account("a", json!({})), account("b", json!({ "seq": 2, "seqmax": 3 }))];
468 copy_stored_numbers(&mut listed, &stored);
469 assert_eq!(listed[0].context, json!({}), "a number the store no longer holds is dropped");
470 assert_eq!(listed[1].context, json!({ "seq": 2, "seqmax": 3 }));
471 assert_eq!(listed[2].context, json!({ "seq": 1 }), "an account the store doesn't know is left as listed");
472 }
473
474 #[test]
475 fn a_get_of_a_missing_account_names_the_id() {
476 let store = Store::open_in_memory().unwrap();
477 let err = get_identity_account(&store, "ghost").unwrap_err();
478 assert_eq!(err, "getidentityaccount: not found id=ghost");
479 }
480}