Skip to main content

agentmux_srv_core/backend/vault/
seal.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Vault's encryption at rest
5//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md ยง5.5).
6//!
7//! One random 256-bit Vault key lives in `secret_store` (the OS keychain, or
8//! the headless file store); each entry's secret parts are sealed with it
9//! (ChaCha20-Poly1305, a random nonce each time, the entry id as associated
10//! data, so a sealed value moved to another row doesn't open) and kept in
11//! the database. One keychain item rather than one per value: Windows'
12//! Credential Manager caps an item at 1280 characters, and macOS asks the
13//! person about every item separately.
14
15use std::collections::BTreeMap;
16use std::sync::Mutex;
17
18use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305, NONCE_LEN};
19use ring::rand::{SecureRandom, SystemRandom};
20use zeroize::{Zeroize, Zeroizing};
21
22use crate::identity::secret_store;
23
24/// The Vault key's id in `secret_store`.
25const KEY_ID: &str = "vault-key";
26const KEY_LEN: usize = 32;
27/// The first byte of every sealed value: its format.
28const FORMAT_V1: u8 = 1;
29
30/// An entry's secret parts by name. Values are wiped when it is dropped.
31#[derive(Default, serde::Deserialize)]
32#[serde(transparent)]
33pub struct Parts(pub BTreeMap<String, String>);
34
35impl Drop for Parts {
36    fn drop(&mut self) {
37        for v in self.0.values_mut() {
38            v.zeroize();
39        }
40    }
41}
42
43impl Parts {
44    pub fn get(&self, part: &str) -> Option<&str> {
45        self.0.get(part).map(String::as_str)
46    }
47}
48
49pub type Key = Zeroizing<[u8; KEY_LEN]>;
50
51/// The key, read once and then kept, so the keychain asks at most once.
52static CACHED: Mutex<Option<Key>> = Mutex::new(None);
53
54/// The Vault key. `create` makes one when the keychain has none, which is
55/// right only while the Vault has no entries: a new key can't open what an
56/// old one sealed.
57pub fn key(create: bool) -> Result<Key, String> {
58    let mut cached = CACHED.lock().unwrap_or_else(|p| p.into_inner());
59    if let Some(k) = cached.as_ref() {
60        return Ok(k.clone());
61    }
62    let key = match secret_store::get_optional(KEY_ID).map_err(|e| explain_key_error(&e))? {
63        Some(hex_key) => decode_key(&hex_key)?,
64        None if create => {
65            let mut k: Key = Zeroizing::new([0u8; KEY_LEN]);
66            SystemRandom::new().fill(&mut k[..]).map_err(|_| "the system's random source failed".to_string())?;
67            let encoded = Zeroizing::new(hex::encode(&k[..]));
68            secret_store::put(KEY_ID, &encoded)?;
69            tracing::info!(backend = secret_store::backend_name(), "vault: created the Vault key");
70            k
71        }
72        None => {
73            return Err(format!(
74                "the Vault key is missing from the {}: the Vault's entries can't be opened",
75                secret_store::backend_name()
76            ))
77        }
78    };
79    *cached = Some(key.clone());
80    Ok(key)
81}
82
83/// A keychain error reading the Vault key, in the Vault's words. On macOS an item
84/// another build wrote can't be read here without asking (a `task dev` or unsigned
85/// build sharing the key); the generic advice, to save it again, is wrong for the
86/// Vault: a new key would not open the entries the old one sealed.
87fn explain_key_error(err: &str) -> String {
88    if secret_store::is_needs_consent(err) {
89        "the Vault key was saved by a different AgentMux build than this one (this one is likely a development or unsigned build), which macOS won't let this build read without asking: open the Vault from the build that created it, normally the installed, signed AgentMux. Nothing was changed, and the entries are safe."
90            .to_string()
91    } else {
92        err.to_string()
93    }
94}
95
96fn decode_key(hex_key: &str) -> Result<Key, String> {
97    let bytes = Zeroizing::new(hex::decode(hex_key.trim()).map_err(|_| "the stored Vault key is damaged".to_string())?);
98    if bytes.len() != KEY_LEN {
99        return Err("the stored Vault key is damaged".into());
100    }
101    let mut k: Key = Zeroizing::new([0u8; KEY_LEN]);
102    k.copy_from_slice(&bytes);
103    Ok(k)
104}
105
106fn aead_key(key: &Key) -> LessSafeKey {
107    LessSafeKey::new(UnboundKey::new(&CHACHA20_POLY1305, &key[..]).expect("a 32-byte key"))
108}
109
110fn aad(entry_id: &str) -> Vec<u8> {
111    format!("agentmux-vault-v1:{entry_id}").into_bytes()
112}
113
114/// Seals `parts` for the entry `entry_id`.
115pub fn seal(key: &Key, entry_id: &str, parts: &Parts) -> Result<Vec<u8>, String> {
116    let mut nonce = [0u8; NONCE_LEN];
117    SystemRandom::new().fill(&mut nonce).map_err(|_| "the system's random source failed".to_string())?;
118    let mut buf = Zeroizing::new(serde_json::to_vec(&parts.0).map_err(|e| e.to_string())?);
119    aead_key(key)
120        .seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce), Aad::from(aad(entry_id)), &mut *buf)
121        .map_err(|_| "sealing failed".to_string())?;
122    let mut out = Vec::with_capacity(1 + NONCE_LEN + buf.len());
123    out.push(FORMAT_V1);
124    out.extend_from_slice(&nonce);
125    out.extend_from_slice(&buf);
126    Ok(out)
127}
128
129/// Opens what [`seal`] sealed for `entry_id`. Fails on any change to it,
130/// and on a value sealed for another entry.
131pub fn open(key: &Key, entry_id: &str, sealed: &[u8]) -> Result<Parts, String> {
132    let damaged = || format!("entry {entry_id} can't be opened: it was changed, or sealed with another Vault key");
133    if sealed.len() < 1 + NONCE_LEN || sealed[0] != FORMAT_V1 {
134        return Err(damaged());
135    }
136    let nonce = Nonce::try_assume_unique_for_key(&sealed[1..1 + NONCE_LEN]).map_err(|_| damaged())?;
137    let mut buf = Zeroizing::new(sealed[1 + NONCE_LEN..].to_vec());
138    let plain = aead_key(key).open_in_place(nonce, Aad::from(aad(entry_id)), &mut *buf).map_err(|_| damaged())?;
139    let map: BTreeMap<String, String> = serde_json::from_slice(plain).map_err(|_| damaged())?;
140    Ok(Parts(map))
141}
142
143#[cfg(any(test, feature = "test-support"))]
144pub fn test_key() -> Key {
145    Zeroizing::new([7u8; KEY_LEN])
146}
147
148/// Tests use [`test_key`] instead of the keychain.
149#[cfg(any(test, feature = "test-support"))]
150pub fn use_test_key() {
151    *CACHED.lock().unwrap_or_else(|p| p.into_inner()) = Some(test_key());
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    fn parts(pairs: &[(&str, &str)]) -> Parts {
159        Parts(pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect())
160    }
161
162    #[test]
163    fn a_sealed_entry_opens_and_holds_no_plaintext() {
164        let key = test_key();
165        let sealed = seal(&key, "e1", &parts(&[("value", "123-45-6789")])).unwrap();
166        assert!(!sealed.windows(11).any(|w| w == b"123-45-6789"));
167        assert_eq!(open(&key, "e1", &sealed).unwrap().get("value"), Some("123-45-6789"));
168    }
169
170    #[test]
171    fn a_keychain_that_wont_let_this_build_read_the_key_says_so_in_the_vaults_terms() {
172        let said = explain_key_error(secret_store::NEEDS_CONSENT);
173        assert!(said.contains("different AgentMux build than this one") && said.contains("entries are safe"), "{said}");
174        assert!(!said.contains("  "), "single spaces only: {said}");
175        // Not the generic advice to save it again: a new key would not open the old entries.
176        assert!(!said.contains("save it again") && !said.contains("re-enter"), "{said}");
177        assert_eq!(explain_key_error("keychain: locked"), "keychain: locked");
178    }
179
180    #[test]
181    fn sealing_twice_differs() {
182        let key = test_key();
183        let p = parts(&[("value", "x")]);
184        assert_ne!(seal(&key, "e1", &p).unwrap(), seal(&key, "e1", &p).unwrap());
185    }
186
187    #[test]
188    fn a_value_moved_to_another_entry_or_changed_doesnt_open() {
189        let key = test_key();
190        let mut sealed = seal(&key, "e1", &parts(&[("value", "secret")])).unwrap();
191        assert!(open(&key, "e2", &sealed).is_err(), "bound to its entry");
192        let last = sealed.len() - 1;
193        sealed[last] ^= 1;
194        assert!(open(&key, "e1", &sealed).is_err(), "tampering is caught");
195        let other: Key = Zeroizing::new([8u8; KEY_LEN]);
196        let sealed = seal(&key, "e1", &parts(&[("value", "secret")])).unwrap();
197        assert!(open(&other, "e1", &sealed).is_err(), "another key can't open it");
198    }
199
200    #[test]
201    fn a_damaged_stored_key_is_refused() {
202        assert!(decode_key("zz").is_err());
203        assert!(decode_key(&"ab".repeat(16)).is_err(), "16 bytes is too short");
204        assert!(decode_key(&"ab".repeat(32)).is_ok());
205    }
206}