1use anyhow::{Context, Result};
9use serde::{Deserialize, Serialize};
10use std::io::{Read, Seek, SeekFrom};
11use std::path::{Path, PathBuf};
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Provenance {
16 pub builder_version: String,
18 pub build_commit: String,
22 pub build_dirty: bool,
25 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#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct IsoIdentity {
36 pub file_name: String,
37 pub size_bytes: u64,
38 pub sha256: String,
40 pub pvd_creation: Option<String>,
43 pub wim_images: Vec<String>,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct HostSpecs {
50 pub os: String,
51 pub os_version: String,
54 pub arch: String,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct DependencyPins {
60 #[serde(alias = "qemu_version")]
65 pub qemu_tag: String,
66 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct GuestParams {
81 pub arch: String,
82 pub username: String,
83 pub locale: String,
84 #[serde(default = "unknown_accel")]
89 pub accel: String,
90}
91
92fn unknown_accel() -> String {
94 "unknown".to_string()
95}
96
97#[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 pub const LOG: &str = "tested-isos.jsonl";
110
111 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 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
149pub 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
166pub 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 || §or[1..6] != b"CD001" {
175 return Ok(None);
176 }
177 let raw = §or[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
184pub 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 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
225fn 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 #[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 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 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 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 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 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}