Skip to main content

litz_engine/
lock.rs

1//! `litz.lock`: which catalog entries and firmware bytes produced a result.
2//!
3//! This is the reproducibility boundary from `docs/formats.md` §5; the caller
4//! owns when to write, when to refuse and what `--update-lock` means.
5
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8use std::collections::{BTreeMap, BTreeSet};
9use std::fmt::Write as _;
10use std::path::Path;
11
12/// The schema version this build understands and writes.
13const LOCK_VERSION: u32 = 1;
14
15/// One `[[entry]]`: a catalog manifest a run loaded.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub struct LockEntry {
18    /// The catalog key (`part.id` / `board.id`), written as `type`.
19    #[serde(rename = "type")]
20    pub type_key: String,
21    pub version: String,
22    /// SHA-256 of the manifest text (see [`Lock::from_run`]).
23    pub sha256: String,
24}
25
26/// The `[firmware]` table: the image the run booted, plus what it flashed
27/// alongside it when the project supplied those.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Firmware {
30    pub sha256: String,
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub rom_sha256: Option<String>,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub bootloader_sha256: Option<String>,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub partition_table_sha256: Option<String>,
37}
38
39/// Everything a run consumed that can move between one green CI run and the
40/// next: the catalog manifests and the firmware bytes.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct Lock {
43    /// Always [`LOCK_VERSION`]; private so every `Lock` is one this module
44    /// knows how to write.
45    #[serde(default = "version_one")]
46    version: u32,
47    /// Written as `[[entry]]`, one table per manifest.
48    #[serde(rename = "entry", default)]
49    pub entries: Vec<LockEntry>,
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub firmware: Option<Firmware>,
52}
53
54fn version_one() -> u32 {
55    LOCK_VERSION
56}
57
58impl Lock {
59    /// Build the lock from what a run loaded: `catalog` holds one
60    /// `(type_key, version, manifest_text)` per entry; the remaining arguments
61    /// are the bytes it flashed (application image, mask ROM, bootloader,
62    /// partition table), `None` when absent.
63    ///
64    /// The manifest *text* is hashed, not its path: text is what behaviour
65    /// derives from, while a path is a checkout location that would make the
66    /// lock machine-specific. A builtin `include_str!` manifest and a
67    /// directory manifest with identical bytes therefore hash identically.
68    ///
69    /// Entries are sorted by catalog id so the file is canonical.
70    pub fn from_run(
71        catalog: &[(String, String, String)],
72        firmware: Option<&[u8]>,
73        rom: Option<&[u8]>,
74        bootloader: Option<&[u8]>,
75        partition_table: Option<&[u8]>,
76    ) -> Lock {
77        let mut entries: Vec<LockEntry> = catalog
78            .iter()
79            .map(|(key, version, text)| LockEntry {
80                type_key: key.clone(),
81                version: version.clone(),
82                sha256: sha256_hex(text.as_bytes()),
83            })
84            .collect();
85        entries.sort_by(|a, b| a.type_key.cmp(&b.type_key));
86        Lock {
87            version: LOCK_VERSION,
88            entries,
89            firmware: firmware.map(|app| Firmware {
90                sha256: sha256_hex(app),
91                rom_sha256: rom.map(sha256_hex),
92                bootloader_sha256: bootloader.map(sha256_hex),
93                partition_table_sha256: partition_table.map(sha256_hex),
94            }),
95        }
96    }
97
98    /// Read a lock file. A missing file is an `Err` like any I/O failure;
99    /// absence is not a mismatch, so the caller decides whether to write one.
100    pub fn load(path: &Path) -> Result<Lock, String> {
101        let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
102        let lock: Lock = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
103        if lock.version != LOCK_VERSION {
104            return Err(format!(
105                "{}: lock version {} is not supported; this litz writes version {LOCK_VERSION}",
106                path.display(),
107                lock.version
108            ));
109        }
110        Ok(lock)
111    }
112
113    /// Write the shape `docs/formats.md` §5 specifies.
114    pub fn write(&self, path: &Path) -> Result<(), String> {
115        let text = toml::to_string_pretty(self).map_err(|e| format!("{}: {e}", path.display()))?;
116        std::fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
117    }
118
119    /// Compare the committed lock (`self`) against what this run loaded
120    /// (`actual`). Every difference is named with its full hashes, and the
121    /// error points at `--update-lock`.
122    pub fn check(&self, actual: &Lock) -> Result<(), String> {
123        let mut notes = Vec::new();
124        diff(&mut notes, &entries(self), &entries(actual));
125        diff(
126            &mut notes,
127            &images(&self.firmware),
128            &images(&actual.firmware),
129        );
130        if notes.is_empty() {
131            return Ok(());
132        }
133        Err(format!(
134            "litz.lock does not match this run:\n  {}\nrun with --update-lock to rewrite litz.lock",
135            notes.join("\n  ")
136        ))
137    }
138}
139
140/// The comparable form of a catalog side: type to `version hash`.
141fn entries(lock: &Lock) -> BTreeMap<&str, String> {
142    lock.entries
143        .iter()
144        .map(|e| (e.type_key.as_str(), format!("{} {}", e.version, e.sha256)))
145        .collect()
146}
147
148/// The comparable form of a firmware side, only for images that were supplied.
149fn images(firmware: &Option<Firmware>) -> BTreeMap<&'static str, String> {
150    let mut images = BTreeMap::new();
151    if let Some(f) = firmware {
152        images.insert("firmware", f.sha256.clone());
153        if let Some(h) = &f.rom_sha256 {
154            images.insert("rom", h.clone());
155        }
156        if let Some(h) = &f.bootloader_sha256 {
157            images.insert("bootloader", h.clone());
158        }
159        if let Some(h) = &f.partition_table_sha256 {
160            images.insert("partition table", h.clone());
161        }
162    }
163    images
164}
165
166/// Name every key whose value differs, is missing or is new, in sorted order.
167fn diff(notes: &mut Vec<String>, locked: &BTreeMap<&str, String>, run: &BTreeMap<&str, String>) {
168    let keys: BTreeSet<&str> = locked.keys().chain(run.keys()).copied().collect();
169    for key in keys {
170        match (locked.get(key), run.get(key)) {
171            (Some(lock), Some(run)) if lock != run => {
172                notes.push(format!("changed: {key} (lock {lock}, run {run})"))
173            }
174            (Some(lock), None) => notes.push(format!("removed: {key} {lock}")),
175            (None, Some(run)) => notes.push(format!("added: {key} {run}")),
176            _ => {}
177        }
178    }
179}
180
181/// Lowercase hex SHA-256, 64 characters.
182pub fn sha256_hex(bytes: &[u8]) -> String {
183    let digest = Sha256::digest(bytes);
184    let digest: &[u8] = digest.as_ref();
185    let mut hex = String::with_capacity(64);
186    for &byte in digest {
187        // Writing into a `String` cannot fail.
188        let _ = write!(hex, "{byte:02x}");
189    }
190    hex
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use std::path::PathBuf;
197    use std::sync::atomic::{AtomicU64, Ordering};
198
199    fn temp_file(tag: &str) -> PathBuf {
200        static NEXT: AtomicU64 = AtomicU64::new(0);
201        let n = NEXT.fetch_add(1, Ordering::Relaxed);
202        std::env::temp_dir().join(format!("litz-lock-{}-{n}-{tag}.lock", std::process::id()))
203    }
204
205    fn catalog() -> Vec<(String, String, String)> {
206        ["litz-led", "litz-resistor"]
207            .map(|id| {
208                (
209                    id.to_string(),
210                    "1.0.0".to_string(),
211                    format!("[part]\nid = {id:?}\nversion = \"1.0.0\"\n"),
212                )
213            })
214            .to_vec()
215    }
216
217    fn sample() -> Lock {
218        Lock::from_run(&catalog(), Some(b"application image"), None, None, None)
219    }
220
221    #[test]
222    fn a_lock_round_trips_through_its_file() {
223        let path = temp_file("roundtrip");
224        let lock = sample();
225        lock.write(&path).unwrap();
226        let text = std::fs::read_to_string(&path).unwrap();
227        assert!(
228            text.contains("version = 1")
229                && text.contains("[[entry]]")
230                && text.contains("[firmware]"),
231            "{text}"
232        );
233        assert_eq!(Lock::load(&path).unwrap(), lock);
234        let _ = std::fs::remove_file(&path);
235    }
236
237    #[test]
238    fn check_accepts_a_match_and_names_every_difference() {
239        let lock = sample();
240        assert!(lock.check(&sample()).is_ok());
241
242        let mut catalog = catalog();
243        catalog[0].2.push_str("# the LED was repainted\n");
244        let changed = Lock::from_run(&catalog, Some(b"application image"), None, None, None);
245        let err = lock.check(&changed).unwrap_err();
246        assert!(
247            err.contains("changed: litz-led") && err.contains("--update-lock"),
248            "{err}"
249        );
250
251        let mut actual = sample();
252        actual.entries.retain(|e| e.type_key != "litz-led");
253        actual.entries.push(LockEntry {
254            type_key: "litz-buzzer".into(),
255            version: "1.0.0".into(),
256            sha256: sha256_hex(b"buzz"),
257        });
258        let err = lock.check(&actual).unwrap_err();
259        assert!(
260            err.contains("removed: litz-led") && err.contains("added: litz-buzzer"),
261            "{err}"
262        );
263    }
264
265    #[test]
266    fn sha256_of_nothing_is_the_known_value() {
267        assert_eq!(
268            sha256_hex(b""),
269            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
270        );
271        assert_eq!(sha256_hex(b"abc").len(), 64);
272    }
273}