Skip to main content

sail_runtime/temporal/
image.rs

1//! Verified private worker images, reused under a settled complete stat
2//! stamp (ADR 0082, ADR 0173).
3//!
4//! Every native job runs a private copy of the installed worker whose bytes
5//! were hashed against the installation manifest, so a later change to the
6//! installed file cannot change what runs. Hashing and copying the 76 MB
7//! worker cost about 100 ms per job (#765). This module keeps one verified
8//! copy per installed worker in a per-user private directory and reuses it
9//! while both files keep their recorded complete stamps:
10//!
11//! - The installed worker's stamp (device, inode, size, mode, mtime and
12//!   ctime with nanoseconds) is recorded only when it was settled
13//!   ([`Stamp::settled`]) before the bytes were read and is unchanged after
14//!   they were hashed. Any later write, replacement, `chmod` or `utimes`
15//!   advances ctime, so the next job misses and verifies the bytes again.
16//! - The private copy is mode `0500` in a mode `0700` directory owned by
17//!   this user. Its own complete stamp, owner and link count must still
18//!   equal the ones recorded right after it was written; writing it needs a
19//!   `chmod` first, which changes ctime.
20//!
21//! Anything unexpected (another owner, a symbolic link, wider permissions,
22//! an unreadable or foreign record, a different source path or digest)
23//! misses, and the job uses a fresh verified copy of its own exactly as
24//! before. A miss never fails a job that would otherwise run.
25use sail_api::stamp::Stamp;
26use serde::{Deserialize, Serialize};
27use std::io::{Read as _, Write as _};
28use std::path::{Path, PathBuf};
29use std::sync::atomic::{AtomicU64, Ordering};
30use std::time::{Duration, SystemTime};
31
32/// Largest worker executable admitted, as before caching.
33const MAX_WORKER_BYTES: u64 = 512 * 1024 * 1024;
34const RECORD: &str = "record.json";
35const RECORD_LIMIT: u64 = 4096;
36const EXECUTABLE: &str = "sail-runtime-worker";
37/// Interrupted installs older than this are removed by the next install.
38const ABANDONED: Duration = Duration::from_secs(3600);
39
40static NEXT: AtomicU64 = AtomicU64::new(0);
41
42#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(deny_unknown_fields)]
44struct Record {
45    version: u32,
46    source: PathBuf,
47    sha256: String,
48    source_stamp: Stamp,
49    image_stamp: Stamp,
50}
51
52/// A verified private copy of the worker, ready to execute.
53#[derive(Debug)]
54pub struct Image {
55    executable: PathBuf,
56    /// A per-job copy is removed with its directory on drop; a reused
57    /// copy stays for later jobs.
58    owned: Option<PathBuf>,
59}
60
61impl Image {
62    /// The verified private executable.
63    #[must_use]
64    pub fn executable(&self) -> &Path {
65        &self.executable
66    }
67
68    /// Whether this is a reused copy rather than one written for this job.
69    #[must_use]
70    pub fn reused(&self) -> bool {
71        self.owned.is_none()
72    }
73}
74
75impl Drop for Image {
76    fn drop(&mut self) {
77        if let Some(directory) = &self.owned {
78            let _ = std::fs::remove_dir_all(directory);
79        }
80    }
81}
82
83fn stamp(path: &Path) -> Option<Stamp> {
84    std::fs::metadata(path).ok().map(|m| Stamp::of(&m))
85}
86
87#[cfg(unix)]
88fn private_directory(path: &Path) -> bool {
89    use std::os::unix::fs::MetadataExt as _;
90    std::fs::symlink_metadata(path).is_ok_and(|m| {
91        m.file_type().is_dir()
92            && m.uid() == rustix::process::getuid().as_raw()
93            && m.mode() & 0o777 == 0o700
94    })
95}
96
97#[cfg(unix)]
98fn create_private(path: &Path) -> std::io::Result<()> {
99    use std::os::unix::fs::DirBuilderExt as _;
100    std::fs::DirBuilder::new().mode(0o700).create(path)
101}
102
103/// The per-user image directory, created on first use. `None` when it is
104/// not a private directory of this user.
105#[cfg(unix)]
106fn root() -> Option<PathBuf> {
107    let root = std::env::temp_dir().join(format!(
108        "sail-runtime-images-{}",
109        rustix::process::getuid().as_raw()
110    ));
111    match create_private(&root) {
112        Ok(()) => {}
113        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
114        Err(_) => return None,
115    }
116    private_directory(&root).then_some(root)
117}
118
119fn entry(root: &Path, source: &Path, sha256: &str) -> PathBuf {
120    let mut key = sha256.as_bytes().to_vec();
121    key.push(0);
122    key.extend_from_slice(source.as_os_str().as_encoded_bytes());
123    root.join(crate::hash(&key))
124}
125
126fn read_record(directory: &Path) -> Option<Record> {
127    let mut bytes = Vec::new();
128    std::fs::File::open(directory.join(RECORD))
129        .and_then(|f| f.take(RECORD_LIMIT + 1).read_to_end(&mut bytes))
130        .ok()?;
131    if u64::try_from(bytes.len()).ok()? > RECORD_LIMIT {
132        return None;
133    }
134    serde_json::from_slice(&bytes).ok()
135}
136
137/// The reusable verified copy of `source` with digest `sha256`, if both
138/// files still carry their recorded stamps.
139#[cfg(unix)]
140fn reusable(source: &Path, sha256: &str) -> Option<PathBuf> {
141    use std::os::unix::fs::MetadataExt as _;
142    if !source.is_absolute() {
143        return None;
144    }
145    let directory = entry(&root()?, source, sha256);
146    if !private_directory(&directory) {
147        return None;
148    }
149    let record = read_record(&directory)?;
150    if record.version != 1
151        || record.source != source
152        || record.sha256 != sha256
153        || stamp(source)? != record.source_stamp
154    {
155        return None;
156    }
157    let executable = directory.join(EXECUTABLE);
158    let image = std::fs::symlink_metadata(&executable).ok()?;
159    (image.file_type().is_file()
160        && image.uid() == rustix::process::getuid().as_raw()
161        && image.nlink() == 1
162        && image.mode() & 0o777 == 0o500
163        && Stamp::of(&image) == record.image_stamp)
164        .then_some(executable)
165}
166
167#[cfg(not(unix))]
168fn reusable(_: &Path, _: &str) -> Option<PathBuf> {
169    None
170}
171
172/// Whether `source` with digest `sha256` was verified at its current
173/// settled stamp. Only a hit is proof; a miss means "hash it".
174#[must_use]
175pub(crate) fn verified(source: &Path, sha256: &str) -> bool {
176    reusable(source, sha256).is_some()
177}
178
179/// Read `source` within the admission bound and check its digest.
180fn read_verified(source: &Path, sha256: &str) -> Result<Vec<u8>, String> {
181    let mut bytes = Vec::new();
182    std::fs::File::open(source)
183        .and_then(|file| file.take(MAX_WORKER_BYTES + 1).read_to_end(&mut bytes))
184        .map_err(|e| e.to_string())?;
185    if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_WORKER_BYTES {
186        return Err("worker executable exceeds its 512 MiB admission bound".into());
187    }
188    if crate::hash(&bytes) != sha256 {
189        return Err("worker executable differs from its pinned identity".into());
190    }
191    Ok(bytes)
192}
193
194/// Writes `bytes` as a mode `0500` executable in a fresh private directory.
195fn write_image(directory: &Path, bytes: &[u8]) -> Result<PathBuf, String> {
196    #[cfg(unix)]
197    create_private(directory).map_err(|e| e.to_string())?;
198    #[cfg(not(unix))]
199    std::fs::create_dir(directory).map_err(|e| e.to_string())?;
200    let executable = directory.join(EXECUTABLE);
201    let mut options = std::fs::OpenOptions::new();
202    options.write(true).create_new(true);
203    #[cfg(unix)]
204    {
205        use std::os::unix::fs::OpenOptionsExt as _;
206        options.mode(0o500);
207    }
208    options
209        .open(&executable)
210        .and_then(|mut f| f.write_all(bytes))
211        .map_err(|e| e.to_string())?;
212    Ok(executable)
213}
214
215fn unique(prefix: &str) -> String {
216    format!(
217        "{prefix}-{}-{}",
218        std::process::id(),
219        NEXT.fetch_add(1, Ordering::Relaxed)
220    )
221}
222
223/// A fresh verified copy of `source` for one job, as before caching.
224///
225/// # Errors
226/// An invalid digest, unreadable, oversized or different worker, or an
227/// unwritable temporary directory.
228pub fn fresh(source: &Path, sha256: &str) -> Result<Image, String> {
229    check_digest(sha256)?;
230    let bytes = read_verified(source, sha256)?;
231    per_job(&bytes)
232}
233
234fn per_job(bytes: &[u8]) -> Result<Image, String> {
235    let directory = std::env::temp_dir().join(unique("sail-runtime-image"));
236    let image = Image {
237        executable: directory.join(EXECUTABLE),
238        owned: Some(directory.clone()),
239    };
240    write_image(&directory, bytes)?;
241    Ok(image)
242}
243
244fn check_digest(sha256: &str) -> Result<(), String> {
245    if sha256.len() != 64
246        || !sha256
247            .bytes()
248            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
249    {
250        return Err("worker requires a pinned lowercase SHA-256".into());
251    }
252    Ok(())
253}
254
255/// The verified private copy of `source` for one job: a reused one when
256/// both stamps still match, otherwise a fresh one, recorded for reuse when
257/// the installed worker was settled and unchanged while it was hashed.
258///
259/// # Errors
260/// As [`fresh`]. Failing to record a reusable copy is not an error.
261pub fn image(source: &Path, sha256: &str) -> Result<Image, String> {
262    check_digest(sha256)?;
263    if let Some(executable) = reusable(source, sha256) {
264        return Ok(Image {
265            executable,
266            owned: None,
267        });
268    }
269    let start = SystemTime::now();
270    let before = source.is_absolute().then(|| stamp(source)).flatten();
271    let bytes = read_verified(source, sha256)?;
272    if let Some(before) = before
273        && before.settled(start)
274        && stamp(source) == Some(before)
275        && let Some(image) = install(source, sha256, before, &bytes)
276    {
277        return Ok(image);
278    }
279    per_job(&bytes)
280}
281
282/// Publishes a verified copy for reuse. `None` leaves the job to use a
283/// per-job copy.
284#[cfg(unix)]
285fn install(source: &Path, sha256: &str, source_stamp: Stamp, bytes: &[u8]) -> Option<Image> {
286    let root = root()?;
287    sweep(&root);
288    let staged = root.join(unique(".new"));
289    let written = write_image(&staged, bytes);
290    let Ok(executable) = written else {
291        let _ = std::fs::remove_dir_all(&staged);
292        return None;
293    };
294    let record = std::fs::symlink_metadata(&executable)
295        .ok()
296        .map(|m| Record {
297            version: 1,
298            source: source.to_owned(),
299            sha256: sha256.to_owned(),
300            source_stamp,
301            image_stamp: Stamp::of(&m),
302        })
303        .and_then(|r| serde_json::to_vec(&r).ok());
304    let published = record.is_some_and(|record| {
305        let mut options = std::fs::OpenOptions::new();
306        {
307            use std::os::unix::fs::OpenOptionsExt as _;
308            options.write(true).create_new(true).mode(0o600);
309        }
310        options
311            .open(staged.join(RECORD))
312            .and_then(|mut f| f.write_all(&record))
313            .is_ok()
314    }) && {
315        let target = entry(&root, source, sha256);
316        // Retire a stale entry first; a job that already chose it and
317        // finds it gone retries with a fresh copy.
318        let retired = root.join(unique(".old"));
319        if std::fs::rename(&target, &retired).is_ok() {
320            let _ = std::fs::remove_dir_all(&retired);
321        }
322        std::fs::rename(&staged, &target).is_ok()
323    };
324    if published {
325        // Hand out only what a later lookup would accept.
326        return reusable(source, sha256).map(|executable| Image {
327            executable,
328            owned: None,
329        });
330    }
331    // Another process published first, or a write failed: this job keeps
332    // its staged verified copy, removed when it finishes.
333    Some(Image {
334        executable,
335        owned: Some(staged),
336    })
337}
338
339#[cfg(not(unix))]
340fn install(_: &Path, _: &str, _: Stamp, _: &[u8]) -> Option<Image> {
341    None
342}
343
344/// Removes interrupted installs and entries whose installed worker changed.
345#[cfg(unix)]
346fn sweep(root: &Path) {
347    let Ok(entries) = std::fs::read_dir(root) else {
348        return;
349    };
350    for entry in entries.flatten() {
351        let path = entry.path();
352        let name = entry.file_name();
353        let name = name.to_string_lossy();
354        if name.starts_with(".new-") || name.starts_with(".old-") {
355            let old = std::fs::symlink_metadata(&path)
356                .and_then(|m| m.modified())
357                .ok()
358                .and_then(|t| t.elapsed().ok())
359                .is_some_and(|age| age >= ABANDONED);
360            if old {
361                let _ = std::fs::remove_dir_all(&path);
362            }
363        } else if private_directory(&path)
364            && read_record(&path).is_some_and(|r| stamp(&r.source) != Some(r.source_stamp))
365        {
366            let _ = std::fs::remove_dir_all(&path);
367        }
368    }
369}
370
371#[cfg(all(test, unix))]
372mod tests {
373    use super::*;
374    use std::os::unix::fs::PermissionsExt as _;
375
376    type TestResult = Result<(), Box<dyn std::error::Error>>;
377
378    /// A settled installed worker: written, then its ctime left to age.
379    fn installed(
380        name: &str,
381        bytes: &[u8],
382    ) -> Result<(PathBuf, String), Box<dyn std::error::Error>> {
383        let directory =
384            std::env::temp_dir().join(format!("sail-image-test-{name}-{}", std::process::id()));
385        let _ = std::fs::remove_dir_all(&directory);
386        std::fs::create_dir(&directory)?;
387        let source = directory.join("sail-runtime-worker");
388        std::fs::write(&source, bytes)?;
389        std::thread::sleep(sail_api::stamp::SETTLED + Duration::from_millis(100));
390        Ok((source, crate::hash(bytes)))
391    }
392
393    /// Removes the test's installed worker and its published entry.
394    fn remove(source: &Path, sha: &str) -> TestResult {
395        if let Some(root) = root() {
396            let _ = std::fs::remove_dir_all(entry(&root, source, sha));
397        }
398        std::fs::remove_dir_all(source.parent().ok_or("no parent")?)?;
399        Ok(())
400    }
401
402    #[test]
403    fn a_settled_worker_is_reused_until_either_file_changes() -> TestResult {
404        let (source, sha) = installed("reuse", b"worker bytes")?;
405        let first = image(&source, &sha)?;
406        assert!(first.reused(), "settled worker was not recorded");
407        assert_eq!(std::fs::read(first.executable())?, b"worker bytes");
408        assert!(verified(&source, &sha));
409        let second = image(&source, &sha)?;
410        assert!(second.reused());
411        assert_eq!(first.executable(), second.executable());
412        drop((first, second));
413        // The reused copy stays after its jobs end.
414        assert!(verified(&source, &sha));
415
416        // Same bytes rewritten in place: ctime moves, so verify again.
417        std::fs::write(&source, b"worker bytes")?;
418        assert!(!verified(&source, &sha));
419        let rewritten = image(&source, &sha)?;
420        assert!(!rewritten.reused(), "an unsettled rewrite was trusted");
421        let directory = rewritten
422            .executable()
423            .parent()
424            .ok_or("no parent")?
425            .to_owned();
426        drop(rewritten);
427        assert!(!directory.exists(), "per-job copy left behind");
428
429        // Different bytes are refused, reused or not.
430        std::fs::write(&source, b"other bytes")?;
431        assert!(image(&source, &sha).is_err());
432        assert!(!verified(&source, &sha));
433        remove(&source, &sha)?;
434        Ok(())
435    }
436
437    #[test]
438    fn a_tampered_private_copy_is_never_reused() -> TestResult {
439        let (source, sha) = installed("tamper", b"tamper worker")?;
440        let first = image(&source, &sha)?;
441        assert!(first.reused());
442        let copy = first.executable().to_owned();
443        drop(first);
444        std::fs::set_permissions(&copy, std::fs::Permissions::from_mode(0o700))?;
445        std::fs::write(&copy, b"tamper WORKER")?;
446        assert!(!verified(&source, &sha));
447        // The next job verifies the installed bytes again and republishes.
448        std::thread::sleep(Duration::from_millis(10));
449        let next = image(&source, &sha)?;
450        assert_eq!(std::fs::read(next.executable())?, b"tamper worker");
451        drop(next);
452        remove(&source, &sha)?;
453        Ok(())
454    }
455
456    #[test]
457    fn fresh_images_are_private_and_removed() -> TestResult {
458        let (source, sha) = installed("fresh", b"fresh worker")?;
459        let image = fresh(&source, &sha)?;
460        assert!(!image.reused());
461        let metadata = std::fs::symlink_metadata(image.executable())?;
462        assert_eq!(metadata.permissions().mode() & 0o777, 0o500);
463        let directory = image.executable().parent().ok_or("no parent")?.to_owned();
464        assert!(private_directory(&directory));
465        drop(image);
466        assert!(!directory.exists());
467        assert!(fresh(&source, "A".repeat(64).as_str()).is_err());
468        remove(&source, &sha)?;
469        Ok(())
470    }
471}