1use 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
16pub 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 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#[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
53pub type Lookup = Option<Option<String>>;
56
57pub trait SnapshotKeyring {
59 fn lookup(&self) -> Lookup;
60 fn store(&self, hex: &str) -> bool;
61}
62
63pub struct SecretToolKeyring {
67 pub command: Option<PathBuf>,
69 pub attributes: Vec<String>,
70 pub timeout: Duration,
71 pub env: Vec<(String, String)>,
73}
74
75const SECRET_TOOL_ENV: &[&str] = &[
77 "PATH",
78 "HOME",
79 "DBUS_SESSION_BUS_ADDRESS",
80 "XDG_RUNTIME_DIR",
81 "DISPLAY",
82 "WAYLAND_DISPLAY",
83];
84
85pub 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
103struct 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 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
184pub 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 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
271pub 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}