Skip to main content

kernel/
snapshot.rs

1//! Host-side snapshot authentication (port of `snapshot-auth.ts`) and the kernel's snapshot/restore reports
2//! (`KernelSnapshotReport` / `KernelRestoreReport` of kernel.ts).
3//!
4//! The key lives only in the host: the Python kernel runs model-written code, so any key it held could be read by
5//! that code. The host signs a snapshot after the kernel writes it and verifies the signature before the kernel may
6//! read it. Signed file: one signature line, then the kernel's content (sha256 header line + JSON body):
7//! `{"format":"ultron-rlm-snapshot-signature","version":1,"alg":"HMAC-SHA256","hmac":"<hex>"}\n<content>`; the HMAC
8//! covers the content bytes exactly.
9
10use crate::{CellError, ExecutionResult, Status};
11use serde::Serialize;
12use serde_json::{Map, Value};
13use std::io::Write;
14use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
15use std::path::Path;
16use std::sync::OnceLock;
17
18pub const SNAPSHOT_KEY_FILE: &str = "rlm-snapshot.key";
19const SIGNATURE_FORMAT: &str = "ultron-rlm-snapshot-signature";
20pub(crate) const KEY_BYTES: usize = 32;
21/// The error name kernel.ts gives refused snapshots (`SnapshotAuthenticationError.name`).
22pub const SNAPSHOT_ERROR_NAME: &str = "SnapshotIntegrityError";
23
24/// A refused snapshot: the message the kernel result reports.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct SnapshotAuthError(pub String);
27
28impl std::fmt::Display for SnapshotAuthError {
29    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        formatter.write_str(&self.0)
31    }
32}
33
34impl std::error::Error for SnapshotAuthError {}
35
36/// Lowercase hex of exactly 64 digits, as `/^[0-9a-f]{64}$/` accepts.
37fn hex64(text: &str) -> Option<Vec<u8>> {
38    if text.len() != 64
39        || !text
40            .bytes()
41            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
42    {
43        return None;
44    }
45    (0..64)
46        .step_by(2)
47        .map(|index| u8::from_str_radix(&text[index..index + 2], 16).ok())
48        .collect()
49}
50
51/// The signed file: a signature line over `content`, then `content`.
52pub fn sign_snapshot(key: &[u8], content: &[u8]) -> Vec<u8> {
53    let mut line = Map::new();
54    line.insert("format".into(), SIGNATURE_FORMAT.into());
55    line.insert("version".into(), 1.into());
56    line.insert("alg".into(), "HMAC-SHA256".into());
57    line.insert(
58        "hmac".into(),
59        jsrt::hash::hex(&jsrt::hash::hmac_sha256(key, content)).into(),
60    );
61    let mut signed = Value::Object(line).to_string().into_bytes();
62    signed.push(b'\n');
63    signed.extend_from_slice(content);
64    signed
65}
66
67/// Verifies a signed snapshot and returns the sha256 of its content, which the kernel re-checks on read.
68pub fn verify_snapshot(key: &[u8], raw: &[u8]) -> Result<String, SnapshotAuthError> {
69    let newline = raw.iter().position(|&byte| byte == b'\n');
70    let signature = newline
71        .and_then(|newline| serde_json::from_str::<Value>(&String::from_utf8_lossy(&raw[..newline])).ok())
72        .filter(Value::is_object);
73    let Some(record) = signature.filter(|record| record["format"] == SIGNATURE_FORMAT) else {
74        return Err(SnapshotAuthError(
75            "snapshot integrity check failed: missing host signature (unsigned snapshots, including ones written before snapshots were signed, are refused)"
76                .into(),
77        ));
78    };
79    let Some(signature) = record["hmac"]
80        .as_str()
81        .filter(|_| record["version"].as_f64() == Some(1.0) && record["alg"] == "HMAC-SHA256")
82    else {
83        return Err(SnapshotAuthError(
84            "snapshot integrity check failed: unsupported host signature".into(),
85        ));
86    };
87    let content = &raw[newline.map_or(raw.len(), |newline| newline + 1)..];
88    let expected = jsrt::hash::hmac_sha256(key, content);
89    let actual = hex64(signature).unwrap_or_default();
90    // Constant time over the digest length.
91    let differs = actual.len() != expected.len()
92        || actual
93            .iter()
94            .zip(expected.iter())
95            .fold(0u8, |acc, (left, right)| acc | (left ^ right))
96            != 0;
97    if differs {
98        return Err(SnapshotAuthError(
99            "snapshot integrity check failed: HMAC signature mismatch (the snapshot was modified or signed with another profile's key)"
100                .into(),
101        ));
102    }
103    Ok(jsrt::hash::sha256_hex(content))
104}
105
106pub(crate) fn parse_key(text: &str, path: &str) -> Result<Vec<u8>, String> {
107    hex64(jsrt::string::trim(text)).ok_or_else(|| {
108        format!(
109            "RLM snapshot key {path} is malformed; delete it to create a new key (existing snapshots become unrestorable)"
110        )
111    })
112}
113
114/// Reads the per-profile snapshot key `<agent_dir>/rlm-snapshot.key`, creating it once (0600, random) when absent.
115pub fn load_or_create_snapshot_key(agent_dir: &Path) -> Result<Vec<u8>, String> {
116    let path = agent_dir.join(SNAPSHOT_KEY_FILE);
117    let shown = path.display().to_string();
118    match std::fs::OpenOptions::new()
119        .write(true)
120        .create_new(true)
121        .mode(0o600)
122        .open(&path)
123    {
124        Ok(mut file) => {
125            let mut key = [0u8; KEY_BYTES];
126            getrandom::fill(&mut key).map_err(|error| error.to_string())?;
127            file.write_all(format!("{}\n", jsrt::hash::hex(&key)).as_bytes())
128                .map_err(|error| error.to_string())?;
129        }
130        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
131        Err(error) => return Err(error.to_string()),
132    }
133    // Keep the key private even if something loosened its mode.
134    let mode = std::fs::metadata(&path)
135        .map_err(|error| error.to_string())?
136        .permissions()
137        .mode();
138    if mode & 0o077 != 0 {
139        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).map_err(|error| error.to_string())?;
140    }
141    parse_key(
142        &std::fs::read_to_string(&path).map_err(|error| error.to_string())?,
143        &shown,
144    )
145}
146
147/// Fallback for kernels built without a profile key: snapshots are then restorable only within this process.
148pub fn process_snapshot_key() -> Vec<u8> {
149    static KEY: OnceLock<[u8; KEY_BYTES]> = OnceLock::new();
150    KEY.get_or_init(|| {
151        let mut key = [0u8; KEY_BYTES];
152        // Without randomness a process key would be guessable; an all-zero key would still sign, so fail loudly.
153        getrandom::fill(&mut key).expect("random snapshot key");
154        key
155    })
156    .to_vec()
157}
158
159/// Names are saved only as constrained data; every other user name is listed with a reason.
160#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
161pub struct SnapshotReport {
162    pub saved: Vec<String>,
163    pub skipped: Vec<String>,
164    /// Name to reason, in the kernel's order.
165    pub reasons: Map<String, Value>,
166    pub sha256: String,
167    /// sha256 of the unsigned file content the host signed.
168    #[serde(rename = "contentSha256", skip_serializing_if = "Option::is_none")]
169    pub content_sha256: Option<String>,
170}
171
172/// `skipped` repeats the names the snapshot could not restore; they are absent, not stale.
173#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
174pub struct RestoreReport {
175    pub restored: Vec<String>,
176    pub missing: bool,
177    pub skipped: Vec<String>,
178    pub reasons: Map<String, Value>,
179}
180
181impl SnapshotReport {
182    pub fn reason(&self, name: &str) -> Option<&str> {
183        self.reasons.get(name).and_then(Value::as_str)
184    }
185}
186
187impl RestoreReport {
188    pub fn reason(&self, name: &str) -> Option<&str> {
189        self.reasons.get(name).and_then(Value::as_str)
190    }
191}
192
193fn string_list(value: &Value) -> Vec<String> {
194    value
195        .as_array()
196        .map(|items| {
197            items
198                .iter()
199                .filter_map(|item| item.as_str().map(String::from))
200                .collect()
201        })
202        .unwrap_or_default()
203}
204
205fn string_record(value: &Value) -> Map<String, Value> {
206    value
207        .as_object()
208        .map(|record| {
209            record
210                .iter()
211                .filter(|(_, item)| item.is_string())
212                .map(|(key, item)| (key.clone(), item.clone()))
213                .collect()
214        })
215        .unwrap_or_default()
216}
217
218/// The done frame's `snapshot` field, as kernel.ts `snapshotReport` reads it.
219pub(crate) fn snapshot_report(value: Option<&Value>) -> Option<SnapshotReport> {
220    let report = value.filter(|value| value.is_object())?;
221    Some(SnapshotReport {
222        saved: string_list(&report["saved"]),
223        skipped: string_list(&report["skipped"]),
224        reasons: string_record(&report["reasons"]),
225        sha256: report["sha256"].as_str().unwrap_or_default().to_string(),
226        content_sha256: report["content_sha256"].as_str().map(String::from),
227    })
228}
229
230/// The done frame's `restore` field, as kernel.ts `restoreReport` reads it.
231pub(crate) fn restore_report(value: Option<&Value>) -> Option<RestoreReport> {
232    let report = value.filter(|value| value.is_object())?;
233    Some(RestoreReport {
234        restored: string_list(&report["restored"]),
235        missing: report["missing"] == true,
236        skipped: string_list(&report["skipped"]),
237        reasons: string_record(&report["reasons"]),
238    })
239}
240
241/// kernel.ts `snapshotError`: a refused or failed snapshot operation as a result.
242pub(crate) fn snapshot_error(message: impl Into<String>) -> ExecutionResult {
243    ExecutionResult {
244        status: Status::Error,
245        stdout: String::new(),
246        stderr: String::new(),
247        result: None,
248        error: Some(CellError {
249            ename: SNAPSHOT_ERROR_NAME.into(),
250            evalue: message.into(),
251            traceback: Vec::new(),
252        }),
253    }
254}