Skip to main content

sail_api/
stamp.rs

1//! Complete stat stamps and the settle rule for cross-run stat trust
2//! (ADR 0082).
3//!
4//! A [`Stamp`] is a file's device, inode, size, mode, mtime and ctime, both
5//! times with nanoseconds. A user program can set mtime but not ctime, and
6//! every write, rename onto the path, `chmod` or `utimes` advances ctime.
7//! A stamp may be trusted across runs only once its ctime is at least
8//! [`SETTLED`] older than the moment observation began
9//! ([`Stamp::settled`]): a later change then moves ctime past the recorded
10//! one even on a filesystem with a coarse clock. Unchanged-call replay and
11//! the daemon's solver identity both use it.
12
13use serde::{Deserialize, Serialize};
14use std::time::{Duration, SystemTime, UNIX_EPOCH};
15
16/// How much older than the start of an observation a trusted ctime must be.
17pub const SETTLED: Duration = Duration::from_secs(2);
18
19/// A complete stat stamp: device, inode, size, mode, mtime and ctime with
20/// nanoseconds.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
22pub struct Stamp([i64; 8]);
23
24impl Stamp {
25    /// The stamp of the file `metadata` describes.
26    #[cfg(unix)]
27    #[must_use]
28    pub fn of(metadata: &std::fs::Metadata) -> Self {
29        use std::os::unix::fs::MetadataExt as _;
30        // Bit-for-bit, so distinct unsigned values never share a field.
31        let wide = |value: u64| i64::from_ne_bytes(value.to_ne_bytes());
32        Self([
33            wide(metadata.dev()),
34            wide(metadata.ino()),
35            wide(metadata.size()),
36            i64::from(metadata.mode()),
37            metadata.mtime(),
38            metadata.mtime_nsec(),
39            metadata.ctime(),
40            metadata.ctime_nsec(),
41        ])
42    }
43
44    /// Without a ctime there is no cross-run stat trust: the stamp is never
45    /// [settled](Self::settled).
46    #[cfg(not(unix))]
47    #[must_use]
48    pub fn of(_metadata: &std::fs::Metadata) -> Self {
49        Self([0, 0, 0, 0, 0, 0, -1, -1])
50    }
51
52    /// Whether the last status change happened at least [`SETTLED`] before
53    /// `start`. A ctime before the epoch or after `start` is never settled.
54    #[must_use]
55    pub fn settled(self, start: SystemTime) -> bool {
56        let (Ok(seconds), Ok(nanos)) = (u64::try_from(self.0[6]), u64::try_from(self.0[7])) else {
57            return false;
58        };
59        let Some(changed) = UNIX_EPOCH
60            .checked_add(Duration::from_secs(seconds))
61            .and_then(|t| t.checked_add(Duration::from_nanos(nanos)))
62        else {
63            return false;
64        };
65        start
66            .duration_since(changed)
67            .is_ok_and(|age| age >= SETTLED)
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    fn at(ctime: Duration) -> Stamp {
76        let mut fields = [0; 8];
77        fields[6] = i64::try_from(ctime.as_secs()).unwrap_or(i64::MAX);
78        fields[7] = i64::from(ctime.subsec_nanos());
79        Stamp(fields)
80    }
81
82    #[test]
83    fn only_status_changes_two_seconds_before_the_start_are_settled() {
84        let start = UNIX_EPOCH + Duration::from_secs(1_000);
85        assert!(at(Duration::from_secs(998)).settled(start));
86        assert!(at(Duration::from_secs(997)).settled(start));
87        assert!(!at(Duration::from_millis(998_001)).settled(start));
88        assert!(!at(Duration::from_millis(998_500)).settled(start));
89        assert!(!at(Duration::from_secs(1_000)).settled(start));
90        assert!(!at(Duration::from_secs(1_001)).settled(start));
91        let mut negative = at(Duration::ZERO);
92        negative.0[6] = -1;
93        assert!(!negative.settled(start));
94    }
95
96    #[test]
97    fn the_serialized_form_is_the_field_array() -> serde_json::Result<()> {
98        let stamp = Stamp([1, 2, 3, 4, 5, 6, 7, 8]);
99        let text = serde_json::to_string(&stamp)?;
100        assert_eq!(text, "[1,2,3,4,5,6,7,8]");
101        assert_eq!(serde_json::from_str::<Stamp>(&text)?, stamp);
102        Ok(())
103    }
104
105    #[cfg(unix)]
106    #[test]
107    fn a_fresh_file_is_stamped_but_not_settled() -> std::io::Result<()> {
108        let path = std::env::temp_dir().join(format!("sail-stamp-{}", std::process::id()));
109        std::fs::write(&path, b"x")?;
110        let stamp = Stamp::of(&std::fs::metadata(&path)?);
111        std::fs::remove_file(&path)?;
112        assert!(!stamp.settled(SystemTime::now()));
113        Ok(())
114    }
115}