use crate::snapshot::{KEY_BYTES, SNAPSHOT_KEY_FILE, load_or_create_snapshot_key, parse_key};
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;
pub const RLM_SNAPSHOT_KEY_STORE_ENV: &str = "ULTRON_RLM_SNAPSHOT_KEY_STORE";
pub const SNAPSHOT_KEYRING_MARKER: &str = "rlm-snapshot.key.keyring";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyStore {
Auto,
Keyring,
File,
}
impl KeyStore {
pub fn from_setting(value: Option<&str>) -> KeyStore {
match value.map(|v| v.trim().to_lowercase()).as_deref() {
Some("auto") => KeyStore::Auto,
Some("keyring") => KeyStore::Keyring,
_ => KeyStore::File,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeySource {
Keyring,
File,
Process,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoadedSnapshotKey {
pub key: Vec<u8>,
pub source: KeySource,
pub warning: Option<String>,
}
pub type Lookup = Option<Option<String>>;
pub trait SnapshotKeyring {
fn lookup(&self) -> Lookup;
fn store(&self, hex: &str) -> bool;
}
pub struct SecretToolKeyring {
pub command: Option<PathBuf>,
pub attributes: Vec<String>,
pub timeout: Duration,
pub env: Vec<(String, String)>,
}
const SECRET_TOOL_ENV: &[&str] = &[
"PATH",
"HOME",
"DBUS_SESSION_BUS_ADDRESS",
"XDG_RUNTIME_DIR",
"DISPLAY",
"WAYLAND_DISPLAY",
];
pub fn secret_tool_keyring(agent_dir: &Path, var: &dyn Fn(&str) -> Option<String>) -> SecretToolKeyring {
let profile = std::path::absolute(agent_dir).unwrap_or_else(|_| agent_dir.to_path_buf());
SecretToolKeyring {
command: var("PATH").and_then(|path| jsrt::process::which("secret-tool", &path)),
attributes: ["application", "ultron", "purpose", "rlm-snapshot-key", "profile"]
.iter()
.map(|s| s.to_string())
.chain([profile.display().to_string()])
.collect(),
timeout: Duration::from_secs(5),
env: SECRET_TOOL_ENV
.iter()
.filter_map(|name| Some((name.to_string(), var(name)?)))
.collect(),
}
}
struct Run {
code: Option<i32>,
stdout: String,
stderr: String,
}
impl SecretToolKeyring {
fn run(&self, args: &[String], input: Option<&str>) -> Option<Run> {
let command = self.command.as_ref()?;
let bound = signals::child::Bound {
timeout: Some(self.timeout),
..Default::default()
};
let out = signals::child::run(
Command::new(command)
.args(args)
.env_clear()
.envs(self.env.iter().map(|(k, v)| (k, v)))
.stdout(Stdio::piped())
.stderr(Stdio::piped()),
input.map(str::as_bytes),
bound,
)
.ok()?;
Some(Run {
code: out.code(),
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
})
}
}
impl SnapshotKeyring for SecretToolKeyring {
fn lookup(&self) -> Lookup {
let args: Vec<String> = std::iter::once("lookup".to_string())
.chain(self.attributes.iter().cloned())
.collect();
let run = self.run(&args, None)?;
match run.code {
Some(0) => Some(Some(run.stdout)),
Some(1) if run.stderr.trim().is_empty() => Some(None),
_ => None,
}
}
fn store(&self, hex: &str) -> bool {
let args: Vec<String> = ["store", "--label=Ultron RLM snapshot signing key"]
.iter()
.map(|s| s.to_string())
.chain(self.attributes.iter().cloned())
.collect();
self.run(&args, Some(hex)).is_some_and(|run| run.code == Some(0))
}
}
fn random_key() -> Result<Vec<u8>, String> {
let mut key = vec![0u8; KEY_BYTES];
getrandom::fill(&mut key).map_err(|error| error.to_string())?;
Ok(key)
}
fn mark_keyring(marker: &Path) -> Result<(), String> {
if marker.exists() {
return Ok(());
}
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(marker)
.and_then(|mut file| {
file.write_all(
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",
)
})
.map_err(|error| error.to_string())
}
pub fn load_snapshot_key(
agent_dir: &Path,
store: KeyStore,
keyring: &dyn SnapshotKeyring,
) -> Result<LoadedSnapshotKey, String> {
let file = |key: Vec<u8>| LoadedSnapshotKey {
key,
source: KeySource::File,
warning: None,
};
if store == KeyStore::File {
return Ok(file(load_or_create_snapshot_key(agent_dir)?));
}
let path = agent_dir.join(SNAPSHOT_KEY_FILE);
let shown = path.display().to_string();
let marker = agent_dir.join(SNAPSHOT_KEYRING_MARKER);
let unreachable = |reason: &str| -> Result<LoadedSnapshotKey, String> {
if store == KeyStore::Auto && !marker.exists() {
return Ok(file(load_or_create_snapshot_key(agent_dir)?));
}
Ok(LoadedSnapshotKey {
key: random_key()?,
source: KeySource::Process,
warning: Some(format!(
"RLM snapshot key: {reason}; using a key for this process only, so its snapshots will not restore in later sessions"
)),
})
};
let Some(found) = keyring.lookup() else {
return unreachable("the OS keyring holding the key is unreachable");
};
if let Some(value) = found.filter(|v| !v.trim().is_empty()) {
let key = parse_key(&value, "in the OS keyring")?;
mark_keyring(&marker)?;
if path.exists() {
let file_key = std::fs::read_to_string(&path)
.ok()
.and_then(|text| parse_key(&text, &shown).ok());
if file_key.as_deref() == Some(key.as_slice()) {
let _ = std::fs::remove_file(&path);
} else {
return Ok(LoadedSnapshotKey {
key,
source: KeySource::Keyring,
warning: Some(format!(
"RLM snapshot key: {shown} differs from the key in the OS keyring; the keyring key is used and the file was left in place"
)),
});
}
}
return Ok(LoadedSnapshotKey {
key,
source: KeySource::Keyring,
warning: None,
});
}
let key = if path.exists() {
parse_key(&std::fs::read_to_string(&path).map_err(|e| e.to_string())?, &shown)?
} else {
random_key()?
};
let encoded = jsrt::hash::hex(&key);
let read_back = if keyring.store(&encoded) {
keyring.lookup()
} else {
None
};
if read_back.flatten().map(|v| v.trim().to_string()).as_deref() != Some(encoded.as_str()) {
if store == KeyStore::Keyring {
return unreachable("the OS keyring did not store the key");
}
return Ok(file(load_or_create_snapshot_key(agent_dir)?));
}
mark_keyring(&marker)?;
let _ = std::fs::remove_file(&path);
Ok(LoadedSnapshotKey {
key,
source: KeySource::Keyring,
warning: None,
})
}
pub fn session_snapshot_key(agent_dir: &Path, var: &dyn Fn(&str) -> Option<String>) -> Option<Vec<u8>> {
let store = KeyStore::from_setting(var(RLM_SNAPSHOT_KEY_STORE_ENV).as_deref());
let keyring = secret_tool_keyring(agent_dir, var);
let loaded = load_snapshot_key(agent_dir, store, &keyring).ok()?;
if let Some(warning) = &loaded.warning {
eprintln!("{warning}");
}
Some(loaded.key)
}