1use super::{kinds, record, seal, NewEntry, Store};
20use agentmux_common::time::now_ms;
21use std::collections::HashMap;
22use std::sync::{Mutex, OnceLock};
23
24pub const PREFIX: &str = "vault:";
26pub const GRANT_PREFIX: &str = "setting:";
28pub const SETTINGS: [&str; 1] = ["voice:groqApiKey"];
30pub const AGENTMUX: &str = "AgentMux";
32pub const USED: &str = "read by AgentMux for a setting";
34pub const ALLOWED: &str = "allowed for a setting";
36pub const WITHDRAWN: &str = "no longer allowed for a setting";
38pub const NOT_AVAILABLE: &str = "the Vault entry this setting names is not there, is not an API key, or was not allowed for this setting";
42const RECORD_EVERY_MS: i64 = 10 * 60 * 1000;
44
45pub fn entry_of(value: &str) -> Option<&str> {
47 let id = value.trim().strip_prefix(PREFIX)?.trim();
48 (!id.is_empty()).then_some(id)
49}
50
51pub fn reference(id: &str) -> String {
53 format!("{PREFIX}{id}")
54}
55
56pub fn grant_for(setting: &str) -> String {
58 format!("{GRANT_PREFIX}{setting}")
59}
60
61pub fn setting_of_grant(grant: &str) -> Option<&str> {
63 grant.strip_prefix(GRANT_PREFIX)
64}
65
66pub fn present(store: &Store, setting: &str, id: &str) -> bool {
68 matches!(store.vault_get(id), Ok(Some(row)) if row.kind == "api-key") && store.vault_grant_check(id, &grant_for(setting)).unwrap_or(false)
69}
70
71pub fn allow(store: &Store, id: &str, setting: &str, who: &str) -> Result<(), String> {
75 if !SETTINGS.contains(&setting) {
76 return Err(format!("{setting} is not a setting that can read a Vault key"));
77 }
78 let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
79 if row.kind != "api-key" {
80 return Err(format!("{} is not an API key, so a setting can't read it", row.label));
81 }
82 let grant = grant_for(setting);
83 store.vault_grant_add(&row.id, &grant, now_ms(), row.created_at).map_err(|e| e.to_string())?;
84 record(store, &row.id, &row.label, who, ALLOWED, setting, "done");
85 let mut others: Vec<String> = store.vault_grants().map_err(|e| e.to_string())?.into_iter().filter(|(entry, grants)| *entry != row.id && grants.contains(&grant)).map(|(entry, _)| entry).collect();
87 others.sort();
88 for other in others {
89 if store.vault_grant_revoke(&other, &grant).map_err(|e| e.to_string())? {
90 let label = store.vault_get(&other).ok().flatten().map(|r| r.label).unwrap_or_default();
91 record(store, &other, &label, who, WITHDRAWN, setting, "done");
92 }
93 }
94 Ok(())
95}
96
97fn due(entry: &str, now: i64) -> bool {
98 static LAST: OnceLock<Mutex<HashMap<String, i64>>> = OnceLock::new();
99 let mut last = LAST.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
100 let at = last.entry(entry.to_string()).or_insert(i64::MIN);
101 let due = now.saturating_sub(*at) >= RECORD_EVERY_MS;
102 if due {
103 *at = now;
104 }
105 due
106}
107
108pub fn read(store: &Store, setting: &str, id: &str, who: &str, what: &str) -> Result<zeroize::Zeroizing<String>, String> {
111 let fail = |why: String| {
112 tracing::info!(entry = %id, "a setting's Vault key could not be read: {why}");
113 NOT_AVAILABLE.to_string()
114 };
115 let row = match store.vault_get(id) {
116 Ok(Some(row)) if row.kind == "api-key" => row,
117 Ok(Some(row)) => return Err(fail(format!("{} is not an api-key entry", row.label))),
118 Ok(None) => return Err(fail(format!("the Vault has no entry {id}"))),
119 Err(e) => return Err(fail(e.to_string())),
120 };
121 if !store.vault_grant_check(&row.id, &grant_for(setting)).unwrap_or(false) {
122 return Err(fail(format!("{} was not allowed for {setting}", row.label)));
123 }
124 let kind = kinds::kind(&row.kind).ok_or_else(|| fail(format!("entry {} has an unknown kind", row.id)))?;
125 let key = seal::key(false).map_err(fail)?;
126 let parts = seal::open(&key, &row.id, &row.sealed).map_err(fail)?;
127 let value = parts.get(kind.parts[0]).filter(|v| !v.trim().is_empty()).ok_or_else(|| fail(format!("{} has no value saved", row.label)))?;
128 let value = zeroize::Zeroizing::new(value.to_string());
129 if due(&row.id, now_ms()) {
130 if let Err(e) = store.vault_touch(&row.id, now_ms()) {
131 tracing::warn!(error = %e, "vault: couldn't note a setting key's use");
132 }
133 record(store, &row.id, &row.label, who, USED, what, "done");
134 }
135 Ok(value)
136}
137
138pub fn keep(store: &Store, label: &str, value: &str) -> Result<String, String> {
140 let entry: NewEntry = serde_json::from_value(serde_json::json!({ "kind": "api-key", "label": label, "parts": { "value": value } })).map_err(|e| e.to_string())?;
141 super::create(store, entry)
142}
143
144pub fn move_setting(
152 store: &Store,
153 setting: &str,
154 label: &str,
155 current: Option<&str>,
156 write: impl FnOnce(serde_json::Map<String, serde_json::Value>) -> Result<(), String>,
157) -> Result<Option<String>, String> {
158 let Some(plain) = current.map(str::trim).filter(|v| !v.is_empty() && entry_of(v).is_none()) else { return Ok(None) };
159 let id = keep(store, label, plain)?;
160 if let Err(e) = allow(store, &id, setting, AGENTMUX) {
162 let _ = store.vault_delete(&id);
163 return Err(e);
164 }
165 let mut keys = serde_json::Map::new();
166 keys.insert(setting.to_string(), serde_json::Value::String(reference(&id)));
167 keys.insert(format!("{setting}Moved"), serde_json::Value::Bool(true));
168 if let Err(e) = write(keys) {
169 if let Err(del) = store.vault_delete(&id) {
170 tracing::warn!(entry = %id, error = %del, "vault: a key kept for a setting could not be taken back after the setting failed to save");
171 }
172 return Err(e);
173 }
174 record(store, &id, label, AGENTMUX, "kept from a setting", setting, "done");
176 Ok(Some(id))
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 const SETTING: &str = "voice:groqApiKey";
184
185 fn store() -> Store {
186 seal::use_test_key();
187 let store = Store::open_in_memory().unwrap();
188 store.apply_identity_schema_for_tests().unwrap();
189 store
190 }
191
192 fn allowed_key(store: &Store, value: &str) -> String {
194 let id = keep(store, "Groq key (voice input)", value).unwrap();
195 allow(store, &id, SETTING, super::super::PERSON).unwrap();
196 id
197 }
198
199 #[test]
200 fn a_reference_is_vault_colon_and_an_id() {
201 assert_eq!(entry_of("vault:abc-1"), Some("abc-1"));
202 assert_eq!(entry_of(" vault: abc-1 "), Some("abc-1"));
203 assert_eq!(entry_of("vault:"), None);
204 assert_eq!(entry_of("gsk_plain_value"), None);
205 assert_eq!(entry_of(&reference("e1")), Some("e1"));
206 assert_eq!(setting_of_grant(&grant_for(SETTING)), Some(SETTING));
207 assert_eq!(setting_of_grant("command:a:value"), None);
208 }
209
210 #[test]
211 fn an_allowed_key_is_read_back_and_the_use_is_recorded_under_who_used_it() {
212 let store = store();
213 let id = keep(&store, "Groq key read-back test", "gsk_test_0123456789").unwrap();
216 allow(&store, &id, SETTING, super::super::PERSON).unwrap();
217 assert!(present(&store, SETTING, &id));
218 assert_eq!(read(&store, SETTING, &id, "AgentMux voice input", "voice input").unwrap().as_str(), "gsk_test_0123456789");
219 let log = crate::backend::vault::activity(&store, 10).unwrap();
220 assert!(log.iter().any(|l| l.actor == "AgentMux voice input" && l.action == USED), "{:?}", log.iter().map(|l| (&l.actor, &l.action)).collect::<Vec<_>>());
221 let again = crate::backend::vault::activity(&store, 10).unwrap().len();
222 read(&store, SETTING, &id, "AgentMux voice input", "voice input").unwrap();
223 assert_eq!(crate::backend::vault::activity(&store, 10).unwrap().len(), again, "a second call in the window writes no second line");
224 }
225
226 #[test]
229 fn an_entry_a_setting_was_not_allowed_to_read_is_not_read_whatever_the_file_names() {
230 let store = store();
231 let other = keep(&store, "A payment key", "sk_live_payment_0123").unwrap();
232 assert!(!present(&store, SETTING, &other));
233 assert_eq!(read(&store, SETTING, &other, "w", "x").unwrap_err(), NOT_AVAILABLE);
234 let mine = allowed_key(&store, "gsk_mine_0123456789");
236 assert!(present(&store, SETTING, &mine) && !present(&store, "messaging:discord:token", &mine));
237 assert_eq!(read(&store, SETTING, &other, "w", "x").unwrap_err(), NOT_AVAILABLE, "still refused beside an allowed one");
238 assert!(store.vault_grant_revoke(&mine, &grant_for(SETTING)).unwrap());
240 assert_eq!(read(&store, SETTING, &mine, "w", "x").unwrap_err(), NOT_AVAILABLE);
241 let again = allowed_key(&store, "gsk_again_0123456789");
243 crate::backend::vault::delete(&store, &again).unwrap();
244 assert!(!store.vault_grant_check(&again, &grant_for(SETTING)).unwrap());
245 }
246
247 #[test]
248 fn allowing_another_entry_takes_the_setting_off_the_old_one_and_records_it() {
249 let store = store();
250 let old = keep(&store, "Old groq key", "gsk_old_0123456789").unwrap();
251 let new = keep(&store, "New groq key", "gsk_new_0123456789").unwrap();
252 allow(&store, &old, SETTING, "you").unwrap();
253 assert_eq!(read(&store, SETTING, &old, "w", "x").unwrap().as_str(), "gsk_old_0123456789");
254 allow(&store, &new, SETTING, "you").unwrap();
255 assert!(!present(&store, SETTING, &old) && present(&store, SETTING, &new));
257 assert_eq!(read(&store, SETTING, &old, "w", "x").unwrap_err(), NOT_AVAILABLE);
258 assert_eq!(read(&store, SETTING, &new, "w", "x").unwrap().as_str(), "gsk_new_0123456789");
259 assert!(!store.vault_grant_check(&old, &grant_for(SETTING)).unwrap() && store.vault_grant_check(&new, &grant_for(SETTING)).unwrap());
260 let log = crate::backend::vault::activity(&store, 20).unwrap();
262 let line = log.iter().find(|l| l.action == WITHDRAWN).expect("the removal is recorded");
263 assert_eq!((line.actor.as_str(), line.target.as_str(), line.entry_id.as_str()), ("you", SETTING, old.as_str()));
264 assert_eq!(log.iter().filter(|l| l.action == WITHDRAWN).count(), 1);
265 allow(&store, &new, SETTING, "you").unwrap();
267 assert!(store.vault_grant_check(&new, &grant_for(SETTING)).unwrap());
268 assert_eq!(crate::backend::vault::activity(&store, 20).unwrap().iter().filter(|l| l.action == WITHDRAWN).count(), 1);
269 }
270
271 #[test]
272 fn a_grant_that_is_not_the_settings_is_left_alone_when_the_setting_moves_to_another_entry() {
273 let store = store();
274 let key = keep(&store, "A groq key", "gsk_a_0123456789").unwrap();
275 let other = keep(&store, "Another key", "gsk_b_0123456789").unwrap();
276 let created = store.vault_get(&other).unwrap().unwrap().created_at;
277 store.vault_grant_add(&other, "command:deploy:value", now_ms(), created).unwrap();
278 allow(&store, &other, SETTING, "you").unwrap();
279 allow(&store, &key, SETTING, "you").unwrap();
280 assert!(store.vault_grant_check(&other, "command:deploy:value").unwrap(), "the other grant stays");
281 assert!(!store.vault_grant_check(&other, &grant_for(SETTING)).unwrap());
282 }
283
284 #[test]
285 fn only_an_api_key_and_only_a_listed_setting_can_be_allowed() {
286 let store = store();
287 let note: NewEntry = serde_json::from_value(serde_json::json!({ "kind": "note", "label": "A note", "parts": { "text": "x" } })).unwrap();
288 let note = crate::backend::vault::create(&store, note).unwrap();
289 assert!(allow(&store, ¬e, SETTING, "you").unwrap_err().contains("not an API key"));
290 let key = keep(&store, "A key", "gsk_x_0123456789").unwrap();
291 assert!(allow(&store, &key, "term:fontsize", "you").unwrap_err().contains("not a setting"));
292 assert!(allow(&store, "nope", SETTING, "you").is_err());
293 assert!(!present(&store, SETTING, &key), "nothing was allowed");
294 }
295
296 #[test]
297 fn a_grant_is_recorded_under_whoever_made_it() {
298 let store = store();
299 let id = keep(&store, "A key", "gsk_x_0123456789").unwrap();
300 allow(&store, &id, SETTING, "you").unwrap();
301 let log = crate::backend::vault::activity(&store, 10).unwrap();
302 assert!(log.iter().any(|l| l.actor == "you" && l.action == ALLOWED && l.target == SETTING));
303 }
304
305 #[test]
306 fn a_plain_key_moves_into_the_vault_with_its_grant_and_the_setting_becomes_a_reference() {
307 let store = store();
308 let mut written = None;
309 let id = move_setting(&store, SETTING, "Groq key (voice input)", Some(" gsk_plain_0123 "), |keys| {
310 written = Some(keys);
311 Ok(())
312 })
313 .unwrap()
314 .expect("moved");
315 let keys = written.unwrap();
316 assert_eq!(keys["voice:groqApiKey"], serde_json::json!(reference(&id)));
317 assert_eq!(keys["voice:groqApiKeyMoved"], serde_json::json!(true));
318 assert!(!serde_json::to_string(&keys).unwrap().contains("gsk_plain_0123"), "the value is not in what the settings file is given");
319 assert_eq!(read(&store, SETTING, &id, "t", "t").unwrap().as_str(), "gsk_plain_0123", "trimmed, kept in the Vault, and readable: the move made the grant");
320 let log = crate::backend::vault::activity(&store, 10).unwrap();
322 let moved = log.iter().find(|l| l.action == "kept from a setting").expect("the move is recorded");
323 assert_eq!(moved.actor, AGENTMUX);
324 let allowed = log.iter().find(|l| l.action == ALLOWED).expect("so is the grant");
325 assert_eq!(allowed.actor, AGENTMUX);
326 assert!(log.iter().all(|l| l.actor != super::super::PERSON || l.action != "kept from a setting"));
327 }
328
329 #[test]
330 fn nothing_moves_when_there_is_no_plain_key_and_a_reference_is_not_moved_again() {
331 let store = store();
332 for current in [None, Some(""), Some(" "), Some("vault:abc")] {
333 let moved = move_setting(&store, SETTING, "Groq", current, |_| panic!("nothing to write")).unwrap();
334 assert_eq!(moved, None, "{current:?}");
335 }
336 assert!(store.vault_list().unwrap().is_empty(), "no entry was made");
337 }
338
339 #[test]
340 fn a_settings_write_that_fails_leaves_no_entry_behind_and_the_plain_key_in_place() {
341 let store = store();
342 let err = move_setting(&store, SETTING, "Groq", Some("gsk_x"), |_| Err("settings.json was not changed".into())).unwrap_err();
343 assert!(err.contains("not changed"));
344 assert!(store.vault_list().unwrap().is_empty(), "the entry made for it was taken back");
345 assert!(store.vault_grants().unwrap().is_empty(), "and its grant went with it");
346 }
347
348 #[test]
349 fn a_missing_entry_and_a_note_get_the_same_answer() {
350 let store = store();
351 let note: NewEntry = serde_json::from_value(serde_json::json!({ "kind": "note", "label": "A note", "parts": { "text": "x" } })).unwrap();
352 let note = crate::backend::vault::create(&store, note).unwrap();
353 assert!(!present(&store, SETTING, ¬e) && !present(&store, SETTING, "nope"));
354 assert_eq!(read(&store, SETTING, "nope", "w", "x").unwrap_err(), NOT_AVAILABLE);
355 assert_eq!(read(&store, SETTING, ¬e, "w", "x").unwrap_err(), NOT_AVAILABLE);
356 }
357}