Skip to main content

windows_headless/
provenance.rs

1//! Build provenance sidecar: `build-media` writes `<out>.json` next to the
2//! installer image, capturing everything needed to reproduce or audit the
3//! build — source ISO identity, host specs, portable dependency pins, and
4//! answer-file parameters (never secrets: no passwords, keys, or tokens).
5//!
6//! The sibling `install` success path appends one line per proven
7//! run to the committed `tested-isos.jsonl` log (see [`TestRecord`]).
8use anyhow::{Context, Result};
9use serde::{Deserialize, Serialize};
10use std::io::{Read, Seek, SeekFrom};
11use std::path::{Path, PathBuf};
12
13/// Everything `build-media` records about one installer image build.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Provenance {
16    /// This crate's version (`CARGO_PKG_VERSION` at compile time).
17    pub builder_version: String,
18    /// Git commit the binary was built from (`BUILD_GIT_SHA` via build.rs;
19    /// `"unknown"` for tarball builds without `.git`). This is the field
20    /// that distinguishes debug runs — the version only changes on bump.
21    pub build_commit: String,
22    /// Uncommitted changes present at compile time (`BUILD_GIT_DIRTY`).
23    /// `true` means the commit hash alone does NOT reproduce the binary.
24    pub build_dirty: bool,
25    /// UTC build timestamp (RFC 3339-ish, no chrono dep: seconds epoch).
26    pub built_at_epoch: u64,
27    pub source_iso: IsoIdentity,
28    pub host: HostSpecs,
29    pub deps: DependencyPins,
30    pub guest: GuestParams,
31}
32
33/// Identity of the user-supplied retail Windows ISO.
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct IsoIdentity {
36    pub file_name: String,
37    pub size_bytes: u64,
38    /// SHA-256 hex of the full ISO (a ~30 s pass on 7 GB; the dedup key).
39    pub sha256: String,
40    /// ISO9660 PVD volume creation stamp, as printed in the descriptor.
41    /// Best-effort: `None` on UDF-only images or parse failure.
42    pub pvd_creation: Option<String>,
43    /// `install.wim` image names from `wimlib-imagex info` (best-effort).
44    pub wim_images: Vec<String>,
45}
46
47/// The machine that ran the build.
48#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct HostSpecs {
50    pub os: String,
51    /// `sw_vers -productVersion` on macOS, `PRETTY_NAME` from
52    /// `/etc/os-release` on Linux, else `"unknown"`.
53    pub os_version: String,
54    pub arch: String,
55}
56
57/// Every external input that isn't the ISO.
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct DependencyPins {
60    /// Full portable release tag (`qemu-v11.1.1-57`), never a bare
61    /// version — rebuild tags mean a version no longer names a unique
62    /// build. Renamed from `qemu_version`; the alias keeps old log lines
63    /// parsing.
64    #[serde(alias = "qemu_version")]
65    pub qemu_tag: String,
66    /// Full portable release tag (`wimlib-v1.14.5-27`), never a bare
67    /// version — rebuild tags mean a version no longer names a unique
68    /// build. Renamed from `wimlib_version`; the alias keeps old log
69    /// lines parsing.
70    #[serde(alias = "wimlib_version")]
71    pub wimlib_tag: String,
72    pub virtio_iso_name: String,
73    pub virtio_sha256: Option<String>,
74    pub openssh_zip_name: String,
75    pub openssh_release_tag: String,
76}
77
78/// Answer-file parameters (usernames/locales only — never the password).
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct GuestParams {
81    pub arch: String,
82    pub username: String,
83    pub locale: String,
84    /// QEMU accelerator actually used (`hvf`/`kvm`/`tcg`): recorded so the
85    /// tested table can say whether TCG was ever exercised. Resolved at
86    /// gather time via [`crate::unattend::resolve_accel`], same probe as boot.
87    /// Defaults to `"unknown"` for log lines written before this field existed.
88    #[serde(default = "unknown_accel")]
89    pub accel: String,
90}
91
92/// Default for log lines predating the `accel` field.
93fn unknown_accel() -> String {
94    "unknown".to_string()
95}
96
97/// One line in the committed `tested-isos.jsonl` log: ISO identity plus
98/// the install outcome. Written by `install` on SSH-banner success.
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct TestRecord {
101    pub tested_at_epoch: u64,
102    pub outcome: String,
103    pub ssh_banner: Option<String>,
104    pub provenance: Provenance,
105}
106
107impl TestRecord {
108    /// Committed log filename (repo root, current dir at runtime).
109    pub const LOG: &str = "tested-isos.jsonl";
110
111    /// Append one line to [`TestRecord::LOG`] in the current directory
112    /// (repo root in practice). Creates the file on first use.
113    pub fn append(provenance: Provenance, banner: &str) -> Result<PathBuf> {
114        let record = Self {
115            tested_at_epoch: now_epoch(),
116            outcome: "ssh-banner".to_string(),
117            ssh_banner: Some(banner.trim().to_string()),
118            provenance,
119        };
120        let path = PathBuf::from(Self::LOG);
121        let mut line = serde_json::to_string(&record)?;
122        line.push('\n');
123        use std::io::Write;
124        std::fs::OpenOptions::new()
125            .create(true)
126            .append(true)
127            .open(&path)?
128            .write_all(line.as_bytes())?;
129        eprintln!("proven: {}", path.display());
130        Ok(path)
131    }
132
133    /// Load the sidecar written by `build-media` for this image.
134    pub fn load_sidecar(image: &Path) -> Result<Provenance> {
135        let path = Provenance::sidecar_path(image);
136        let json = std::fs::read_to_string(&path)
137            .with_context(|| format!("read sidecar {}", path.display()))?;
138        serde_json::from_str(&json).with_context(|| format!("parse sidecar {}", path.display()))
139    }
140}
141
142pub fn now_epoch() -> u64 {
143    std::time::SystemTime::now()
144        .duration_since(std::time::UNIX_EPOCH)
145        .map(|d| d.as_secs())
146        .unwrap_or(0)
147}
148
149/// SHA-256 hex of a file, streamed (never whole in RAM).
150pub fn sha256_file(path: &Path) -> Result<String> {
151    use sha2::Digest;
152    let mut f = std::fs::File::open(path)
153        .with_context(|| format!("open {} for hashing", path.display()))?;
154    let mut h = sha2::Sha256::new();
155    let mut buf = vec![0u8; 1024 * 1024];
156    loop {
157        let n = f.read(&mut buf)?;
158        if n == 0 {
159            break;
160        }
161        h.update(&buf[..n]);
162    }
163    Ok(hex::encode(h.finalize()))
164}
165
166/// ISO9660 PVD volume-creation stamp: sector 16, offset 40, 17 ASCII bytes
167/// (`YYYYMMDDHHMMSScc`) + 1 offset byte. Returns the raw 17-char stamp.
168/// `None` when the sector isn't a PVD (UDF-only image) — not an error.
169pub fn pvd_creation_stamp(iso: &Path) -> Result<Option<String>> {
170    let mut f = std::fs::File::open(iso)?;
171    f.seek(SeekFrom::Start(16 * 2048))?;
172    let mut sector = vec![0u8; 2048];
173    f.read_exact(&mut sector)?;
174    if sector[0] != 1 || &sector[1..6] != b"CD001" {
175        return Ok(None);
176    }
177    let raw = &sector[40..57];
178    if !raw.iter().all(|b| b.is_ascii_digit()) {
179        return Ok(None);
180    }
181    Ok(Some(String::from_utf8_lossy(raw).into_owned()))
182}
183
184/// `install.wim` image names via `wimlib-imagex info` (best-effort:
185/// empty vec on any failure — provenance must never fail the build).
186pub fn wim_image_names(wimlib_bin: &Path, wim_path: &Path) -> Vec<String> {
187    let out = std::process::Command::new(wimlib_bin)
188        .args(["info", &wim_path.to_string_lossy()])
189        .output();
190    let Ok(out) = out else { return Vec::new() };
191    if !out.status.success() {
192        return Vec::new();
193    }
194    let text = String::from_utf8_lossy(&out.stdout);
195    // `wimlib-imagex info` prints `Index: N` + `Name: "..."` per image.
196    text.lines()
197        .filter_map(|l| {
198            let (_, name) = l.trim_start().split_once("Name:")?;
199            Some(name.trim().trim_matches('"').to_string())
200        })
201        .filter(|n| !n.is_empty())
202        .collect()
203}
204
205fn host_specs() -> HostSpecs {
206    let os_version = match std::env::consts::OS {
207        "macos" => std::process::Command::new("sw_vers")
208            .arg("-productVersion")
209            .output()
210            .ok()
211            .filter(|o| o.status.success())
212            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
213            .filter(|s| !s.is_empty())
214            .unwrap_or_else(|| "unknown".to_string()),
215        "linux" => linux_pretty_name(),
216        _ => "unknown".to_string(),
217    };
218    HostSpecs {
219        os: std::env::consts::OS.to_string(),
220        os_version,
221        arch: std::env::consts::ARCH.to_string(),
222    }
223}
224
225/// Distribution name from `/etc/os-release`'s `PRETTY_NAME`
226/// (e.g. `Ubuntu 24.04.1 LTS`); `"unknown"` when the file or the key
227/// is missing. Parsing lives in [`os_release_pretty_name`] so it can
228/// be tested without the file.
229fn linux_pretty_name() -> String {
230    std::fs::read_to_string("/etc/os-release")
231        .ok()
232        .and_then(|c| os_release_pretty_name(&c))
233        .unwrap_or_else(|| "unknown".to_string())
234}
235
236fn os_release_pretty_name(content: &str) -> Option<String> {
237    content.lines().find_map(|line| {
238        let value = line.strip_prefix("PRETTY_NAME=")?.trim();
239        let value = value
240            .strip_prefix('"')
241            .and_then(|v| v.strip_suffix('"'))
242            .unwrap_or(value);
243        (!value.is_empty()).then(|| value.to_string())
244    })
245}
246
247impl Provenance {
248    /// Gather provenance for a `build-media` run. `wim_path` is the
249    /// extracted `install.wim` (queried via `wimlib-imagex info`, then the
250    /// caller deletes it). Slow steps (ISO hash) print progress.
251    /// Best-effort sub-steps degrade to `None`/empty — only hard I/O
252    /// errors propagate. Nine params is the honest shape (every input is
253    /// recorded); grouping them would hide what the sidecar captures.
254    #[allow(clippy::too_many_arguments)]
255    pub fn gather(
256        win_iso: &Path,
257        wimlib_bin: &Path,
258        wim_path: &Path,
259        arch: crate::unattend::Architecture,
260        qemu_tag: &str,
261        wimlib_tag: &str,
262        virtio_iso: Option<&Path>,
263        username: &str,
264        locale: &str,
265    ) -> Result<Self> {
266        let meta = std::fs::metadata(win_iso)?;
267        let file_name = win_iso
268            .file_name()
269            .map(|n| n.to_string_lossy().into_owned())
270            .unwrap_or_else(|| win_iso.display().to_string());
271        eprintln!("media: hashing source ISO (one pass, ~30 s) ...");
272        let sha256 = sha256_file(win_iso)?;
273        let pvd_creation = pvd_creation_stamp(win_iso).unwrap_or(None);
274        let wim_images = wim_image_names(wimlib_bin, wim_path);
275        let (virtio_iso_name, virtio_sha256) = match virtio_iso {
276            Some(p) => (
277                p.file_name()
278                    .map(|n| n.to_string_lossy().into_owned())
279                    .unwrap_or_default(),
280                sha256_file(p).ok(),
281            ),
282            None => ("<drivers-dir>".to_string(), None),
283        };
284        Ok(Self {
285            builder_version: env!("CARGO_PKG_VERSION").to_string(),
286            build_commit: option_env!("BUILD_GIT_SHA")
287                .unwrap_or("unknown")
288                .to_string(),
289            build_dirty: option_env!("BUILD_GIT_DIRTY").is_some_and(|v| v == "true"),
290            built_at_epoch: now_epoch(),
291            source_iso: IsoIdentity {
292                file_name,
293                size_bytes: meta.len(),
294                sha256,
295                pvd_creation,
296                wim_images,
297            },
298            host: host_specs(),
299            deps: DependencyPins {
300                qemu_tag: qemu_tag.to_string(),
301                wimlib_tag: wimlib_tag.to_string(),
302                virtio_iso_name,
303                virtio_sha256,
304                openssh_zip_name: arch.openssh_zip_name().to_string(),
305                openssh_release_tag: crate::pins::OPENSSH_RELEASE_TAG.to_string(),
306            },
307            guest: GuestParams {
308                arch: arch.as_xml_str().to_string(),
309                username: username.to_string(),
310                locale: locale.to_string(),
311                accel: crate::unattend::resolve_accel().to_string(),
312            },
313        })
314    }
315
316    /// `<image>.json` next to the installer image.
317    pub fn sidecar_path(image: &Path) -> PathBuf {
318        let mut s = image.as_os_str().to_owned();
319        s.push(".json");
320        PathBuf::from(s)
321    }
322
323    /// Invalidate a previous build: delete its sidecar so a crashed/failed
324    /// rebuild can never report "fresh" over a partial image. Runs at build
325    /// start (after the freshness skip); missing file is fine.
326    pub fn invalidate(image: &Path) {
327        let _ = std::fs::remove_file(Self::sidecar_path(image));
328    }
329
330    pub fn write_sidecar(&self, image: &Path) -> Result<PathBuf> {
331        let path = Self::sidecar_path(image);
332        let json = serde_json::to_string_pretty(self)?;
333        std::fs::write(&path, json)?;
334        eprintln!("media: provenance {}", path.display());
335        Ok(path)
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    fn synthetic_pvd(stamp: &[u8; 17]) -> Vec<u8> {
344        // 16 empty sectors + PVD with "CD001" + stamp at offset 40.
345        let mut img = vec![0u8; 17 * 2048];
346        img[16 * 2048] = 1;
347        img[16 * 2048 + 1..16 * 2048 + 6].copy_from_slice(b"CD001");
348        img[16 * 2048 + 40..16 * 2048 + 57].copy_from_slice(stamp);
349        img
350    }
351
352    #[test]
353    fn pvd_stamp_parses() {
354        let dir = tempfile::tempdir().unwrap();
355        let p = dir.path().join("fake.iso");
356        std::fs::write(&p, synthetic_pvd(b"20260922093000000")).unwrap();
357        assert_eq!(
358            pvd_creation_stamp(&p).unwrap(),
359            Some("20260922093000000".to_string())
360        );
361    }
362
363    #[test]
364    fn pvd_absent_on_non_iso9660() {
365        let dir = tempfile::tempdir().unwrap();
366        let p = dir.path().join("fake.iso");
367        std::fs::write(&p, vec![0u8; 17 * 2048]).unwrap();
368        assert_eq!(pvd_creation_stamp(&p).unwrap(), None);
369    }
370
371    #[test]
372    fn os_release_pretty_name_parses() {
373        let s = "NAME=\"Ubuntu\"\nPRETTY_NAME=\"Ubuntu 26.04.1 LTS\"\nID=ubuntu\n";
374        assert_eq!(
375            os_release_pretty_name(s),
376            Some("Ubuntu 26.04.1 LTS".to_string())
377        );
378        // Unquoted values are legal per os-release(5).
379        assert_eq!(
380            os_release_pretty_name("PRETTY_NAME=Alpine Linux v3.20"),
381            Some("Alpine Linux v3.20".to_string())
382        );
383    }
384
385    #[test]
386    fn os_release_pretty_name_missing_is_none() {
387        assert_eq!(os_release_pretty_name("ID=ubuntu\n"), None);
388        assert_eq!(os_release_pretty_name("PRETTY_NAME=\n"), None);
389    }
390
391    #[test]
392    fn provenance_json_roundtrip() {
393        let prov = Provenance {
394            builder_version: "0.1.0-alpha".to_string(),
395            build_commit: "abc123def456".to_string(),
396            build_dirty: true,
397            built_at_epoch: 1_758_000_000,
398            source_iso: IsoIdentity {
399                file_name: "Win11.iso".to_string(),
400                size_bytes: 7_000_000_000,
401                sha256: "abc".to_string(),
402                pvd_creation: Some("20260922093000000".to_string()),
403                wim_images: vec!["Windows 11 Pro".to_string()],
404            },
405            host: HostSpecs {
406                os: "macos".to_string(),
407                os_version: "26.0".to_string(),
408                arch: "aarch64".to_string(),
409            },
410            deps: DependencyPins {
411                qemu_tag: "qemu-v11.1.1".to_string(),
412                wimlib_tag: "wimlib-v1.14.5-27".to_string(),
413                virtio_iso_name: "virtio-win.iso".to_string(),
414                virtio_sha256: Some("def".to_string()),
415                openssh_zip_name: "OpenSSH-ARM64.zip".to_string(),
416                openssh_release_tag: crate::pins::OPENSSH_RELEASE_TAG.to_string(),
417            },
418            guest: GuestParams {
419                arch: "arm64".to_string(),
420                username: crate::unattend::DEFAULT_USERNAME.to_string(),
421                locale: "en-US".to_string(),
422                accel: "hvf".to_string(),
423            },
424        };
425        let json = serde_json::to_string(&prov).unwrap();
426        assert!(
427            !json.contains(crate::unattend::DEFAULT_PASSWORD),
428            "no secrets in provenance"
429        );
430        let back: Provenance = serde_json::from_str(&json).unwrap();
431        assert_eq!(back.source_iso.file_name, "Win11.iso");
432        assert_eq!(back.deps.qemu_tag, "qemu-v11.1.1");
433        assert_eq!(back.deps.wimlib_tag, "wimlib-v1.14.5-27");
434        // Old log lines used `qemu_version`/`wimlib_version` — the aliases
435        // keep them parsing.
436        let old = json
437            .replace("qemu_tag", "qemu_version")
438            .replace("wimlib_tag", "wimlib_version");
439        let back_old: Provenance = serde_json::from_str(&old).unwrap();
440        assert_eq!(back_old.deps.qemu_tag, "qemu-v11.1.1");
441        assert_eq!(back_old.deps.wimlib_tag, "wimlib-v1.14.5-27");
442    }
443}