1use super::{kinds, seal, NewEntry, Store};
9use crate::backend::storage::{store::SecretRef, vault::VaultRow};
10use crate::backend::transcript::withhold_sources;
11use std::collections::BTreeMap;
12
13pub const TAG: &str = "account-key";
15
16fn label(provider: &str, name: &str) -> String {
18 format!("{provider} account key: {name}")
19}
20
21fn parts(key: &str) -> seal::Parts {
22 seal::Parts(BTreeMap::from([("value".to_string(), key.to_string())]))
23}
24
25fn note(account_id: &str) -> String {
26 format!("Added in Connectors > Accounts for the account {account_id}. The account reads its key from here.")
27}
28
29pub fn create(store: &Store, account_id: &str, provider: &str, name: &str, key: &str) -> Result<SecretRef, String> {
31 let fields = BTreeMap::from([
32 ("service".to_string(), provider.to_string()),
33 ("notes".to_string(), note(account_id)),
34 ]);
35 let entry = NewEntry { kind: "api-key".into(), label: label(provider, name), fields, tags: vec![TAG.to_string()], parts: parts(key) };
36 let link_id = super::new_link_id();
37 let (id, label) = super::insert_unrecorded_bound(store, entry, super::PERSONAL_VAULT, Some(&link_id))
38 .map_err(|_| "could not create the account key entry")?;
39 super::record(store, &id, &label, super::PERSON, "created", "", "done");
40 withhold_sources::account_key(&id, key);
41 Ok(SecretRef::Vault { entry: id, link_id: Some(link_id) })
42}
43
44fn checked(store: &Store, account_id: &str, reference: &SecretRef) -> Result<(VaultRow, String), String> {
45 store.vault_account_key_row(account_id, reference, &super::new_link_id(), ¬e(account_id))
46 .map_err(|_| "could not check the account key entry identity".to_string())?
47 .ok_or_else(|| {
48 tracing::warn!(target: "identity", "account.key: refused a missing or unowned Vault entry");
49 "the Vault entry that holds this account's key is gone or no longer belongs to it".to_string()
50 })
51}
52
53pub fn replace(store: &Store, account_id: &str, reference: &SecretRef, key: &str) -> Result<SecretRef, String> {
55 let (row, link_id) = checked(store, account_id, reference)?;
56 if row.kind != "api-key" { return Err("the account key entry is not an api-key entry".into()); }
57 let kept = super::versions::of(&row, super::PERSON, "replaced");
58 let (was, was_fields) = (row.sealed.clone(), row.fields.clone());
59 let id = row.id.clone();
60 let changed = VaultRow { sealed: seal::seal(&seal::key(false)?, &id, &parts(key))?, updated_at: super::now_ms(), ..row };
61 if !store.vault_update_kept_bound(&changed, &was, &was_fields, Some(&kept), Some(&link_id)).map_err(|_| "could not replace the account key")? {
62 return Err("the account key entry changed while replacing it".into());
63 }
64 super::versions::prune(store);
65 super::record(store, &id, &changed.label, super::PERSON, "replaced", "", "done");
66 withhold_sources::account_key(&id, key);
67 Ok(SecretRef::Vault { entry: id, link_id: Some(link_id) })
68}
69
70pub fn read(store: &Store, account_id: &str, reference: &SecretRef) -> Result<zeroize::Zeroizing<String>, String> {
73 let (row, _) = checked(store, account_id, reference)?;
74 let kind = kinds::kind(&row.kind).filter(|k| k.name == "api-key").ok_or_else(|| "the Vault entry that holds this account's key is not an api-key entry".to_string())?;
75 let opened = seal::open(&seal::key(false)?, &row.id, &row.sealed).map_err(|_| "the account key entry could not be opened")?;
76 let value = opened.get(kind.parts[0]).ok_or_else(|| "the Vault entry that holds this account's key has no value".to_string())?;
77 withhold_sources::account_key(&row.id, value);
78 Ok(zeroize::Zeroizing::new(value.to_string()))
79}
80
81pub fn remove(store: &Store, account_id: &str, reference: &SecretRef) -> Result<(), String> {
83 let Some((row, link_id)) = store.vault_account_key_row(account_id, reference, &super::new_link_id(), ¬e(account_id))
84 .map_err(|_| "could not check the account key entry identity")? else {
85 tracing::warn!(target: "identity", "account.key: left a missing or unowned Vault entry alone");
86 return Ok(());
87 };
88 if store.vault_delete_bound(&row.id, Some(&link_id)).map_err(|_| "could not remove the account key entry")? {
89 super::requests::requests().forget_entry(&row.id);
90 super::record(store, &row.id, &row.label, super::PERSON, "deleted", "", "done");
91 }
92 Ok(())
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 fn entry(reference: &SecretRef) -> &str {
100 let SecretRef::Vault { entry, .. } = reference else { panic!("expected a Vault pointer") };
101 entry
102 }
103
104 fn read(store: &Store, reference: &SecretRef) -> Result<zeroize::Zeroizing<String>, String> {
105 super::read(store, "acct-1", reference)
106 }
107
108 fn replace(store: &Store, reference: &SecretRef, key: &str) -> Result<SecretRef, String> {
109 super::replace(store, "acct-1", reference, key)
110 }
111
112 fn remove(store: &Store, reference: &SecretRef) -> Result<(), String> {
113 super::remove(store, "acct-1", reference)
114 }
115
116 fn store() -> Store {
117 seal::use_test_key();
118 let store = Store::open_in_memory().unwrap();
119 store.apply_identity_schema_for_tests().unwrap();
120 store
121 }
122
123 #[test]
124 fn an_account_key_is_an_api_key_entry_that_reads_back_and_is_replaced_in_place() {
125 let store = store();
126 let id = create(&store, "acct-1", "Anthropic", "work", "sk-ant-one").unwrap();
127 let row = store.vault_get(entry(&id)).unwrap().unwrap();
128 assert_eq!((row.kind.as_str(), row.label.as_str()), ("api-key", "Anthropic account key: work"));
129 assert!(row.tags.contains(TAG));
130 assert_eq!(&**read(&store, &id).unwrap(), "sk-ant-one");
131 replace(&store, &id, "sk-ant-two").unwrap();
132 assert_eq!(&**read(&store, &id).unwrap(), "sk-ant-two");
133 assert_eq!(store.vault_get(entry(&id)).unwrap().unwrap().label, row.label, "the label stays");
134 }
135
136 #[test]
137 fn a_key_made_replaced_or_read_is_withheld_from_transcripts() {
138 let store = store();
139 let made = create(&store, "acct-1", "Anthropic", "work", "sk-ant-made-aaaaaaaaaaaaaaaa").unwrap();
140 assert!(crate::backend::transcript::withhold::holds("the key sk-ant-made-aaaaaaaaaaaaaaaa was printed"));
141 replace(&store, &made, "sk-ant-replaced-bbbbbbbbbbbbbbbb").unwrap();
142 assert!(crate::backend::transcript::withhold::holds("sk-ant-replaced-bbbbbbbbbbbbbbbb"));
143 let other = store.vault_get(entry(&made)).unwrap().unwrap();
144 let sealed = seal::seal(&seal::key(false).unwrap(), &other.id, &seal::Parts(BTreeMap::from([("value".to_string(), "sk-ant-read-cccccccccccccccc".to_string())]))).unwrap();
145 store.vault_update(&crate::backend::storage::vault::VaultRow { sealed, ..other }).unwrap();
146 assert!(!crate::backend::transcript::withhold::holds("sk-ant-read-cccccccccccccccc"));
147 read(&store, &made).unwrap();
148 assert!(crate::backend::transcript::withhold::holds("sk-ant-read-cccccccccccccccc"), "a read registers it too");
149 }
150
151 #[test]
152 fn a_removed_entry_reads_as_gone_and_is_removed_again_without_error() {
153 let store = store();
154 let id = create(&store, "acct-1", "Anthropic", "work", "sk-ant-one").unwrap();
155 remove(&store, &id).unwrap();
156 assert!(read(&store, &id).unwrap_err().contains("is gone"));
157 remove(&store, &id).unwrap();
158 }
159
160 #[test]
161 fn a_reused_entry_does_not_let_the_previous_account_read_replace_or_remove_it() {
162 let store = store();
163 let previous = create(&store, "account-a", "provider", "same-name", "first-test-value").unwrap();
164 super::super::delete(&store, entry(&previous)).unwrap();
165 let current = create(&store, "account-b", "provider", "same-name", "second-test-value").unwrap();
166 assert!(entry(&previous) == entry(¤t), "the label-derived entry id is reused");
167 assert!(previous != current, "the non-reusable link id is different");
168 assert!(read(&store, &previous).is_err(), "the previous account must not read the replacement entry");
169 assert!(replace(&store, &previous, "third-test-value").is_err(), "the previous account must not replace another account's key");
170 remove(&store, &previous).unwrap();
171 assert!(read(&store, ¤t).is_ok_and(|value| &**value == "second-test-value"), "the current account keeps its own key");
172 }
173
174 fn legacy(store: &Store, reference: &SecretRef) -> crate::backend::storage::store::IdentityAccount {
175 let account = serde_json::from_value(serde_json::json!({
176 "id": "acct-1", "name": "work", "provider": "provider", "kind": "api_key",
177 "secret_ref": { "backend": "vault", "entry": entry(reference) },
178 })).unwrap();
179 store.identity_upsert(&account).unwrap();
180 account
181 }
182
183 #[test]
184 fn a_legacy_pointer_with_a_matching_note_is_bound_once_and_keeps_working() {
185 let store = store();
186 let current = create(&store, "acct-1", "provider", "same-name", "first-test-value").unwrap();
187 let account = legacy(&store, ¤t);
188 assert!(read(&store, &account.secret_ref).is_ok());
189 assert!(store.identity_get("acct-1").unwrap().unwrap().secret_ref == current);
190 store.vault_set_fields(entry(¤t), "{}").unwrap();
191 store.identity_upsert(&account).unwrap();
192 assert!(store.identity_get("acct-1").unwrap().unwrap().secret_ref == current, "a stale account save preserves the binding");
193 assert!(read(&store, &account.secret_ref).is_ok(), "a stale legacy pointer uses the persisted binding, not the note again");
194 assert!(replace(&store, &account.secret_ref, "second-test-value").unwrap() == current);
195 super::super::delete(&store, entry(¤t)).unwrap();
196 let reused = create(&store, "acct-1", "provider", "same-name", "third-test-value").unwrap();
197 assert!(read(&store, &account.secret_ref).is_err(), "even another matching note cannot rebind a migrated pointer");
198 assert!(replace(&store, &account.secret_ref, "fourth-test-value").is_err());
199 remove(&store, &account.secret_ref).unwrap();
200 assert!(read(&store, &reused).is_ok_and(|value| &**value == "third-test-value"));
201 }
202
203 fn refuses_legacy(store: &Store, current: &SecretRef) {
204 let account = legacy(store, current);
205 assert!(read(store, &account.secret_ref).is_err());
206 assert!(replace(store, &account.secret_ref, "replacement-test-value").is_err());
207 remove(store, &account.secret_ref).unwrap();
208 assert!(store.identity_get("acct-1").unwrap().unwrap().secret_ref == account.secret_ref);
209 assert!(read(store, current).is_ok_and(|value| &**value == "first-test-value"));
210 }
211
212 #[test]
213 fn a_legacy_pointer_without_an_account_note_is_refused() {
214 let store = store();
215 let current = create(&store, "acct-1", "provider", "same-name", "first-test-value").unwrap();
216 store.vault_set_fields(entry(¤t), "{}").unwrap();
217 refuses_legacy(&store, ¤t);
218 }
219
220 #[test]
221 fn a_legacy_pointer_with_another_accounts_note_is_refused() {
222 let store = store();
223 let current = create(&store, "account-b", "provider", "same-name", "first-test-value").unwrap();
224 refuses_legacy(&store, ¤t);
225 }
226
227 #[test]
228 fn a_legacy_pointer_can_be_bound_by_replace_or_remove_before_its_first_read() {
229 for removing in [false, true] {
230 let store = store();
231 let current = create(&store, "acct-1", "provider", "same-name", "first-test-value").unwrap();
232 let account = legacy(&store, ¤t);
233 if removing {
234 remove(&store, &account.secret_ref).unwrap();
235 assert!(store.vault_get(entry(¤t)).unwrap().is_none());
236 } else {
237 assert!(replace(&store, &account.secret_ref, "second-test-value").unwrap() == current);
238 assert!(read(&store, ¤t).is_ok_and(|value| &**value == "second-test-value"));
239 }
240 assert!(store.identity_get("acct-1").unwrap().unwrap().secret_ref == current);
241 }
242 }
243
244 #[test]
245 fn a_legacy_entry_without_a_link_gets_one_before_its_first_read() {
246 let store = store();
247 let id = super::super::create(&store, NewEntry {
248 kind: "api-key".into(), label: "legacy fixture".into(),
249 fields: BTreeMap::from([("notes".into(), note("acct-1"))]),
250 tags: Vec::new(), parts: parts("first-test-value"),
251 }).unwrap();
252 let account = legacy(&store, &SecretRef::Vault { entry: id.clone(), link_id: None });
253 assert!(store.vault_link_primary(&id).unwrap().is_none());
254 assert!(read(&store, &account.secret_ref).is_ok());
255 let saved = store.identity_get("acct-1").unwrap().unwrap().secret_ref;
256 assert!(matches!(saved, SecretRef::Vault { link_id: Some(_), .. }));
257 assert!(read(&store, &saved).is_ok());
258 }
259
260 #[test]
261 fn a_checked_entry_reused_before_a_write_cannot_be_replaced_or_removed() {
262 let store = store();
263 let previous = create(&store, "acct-1", "provider", "same-name", "first-test-value").unwrap();
264 let (row, link_id) = checked(&store, "acct-1", &previous).unwrap();
265 super::super::delete(&store, &row.id).unwrap();
266 let current = create(&store, "account-b", "provider", "same-name", "second-test-value").unwrap();
267 let current_row = store.vault_get(entry(¤t)).unwrap().unwrap();
268 assert!(!store.vault_update_kept_bound(¤t_row, ¤t_row.sealed, ¤t_row.fields, None, Some(&link_id)).unwrap());
269 assert!(!store.vault_delete_bound(&row.id, Some(&link_id)).unwrap());
270 assert!(read(&store, ¤t).is_ok_and(|value| &**value == "second-test-value"));
271 }
272
273 #[test]
274 fn no_model_route_takes_an_account_key_for_its_own() {
275 let store = store();
276 create(&store, "acct-1", "OpenRouter", "work", "sk-or-one").unwrap();
277 assert!(!super::super::route_key::present(&store, "OpenRouter API key"));
278 }
279}