Skip to main content

agentmux_srv_core/backend/vault/
setting_key.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A key a setting names as `vault:<entry id>` instead of holding it: srv's own reader of a service key
5//! (voice input's Groq key, and the other settings keys the same way when they move). The value is read
6//! inside srv at the moment of the call, goes into one outgoing request, and is never written to
7//! settings.json, a log or the renderer. The spelling is the one `endpoint_key` resolves for an agent's
8//! launch environment.
9//!
10//! **The grant lives on the entry, not in the settings file.** settings.json only names an entry; what lets
11//! a setting read it is a grant kept in the Vault (`setting:<key>` in `db_vault_grants`, bound to the entry
12//! it was given to), made by the Settings picker (the person's choice) or by AgentMux's own move of a plain
13//! key. So a file edit that points a setting at another entry reads nothing: the entry has no grant for it.
14//! The person sees it under the entry in the Vault and can take it back there. **One entry per setting:**
15//! allowing an entry takes the setting's grant off every other entry, each removal recorded, so the file
16//! alone can never point the setting back at an entry chosen before. A read records the use, once every
17//! few minutes per entry, not once per call.
18
19use super::{kinds, record, seal, NewEntry, Store};
20use agentmux_common::time::now_ms;
21use std::collections::HashMap;
22use std::sync::{Mutex, OnceLock};
23
24/// What a setting's value starts with when it names a Vault entry.
25pub const PREFIX: &str = "vault:";
26/// What a grant on an entry starts with when it lets a setting read the entry: `setting:<settings key>`.
27pub const GRANT_PREFIX: &str = "setting:";
28/// The settings that may name a Vault entry. A grant for any other name is refused.
29pub const SETTINGS: [&str; 1] = ["voice:groqApiKey"];
30/// Who is named in the Activity for what AgentMux does on its own, as opposed to the person.
31pub const AGENTMUX: &str = "AgentMux";
32/// The activity line for a use, listed with the other uses of a value.
33pub const USED: &str = "read by AgentMux for a setting";
34/// The activity line for the grant.
35pub const ALLOWED: &str = "allowed for a setting";
36/// The activity line for a grant taken off an entry because another entry was allowed for the setting.
37pub const WITHDRAWN: &str = "no longer allowed for a setting";
38/// The one answer for a missing entry, an entry of another kind, an entry the setting was not allowed to
39/// read and a Vault that could not be opened, so a setting's error never says which entries exist; the
40/// reason is in srv's log.
41pub 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";
42/// How often a use of the same entry is written to the activity log.
43const RECORD_EVERY_MS: i64 = 10 * 60 * 1000;
44
45/// The entry id a setting value names, when it is a `vault:<id>` reference.
46pub 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
51/// The setting value that names entry `id`.
52pub fn reference(id: &str) -> String {
53    format!("{PREFIX}{id}")
54}
55
56/// The grant that lets `setting` read an entry.
57pub fn grant_for(setting: &str) -> String {
58    format!("{GRANT_PREFIX}{setting}")
59}
60
61/// The setting a grant on an entry is for, when it is one.
62pub fn setting_of_grant(grant: &str) -> Option<&str> {
63    grant.strip_prefix(GRANT_PREFIX)
64}
65
66/// Whether the Vault has an `api-key` entry with this id that `setting` may read. Opens nothing.
67pub 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
71/// Lets `setting` read entry `id`, recorded under `who`: the person's choice in Settings, or AgentMux's own
72/// move of a key that sat in the file. Only an `api-key` entry, and only for a setting that is on the list.
73/// One entry per setting: the setting's grant comes off every other entry, each removal recorded under `who`.
74pub 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    // The new grant is in before the old ones go: a failure part way leaves the setting readable, never unreadable.
86    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
108/// The entry's value for `setting`, recorded as a use by `who` for `what` (`"voice input"`). Only an entry
109/// that `setting` was allowed to read: the setting file's word alone is not enough.
110pub 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
138/// Keeps `value` as a new `api-key` entry labelled `label` in the Personal Vault and returns its id.
139pub 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
144/// Moves a key that sits in settings.json as plain text into the Vault: keeps it as an `api-key` entry
145/// labelled `label`, then has `write` replace the setting with its `vault:<id>` reference and set
146/// `<setting>Moved` (so Settings can say so once). `current` is the setting's value as the file has it.
147/// Returns the new entry's id, or `None` when there was nothing to move (unset, blank, or already a
148/// reference). Whether it already ran is read from the value alone, never from a marker. When `write`
149/// fails the new entry is deleted again and the plain key stays where it was, so a later start tries
150/// again and nothing is kept twice.
151pub 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    // The grant first: a reference with no grant would read nothing, and a failed grant leaves no entry.
161    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    // AgentMux did this on its own at start, not the person.
175    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    /// A kept key the setting was allowed to read, as the Settings picker makes one.
193    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        // Its own label: `due` keeps one process-wide clock per entry id, and ids come from kind and label,
214        // so a test that reads a key under the shared label first would make this one's first read "not due".
215        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    /// The file only names an entry: an entry the setting was not allowed to read is not read, whatever
227    /// the file says (a tidying agent, a bad merge).
228    #[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        // Allowed for one setting is not allowed for another, and a grant is for its own entry only.
235        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        // Taking the grant back in the Vault takes the reading with it.
239        assert!(store.vault_grant_revoke(&mine, &grant_for(SETTING)).unwrap());
240        assert_eq!(read(&store, SETTING, &mine, "w", "x").unwrap_err(), NOT_AVAILABLE);
241        // Deleting an entry takes its grant, so an entry made again under the same id starts with none.
242        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        // The old entry is refused on read, as an entry that was never allowed; the new one reads.
256        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        // The removal is a line in the Vault's history, under who chose and on the old entry.
261        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        // Choosing the same entry again takes nothing off and records no removal.
266        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, &note, 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        // The start-up move is AgentMux's own doing, not the person's.
321        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, &note) && !present(&store, SETTING, "nope"));
354        assert_eq!(read(&store, SETTING, "nope", "w", "x").unwrap_err(), NOT_AVAILABLE);
355        assert_eq!(read(&store, SETTING, &note, "w", "x").unwrap_err(), NOT_AVAILABLE);
356    }
357}