Skip to main content

kernel/
snapshot_store.rs

1//! Where the snapshot signing key lives (`snapshot-auth.ts` `loadSnapshotKey`, `secretToolKeyring`):
2//! `ULTRON_RLM_SNAPSHOT_KEY_STORE` = `file` (default) keeps `<agentDir>/rlm-snapshot.key`; `auto` moves the key into
3//! the OS keyring when one answers (through libsecret's `secret-tool`), leaving a marker file; `keyring` insists on
4//! the keyring and otherwise uses a key for this process only. Exposure reduction, not secrecy: model code runs as
5//! the same user. `secret-tool` is found on the session's `PATH` only, and runs with the session's desktop variables.
6
7use crate::snapshot::{KEY_BYTES, SNAPSHOT_KEY_FILE, load_or_create_snapshot_key, parse_key};
8use std::io::Write;
9use std::os::unix::fs::OpenOptionsExt;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::time::Duration;
13
14pub const RLM_SNAPSHOT_KEY_STORE_ENV: &str = "ULTRON_RLM_SNAPSHOT_KEY_STORE";
15
16/// Marker left in place of the key file once the key lives in the OS keyring; it holds no secret.
17pub const SNAPSHOT_KEYRING_MARKER: &str = "rlm-snapshot.key.keyring";
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum KeyStore {
21    Auto,
22    Keyring,
23    File,
24}
25
26impl KeyStore {
27    /// `ULTRON_RLM_SNAPSHOT_KEY_STORE` (trimmed, any case): `auto` or `keyring`, anything else the file.
28    pub fn from_setting(value: Option<&str>) -> KeyStore {
29        match value.map(|v| v.trim().to_lowercase()).as_deref() {
30            Some("auto") => KeyStore::Auto,
31            Some("keyring") => KeyStore::Keyring,
32            _ => KeyStore::File,
33        }
34    }
35}
36
37/// Where a loaded key lives: the OS keyring, the profile file, or only this process (its snapshots do not outlive
38/// it).
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum KeySource {
41    Keyring,
42    File,
43    Process,
44}
45
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct LoadedSnapshotKey {
48    pub key: Vec<u8>,
49    pub source: KeySource,
50    pub warning: Option<String>,
51}
52
53/// What a keyring lookup found: `None` when the store cannot be reached (no Secret Service, locked keyring, a
54/// timeout), `Some(None)` when it holds no key.
55pub type Lookup = Option<Option<String>>;
56
57/// A secret store outside the profile directory (`SnapshotKeyring`).
58pub trait SnapshotKeyring {
59    fn lookup(&self) -> Lookup;
60    fn store(&self, hex: &str) -> bool;
61}
62
63/// The login keyring through `secret-tool` (GNOME Keyring, KWallet's Secret Service, KeePassXC), keyed by the
64/// resolved profile directory. A call that does not answer within the timeout (an unlock prompt nobody answers)
65/// counts as unavailable, and is killed.
66pub struct SecretToolKeyring {
67    /// The executable, or `None` when the session's `PATH` has none (every call is then unavailable).
68    pub command: Option<PathBuf>,
69    pub attributes: Vec<String>,
70    pub timeout: Duration,
71    /// The child's whole environment.
72    pub env: Vec<(String, String)>,
73}
74
75/// The variables `secret-tool` needs to find the session's Secret Service, taken from the session environment.
76const SECRET_TOOL_ENV: &[&str] = &[
77    "PATH",
78    "HOME",
79    "DBUS_SESSION_BUS_ADDRESS",
80    "XDG_RUNTIME_DIR",
81    "DISPLAY",
82    "WAYLAND_DISPLAY",
83];
84
85/// `secretToolKeyring(agentDir)` over the session environment `var`: `secret-tool` from its `PATH`, a 5 s timeout.
86pub fn secret_tool_keyring(agent_dir: &Path, var: &dyn Fn(&str) -> Option<String>) -> SecretToolKeyring {
87    let profile = std::path::absolute(agent_dir).unwrap_or_else(|_| agent_dir.to_path_buf());
88    SecretToolKeyring {
89        command: var("PATH").and_then(|path| jsrt::process::which("secret-tool", &path)),
90        attributes: ["application", "ultron", "purpose", "rlm-snapshot-key", "profile"]
91            .iter()
92            .map(|s| s.to_string())
93            .chain([profile.display().to_string()])
94            .collect(),
95        timeout: Duration::from_secs(5),
96        env: SECRET_TOOL_ENV
97            .iter()
98            .filter_map(|name| Some((name.to_string(), var(name)?)))
99            .collect(),
100    }
101}
102
103/// A finished `secret-tool` run: its exit code (`None`: killed by a signal or the timeout), stdout and stderr.
104struct Run {
105    code: Option<i32>,
106    stdout: String,
107    stderr: String,
108}
109
110impl SecretToolKeyring {
111    fn run(&self, args: &[String], input: Option<&str>) -> Option<Run> {
112        let command = self.command.as_ref()?;
113        let bound = signals::child::Bound {
114            timeout: Some(self.timeout),
115            ..Default::default()
116        };
117        let out = signals::child::run(
118            Command::new(command)
119                .args(args)
120                .env_clear()
121                .envs(self.env.iter().map(|(k, v)| (k, v)))
122                .stdout(Stdio::piped())
123                .stderr(Stdio::piped()),
124            input.map(str::as_bytes),
125            bound,
126        )
127        .ok()?;
128        Some(Run {
129            code: out.code(),
130            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
131            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
132        })
133    }
134}
135
136impl SnapshotKeyring for SecretToolKeyring {
137    fn lookup(&self) -> Lookup {
138        let args: Vec<String> = std::iter::once("lookup".to_string())
139            .chain(self.attributes.iter().cloned())
140            .collect();
141        let run = self.run(&args, None)?;
142        match run.code {
143            Some(0) => Some(Some(run.stdout)),
144            // secret-tool exits 1 silently when nothing matches, and 1 with a message when the service fails.
145            Some(1) if run.stderr.trim().is_empty() => Some(None),
146            _ => None,
147        }
148    }
149
150    fn store(&self, hex: &str) -> bool {
151        let args: Vec<String> = ["store", "--label=Ultron RLM snapshot signing key"]
152            .iter()
153            .map(|s| s.to_string())
154            .chain(self.attributes.iter().cloned())
155            .collect();
156        self.run(&args, Some(hex)).is_some_and(|run| run.code == Some(0))
157    }
158}
159
160fn random_key() -> Result<Vec<u8>, String> {
161    let mut key = vec![0u8; KEY_BYTES];
162    getrandom::fill(&mut key).map_err(|error| error.to_string())?;
163    Ok(key)
164}
165
166fn mark_keyring(marker: &Path) -> Result<(), String> {
167    if marker.exists() {
168        return Ok(());
169    }
170    std::fs::OpenOptions::new()
171        .write(true)
172        .create(true)
173        .truncate(true)
174        .mode(0o600)
175        .open(marker)
176        .and_then(|mut file| {
177            file.write_all(
178                b"The RLM snapshot signing key is stored in the OS keyring (secret-tool, application=ultron purpose=rlm-snapshot-key). This file holds no secret.\n",
179            )
180        })
181        .map_err(|error| error.to_string())
182}
183
184/// `loadSnapshotKey`: the per-profile key from the store `store` selects. In auto mode a reachable keyring takes over
185/// the key (an existing key file is copied in, read back, and deleted, and a marker records it); once the marker
186/// exists an unreachable keyring gives a key for this process only, with a warning, so no second persistent key is
187/// ever made.
188pub fn load_snapshot_key(
189    agent_dir: &Path,
190    store: KeyStore,
191    keyring: &dyn SnapshotKeyring,
192) -> Result<LoadedSnapshotKey, String> {
193    let file = |key: Vec<u8>| LoadedSnapshotKey {
194        key,
195        source: KeySource::File,
196        warning: None,
197    };
198    if store == KeyStore::File {
199        return Ok(file(load_or_create_snapshot_key(agent_dir)?));
200    }
201    let path = agent_dir.join(SNAPSHOT_KEY_FILE);
202    let shown = path.display().to_string();
203    let marker = agent_dir.join(SNAPSHOT_KEYRING_MARKER);
204    let unreachable = |reason: &str| -> Result<LoadedSnapshotKey, String> {
205        if store == KeyStore::Auto && !marker.exists() {
206            return Ok(file(load_or_create_snapshot_key(agent_dir)?));
207        }
208        Ok(LoadedSnapshotKey {
209            key: random_key()?,
210            source: KeySource::Process,
211            warning: Some(format!(
212                "RLM snapshot key: {reason}; using a key for this process only, so its snapshots will not restore in later sessions"
213            )),
214        })
215    };
216    let Some(found) = keyring.lookup() else {
217        return unreachable("the OS keyring holding the key is unreachable");
218    };
219    if let Some(value) = found.filter(|v| !v.trim().is_empty()) {
220        let key = parse_key(&value, "in the OS keyring")?;
221        mark_keyring(&marker)?;
222        if path.exists() {
223            let file_key = std::fs::read_to_string(&path)
224                .ok()
225                .and_then(|text| parse_key(&text, &shown).ok());
226            if file_key.as_deref() == Some(key.as_slice()) {
227                let _ = std::fs::remove_file(&path);
228            } else {
229                return Ok(LoadedSnapshotKey {
230                    key,
231                    source: KeySource::Keyring,
232                    warning: Some(format!(
233                        "RLM snapshot key: {shown} differs from the key in the OS keyring; the keyring key is used and the file was left in place"
234                    )),
235                });
236            }
237        }
238        return Ok(LoadedSnapshotKey {
239            key,
240            source: KeySource::Keyring,
241            warning: None,
242        });
243    }
244    // Nothing stored yet: move the file key into the keyring (so existing snapshots keep verifying), or make one.
245    let key = if path.exists() {
246        parse_key(&std::fs::read_to_string(&path).map_err(|e| e.to_string())?, &shown)?
247    } else {
248        random_key()?
249    };
250    let encoded = jsrt::hash::hex(&key);
251    let read_back = if keyring.store(&encoded) {
252        keyring.lookup()
253    } else {
254        None
255    };
256    if read_back.flatten().map(|v| v.trim().to_string()).as_deref() != Some(encoded.as_str()) {
257        if store == KeyStore::Keyring {
258            return unreachable("the OS keyring did not store the key");
259        }
260        return Ok(file(load_or_create_snapshot_key(agent_dir)?));
261    }
262    mark_keyring(&marker)?;
263    let _ = std::fs::remove_file(&path);
264    Ok(LoadedSnapshotKey {
265        key,
266        source: KeySource::Keyring,
267        warning: None,
268    })
269}
270
271/// The key a session's kernels sign snapshots with (session-worker.ts: `loadSnapshotKey(getAgentDir())`, its
272/// warning on stderr): the store from `ULTRON_RLM_SNAPSHOT_KEY_STORE`, the keyring through the session
273/// environment's `secret-tool`. `None` when the key cannot be loaded (the kernel then uses a process key).
274pub fn session_snapshot_key(agent_dir: &Path, var: &dyn Fn(&str) -> Option<String>) -> Option<Vec<u8>> {
275    let store = KeyStore::from_setting(var(RLM_SNAPSHOT_KEY_STORE_ENV).as_deref());
276    let keyring = secret_tool_keyring(agent_dir, var);
277    let loaded = load_snapshot_key(agent_dir, store, &keyring).ok()?;
278    if let Some(warning) = &loaded.warning {
279        eprintln!("{warning}");
280    }
281    Some(loaded.key)
282}