aegis-hwsim 0.1.1

QEMU+OVMF+swtpm hardware-persona matrix harness for aegis-boot signed-chain testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! QEMU invocation synthesis.
//!
//! Given a validated [`Persona`] + the paths for the USB stick, working
//! directory, firmware root, and (optional) swtpm socket, produces a
//! fully-configured [`std::process::Command`] ready to spawn. No shell
//! sits between the persona string fields and QEMU — argv elements go
//! through `Command::args()` as literals, so shell metacharacters in
//! DMI fields pass through verbatim.
//!
//! # Architecture
//!
//! Split into two layers:
//!
//! - **[`build_argv`]** — pure argv composition. Takes all resolved
//!   paths as inputs, returns `Vec<String>`. Testable against every
//!   persona-variant combination without touching the filesystem.
//! - **[`Invocation::new`]** — the I/O layer. Calls [`crate::ovmf::resolve`]
//!   to find the firmware paths, copies `OVMF_VARS` into the per-run
//!   directory so the VM gets its own SB-variable state, computes the
//!   swtpm socket via the caller-supplied [`crate::swtpm::SwtpmInstance`],
//!   then delegates to `build_argv`.
//!
//! # Security
//!
//! Three defenses layered at this boundary:
//!
//! 1. **No shell.** `Command::args()` passes argv as literals; no shell
//!    interpolation path exists. Shell-metachar fuzz (E2.6, #23) lives
//!    here.
//! 2. **No NUL in argv.** [`smbios_argv`] rejects NUL upfront;
//!    [`Invocation::new`] repeats the check for the stick path.
//! 3. **Path canonicalization + sandbox boundary.** The stick path must
//!    exist and is canonicalized before being passed to QEMU. The
//!    per-run `OVMF_VARS` copy is also canonicalized after the copy
//!    lands and must `starts_with` the canonicalized work root — a
//!    pre-existing symlink at the destination cannot redirect QEMU's
//!    SB-variable writes outside the run's sandbox (E2.7, #24).

use crate::ovmf::{self, OvmfError};
use crate::persona::{Persona, TpmVersion};
use crate::smbios::{self, SmbiosError};
use crate::swtpm::SwtpmInstance;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use thiserror::Error;

/// A composed QEMU invocation. Built by [`Invocation::new`], consumed
/// by [`Invocation::build`].
#[derive(Debug, Clone)]
pub struct Invocation {
    argv: Vec<String>,
    vars_copy: PathBuf,
}

impl Invocation {
    /// Compose a QEMU invocation for `persona`. Runs the I/O steps
    /// (resolve firmware paths, copy `OVMF_VARS` into `work_dir/<run_id>/`),
    /// then delegates argv composition to [`build_argv`].
    ///
    /// `swtpm` is the live swtpm instance from [`SwtpmInstance::spawn`];
    /// if it's [`SwtpmInstance::NoTpm`], the returned argv omits the
    /// TPM chardev/tpmdev wiring.
    ///
    /// # Errors
    ///
    /// See [`InvocationError`] variants.
    pub fn new(
        persona: &Persona,
        stick: &Path,
        work_dir: &Path,
        firmware_root: &Path,
        swtpm: &SwtpmInstance,
    ) -> Result<Self, InvocationError> {
        // Stick must exist + contain no NUL (argv safety).
        if stick.to_string_lossy().contains('\0') {
            return Err(InvocationError::StickPathInvalid {
                path: stick.to_path_buf(),
                reason: "path contains NUL byte; QEMU argv cannot encode it",
            });
        }
        let stick_canon = fs::canonicalize(stick).map_err(|e| InvocationError::StickNotFound {
            path: stick.to_path_buf(),
            kind: e.to_string(),
        })?;

        // Resolve `OVMF_CODE` + VARS template (the CustomPk keyring check
        // is done by ovmf::resolve).
        let paths = ovmf::resolve(
            persona.secure_boot.ovmf_variant,
            persona.secure_boot.custom_keyring.as_deref(),
            firmware_root,
        )?;

        // Copy VARS template → per-run copy so each VM has isolated SB state.
        // E2.7 path-boundary: the work_dir is canonicalized first, then
        // every path we materialize underneath is required to land
        // *inside* the canonicalized root. Symlinks and `..` traversal
        // can't escape because we canonicalize the destination AFTER
        // the copy lands (which resolves any symlink swapped in mid-op)
        // and re-check `starts_with`.
        fs::create_dir_all(work_dir).map_err(|e| InvocationError::WorkDirInaccessible {
            path: work_dir.to_path_buf(),
            kind: e.to_string(),
        })?;
        let work_root_canon =
            fs::canonicalize(work_dir).map_err(|e| InvocationError::WorkDirInaccessible {
                path: work_dir.to_path_buf(),
                kind: e.to_string(),
            })?;
        let vars_copy = work_root_canon.join("OVMF_VARS.fd");
        fs::copy(&paths.vars_template, &vars_copy).map_err(|e| {
            InvocationError::VarsCopyFailed {
                from: paths.vars_template.clone(),
                to: vars_copy.clone(),
                kind: e.to_string(),
            }
        })?;

        // Defense in depth: re-canonicalize the just-created copy and
        // confirm it lives under the canonicalized work root. A
        // pre-existing symlink at `vars_copy` pointing outside the root
        // would cause fs::copy to write to the symlink target; this
        // check catches that exact escape path.
        let vars_copy_canon =
            fs::canonicalize(&vars_copy).map_err(|e| InvocationError::VarsCopyFailed {
                from: paths.vars_template.clone(),
                to: vars_copy.clone(),
                kind: e.to_string(),
            })?;
        if !vars_copy_canon.starts_with(&work_root_canon) {
            return Err(InvocationError::VarsCopyEscapedRoot {
                vars_copy: vars_copy_canon,
                work_root: work_root_canon,
            });
        }

        let argv = build_argv(persona, &paths.code, &vars_copy_canon, &stick_canon, swtpm)?;
        Ok(Self {
            argv,
            vars_copy: vars_copy_canon,
        })
    }

    /// Produce a `std::process::Command` ready to spawn. The caller is
    /// responsible for attaching stdin/stdout/stderr.
    #[must_use]
    pub fn build(&self) -> Command {
        let mut cmd = Command::new("qemu-system-x86_64");
        cmd.args(&self.argv);
        cmd
    }

    /// Access the argv vec directly (useful for testing + diagnostics).
    #[must_use]
    pub fn argv(&self) -> &[String] {
        &self.argv
    }

    /// The per-run `OVMF_VARS` copy path. Kept around so the caller can
    /// inspect SB state after the VM exits.
    #[must_use]
    pub fn vars_copy(&self) -> &Path {
        &self.vars_copy
    }
}

/// Compose QEMU argv from resolved paths. Pure — no filesystem I/O.
///
/// Emits, in order:
/// - `-machine q35,smm=on,accel=kvm:tcg` (SMM required for SB; KVM with TCG fallback)
/// - `-cpu qemu64` (portable baseline; persona-specific CPU flags can be added later)
/// - `-m 4096` (4 GB default)
/// - `-drive` pflash `OVMF_CODE` (readonly)
/// - `-drive` pflash `OVMF_VARS` (per-run copy)
/// - `-drive` + `-device usb-storage` for the aegis-boot stick
/// - For non-`NoTpm` swtpm: `-chardev`, `-tpmdev`, `-device tpm-crb`
/// - `-smbios` blocks from [`smbios::smbios_argv`]
/// - `-nographic -serial mon:stdio`
///
/// # Errors
///
/// - [`InvocationError::Smbios`] if DMI field rejection fires (NUL bytes).
pub fn build_argv(
    persona: &Persona,
    ovmf_code: &Path,
    ovmf_vars_copy: &Path,
    stick: &Path,
    swtpm: &SwtpmInstance,
) -> Result<Vec<String>, InvocationError> {
    let mut argv: Vec<String> = Vec::with_capacity(32);

    // Machine + firmware.
    argv.extend([
        "-machine".into(),
        "q35,smm=on,accel=kvm:tcg".into(),
        "-cpu".into(),
        "qemu64".into(),
        "-m".into(),
        "4096".into(),
        "-drive".into(),
        format!(
            "if=pflash,format=raw,unit=0,readonly=on,file={}",
            ovmf_code.display()
        ),
        "-drive".into(),
        format!(
            "if=pflash,format=raw,unit=1,file={}",
            ovmf_vars_copy.display()
        ),
    ]);

    // USB stick. q35 doesn't ship a USB controller by default; explicit
    // qemu-xhci needed before usb-storage can attach to a bus.
    argv.extend([
        "-device".into(),
        "qemu-xhci,id=xhci".into(),
        "-drive".into(),
        format!("file={},format=raw,if=none,id=stick", stick.display()),
        "-device".into(),
        "usb-storage,bus=xhci.0,drive=stick".into(),
    ]);

    // TPM wiring (skipped when SwtpmInstance::NoTpm).
    if let Some(sock) = swtpm.socket_path() {
        argv.extend([
            "-chardev".into(),
            format!("socket,id=chrtpm,path={}", sock.display()),
            "-tpmdev".into(),
            "emulator,id=tpm,chardev=chrtpm".into(),
            "-device".into(),
            tpm_device_for_version(persona.tpm.version).into(),
        ]);
    }

    // SMBIOS from DMI (propagates NUL-rejection through InvocationError::Smbios).
    argv.extend(smbios::smbios_argv(&persona.dmi)?);

    // Headless serial.
    argv.extend(["-nographic".into(), "-serial".into(), "mon:stdio".into()]);

    Ok(argv)
}

/// QEMU device name for a given TPM interface. TPM 2.0 uses CRB; TPM 1.2
/// uses TIS. The `None` arm is unreachable in practice because
/// [`SwtpmInstance::socket_path`] returns `None` for the `NoTpm`
/// variant and the caller already branched on that; we fold it into the
/// CRB arm so clippy's `match_same_arms` stays happy without hiding the
/// logical cases.
fn tpm_device_for_version(v: TpmVersion) -> &'static str {
    match v {
        TpmVersion::Tpm12 => "tpm-tis,tpmdev=tpm",
        TpmVersion::Tpm20 | TpmVersion::None => "tpm-crb,tpmdev=tpm",
    }
}

/// Failure modes for [`Invocation::new`] + [`build_argv`].
#[derive(Debug, Error)]
pub enum InvocationError {
    /// The USB-stick path doesn't exist or can't be canonicalized.
    #[error("stick {path} not found or inaccessible: {kind}")]
    StickNotFound {
        /// The path the operator passed.
        path: PathBuf,
        /// Underlying `io::Error` message — Display form so OS-level
        /// detail (e.g. "No such file or directory (os error 2)")
        /// surfaces to the operator instead of the bare `ErrorKind`
        /// name.
        kind: String,
    },

    /// The stick path violates an argv invariant (e.g. contains NUL).
    #[error("stick {path} is invalid: {reason}")]
    StickPathInvalid {
        /// The offending path.
        path: PathBuf,
        /// Human-readable reason.
        reason: &'static str,
    },

    /// Work-dir parent couldn't be created for the VARS copy.
    #[error("work dir {path} inaccessible: {kind}")]
    WorkDirInaccessible {
        /// The path that couldn't be created.
        path: PathBuf,
        /// Underlying `io::Error` message — Display form so OS-level
        /// detail (e.g. "No such file or directory (os error 2)")
        /// surfaces to the operator instead of the bare `ErrorKind`
        /// name.
        kind: String,
    },

    /// Copying the `OVMF_VARS` template into the work dir failed.
    #[error("copying `OVMF_VARS` from {from} to {to} failed: {kind}")]
    VarsCopyFailed {
        /// Source template.
        from: PathBuf,
        /// Destination per-run copy.
        to: PathBuf,
        /// Underlying `io::Error` message — Display form so OS-level
        /// detail (e.g. "No such file or directory (os error 2)")
        /// surfaces to the operator instead of the bare `ErrorKind`
        /// name.
        kind: String,
    },

    /// The per-run `OVMF_VARS` copy resolved (after `fs::canonicalize`)
    /// to a path outside the canonicalized work root. A pre-existing
    /// symlink at the destination is the most common cause; we refuse
    /// to hand QEMU a write-target that escaped the run's sandbox.
    #[error("`OVMF_VARS` copy {vars_copy} escaped work root {work_root}")]
    VarsCopyEscapedRoot {
        /// Canonicalized (resolved) path the copy ended up at.
        vars_copy: PathBuf,
        /// Canonicalized work-root the copy was supposed to live under.
        work_root: PathBuf,
    },

    /// OVMF resolution failed (underlying error comes from
    /// [`crate::ovmf::OvmfError`]).
    #[error(transparent)]
    Ovmf(#[from] OvmfError),

    /// SMBIOS synthesis failed (underlying error comes from
    /// [`crate::smbios::SmbiosError`]).
    #[error(transparent)]
    Smbios(#[from] SmbiosError),
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::persona::{Dmi, Kernel, OvmfVariant, SecureBoot, Source, SourceKind, Tpm};

    fn tpm20_persona() -> Persona {
        Persona {
            schema_version: 1,
            id: "test".into(),
            vendor: "QEMU".into(),
            display_name: "test".into(),
            year: None,
            source: Source {
                kind: SourceKind::VendorDocs,
                ref_: "test".into(),
                captured_at: None,
            },
            dmi: Dmi {
                sys_vendor: "QEMU".into(),
                product_name: "Standard PC".into(),
                product_version: None,
                bios_vendor: "EDK II".into(),
                bios_version: "edk2-stable".into(),
                bios_date: "01/01/2024".into(),
                board_name: None,
                chassis_type: None,
            },
            secure_boot: SecureBoot {
                ovmf_variant: OvmfVariant::MsEnrolled,
                custom_keyring: None,
            },
            tpm: Tpm {
                version: TpmVersion::Tpm20,
                manufacturer: None,
                firmware_version: None,
            },
            kernel: Kernel::default(),
            quirks: Vec::new(),
            scenarios: std::collections::BTreeMap::new(),
        }
    }

    fn tpm12_persona() -> Persona {
        let mut p = tpm20_persona();
        p.tpm.version = TpmVersion::Tpm12;
        p
    }

    fn no_tpm_persona() -> Persona {
        let mut p = tpm20_persona();
        p.tpm.version = TpmVersion::None;
        p
    }

    fn fake_swtpm(version: TpmVersion, work: &Path) -> SwtpmInstance {
        let spec = crate::swtpm::SwtpmSpec::derive("test-run", work, version);
        if matches!(version, TpmVersion::None) {
            // NoTpm variant — no subprocess.
            return crate::swtpm::SwtpmInstance::NoTpm { spec };
        }
        // Use sleep as a swtpm stand-in so the socket path is reachable.
        crate::swtpm::SwtpmInstance::spawn_with_binary(&spec, "sleep").unwrap()
    }

    #[test]
    fn argv_for_tpm20_persona_emits_crb_device() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());
        let argv = build_argv(
            &tpm20_persona(),
            Path::new("/fake/OVMF_CODE.fd"),
            Path::new("/fake/OVMF_VARS.fd"),
            Path::new("/fake/stick.img"),
            &swtpm,
        )
        .unwrap();
        assert!(argv.iter().any(|a| a == "tpm-crb,tpmdev=tpm"));
        assert!(argv.iter().any(|a| a.contains("chrtpm,path=")));
    }

    #[test]
    fn argv_for_tpm12_persona_emits_tis_device() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm12, tmp.path());
        let argv = build_argv(
            &tpm12_persona(),
            Path::new("/fake/OVMF_CODE.fd"),
            Path::new("/fake/OVMF_VARS.fd"),
            Path::new("/fake/stick.img"),
            &swtpm,
        )
        .unwrap();
        assert!(argv.iter().any(|a| a == "tpm-tis,tpmdev=tpm"));
    }

    #[test]
    fn argv_for_no_tpm_persona_omits_tpm_wiring() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::None, tmp.path());
        let argv = build_argv(
            &no_tpm_persona(),
            Path::new("/fake/OVMF_CODE.fd"),
            Path::new("/fake/OVMF_VARS.fd"),
            Path::new("/fake/stick.img"),
            &swtpm,
        )
        .unwrap();
        assert!(
            !argv.iter().any(|a| a.starts_with("tpm-")),
            "no TPM device should be present; got {argv:?}"
        );
        assert!(
            !argv.iter().any(|a| a.contains("chrtpm")),
            "no TPM chardev should be present"
        );
        assert!(!argv.iter().any(|a| a == "-tpmdev"));
    }

    #[test]
    fn argv_contains_smm_on_machine() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());
        let argv = build_argv(
            &tpm20_persona(),
            Path::new("/fake/OVMF_CODE.fd"),
            Path::new("/fake/OVMF_VARS.fd"),
            Path::new("/fake/stick.img"),
            &swtpm,
        )
        .unwrap();
        let m = argv
            .iter()
            .zip(argv.iter().skip(1))
            .find(|(a, _)| *a == "-machine")
            .map(|(_, v)| v.as_str())
            .expect("-machine arg");
        assert!(m.contains("smm=on"), "SMM required for Secure Boot");
    }

    #[test]
    fn argv_wires_pflash_code_readonly_and_vars_writable() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());
        let argv = build_argv(
            &tpm20_persona(),
            Path::new("/firmware/OVMF_CODE.fd"),
            Path::new("/work/OVMF_VARS.fd"),
            Path::new("/fake/stick.img"),
            &swtpm,
        )
        .unwrap();
        let joined = argv.join(" ");
        assert!(
            joined.contains("unit=0,readonly=on,file=/firmware/OVMF_CODE.fd"),
            "`OVMF_CODE` must be readonly on pflash unit 0"
        );
        assert!(
            joined.contains("unit=1,file=/work/OVMF_VARS.fd"),
            "`OVMF_VARS` must be writable on pflash unit 1"
        );
        assert!(
            !joined.contains("unit=1,readonly=on"),
            "`OVMF_VARS` must NOT be readonly (the VM writes SB state here)"
        );
    }

    #[test]
    fn argv_includes_stick_as_usb_storage() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());
        let argv = build_argv(
            &tpm20_persona(),
            Path::new("/fake/OVMF_CODE.fd"),
            Path::new("/fake/OVMF_VARS.fd"),
            Path::new("/flash/aegis-boot.img"),
            &swtpm,
        )
        .unwrap();
        let joined = argv.join(" ");
        assert!(joined.contains("file=/flash/aegis-boot.img,format=raw,if=none,id=stick"));
        assert!(
            joined.contains("qemu-xhci,id=xhci"),
            "q35 needs explicit USB controller"
        );
        assert!(joined.contains("usb-storage,bus=xhci.0,drive=stick"));
    }

    #[test]
    fn argv_passes_dmi_through_smbios_blocks() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());
        let argv = build_argv(
            &tpm20_persona(),
            Path::new("/fake/OVMF_CODE.fd"),
            Path::new("/fake/OVMF_VARS.fd"),
            Path::new("/fake/stick.img"),
            &swtpm,
        )
        .unwrap();
        let joined = argv.join(" ");
        assert!(joined.contains("type=0,vendor=EDK II"));
        assert!(joined.contains("type=1,manufacturer=QEMU,product=Standard PC"));
    }

    #[test]
    fn argv_is_headless() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::None, tmp.path());
        let argv = build_argv(
            &no_tpm_persona(),
            Path::new("/fake/OVMF_CODE.fd"),
            Path::new("/fake/OVMF_VARS.fd"),
            Path::new("/fake/stick.img"),
            &swtpm,
        )
        .unwrap();
        assert!(argv.iter().any(|a| a == "-nographic"));
        assert!(argv.iter().any(|a| a == "mon:stdio"));
    }

    #[test]
    fn invocation_new_rejects_nul_in_stick_path() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());
        // Construct a PathBuf with an embedded NUL via OsString bytes on Unix.
        #[cfg(unix)]
        {
            use std::ffi::OsString;
            use std::os::unix::ffi::OsStringExt as _;
            let bytes = b"/tmp/bad\0stick.img".to_vec();
            let stick = PathBuf::from(OsString::from_vec(bytes));
            let err = Invocation::new(&tpm20_persona(), &stick, tmp.path(), tmp.path(), &swtpm)
                .unwrap_err();
            assert!(
                matches!(err, InvocationError::StickPathInvalid { .. }),
                "expected StickPathInvalid, got {err:?}"
            );
        }
    }

    #[test]
    fn invocation_new_surfaces_ovmf_missing_as_named_error() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());
        let stick = tmp.path().join("stick.img");
        fs::write(&stick, b"fake stick").unwrap();
        // firmware_root is empty — no `OVMF_CODE` there.
        let err =
            Invocation::new(&tpm20_persona(), &stick, tmp.path(), tmp.path(), &swtpm).unwrap_err();
        assert!(
            matches!(
                err,
                InvocationError::Ovmf(OvmfError::OvmfCodeMissing { .. })
            ),
            "expected Ovmf(OvmfCodeMissing), got {err:?}"
        );
    }

    #[test]
    fn invocation_new_happy_path_copies_vars_template() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());

        // Build a fake Debian firmware root.
        let fw = tmp.path().join("fw");
        fs::create_dir_all(&fw).unwrap();
        fs::write(fw.join("OVMF_CODE_4M.secboot.fd"), b"code").unwrap();
        fs::write(fw.join("OVMF_VARS_4M.ms.fd"), b"vars template").unwrap();

        // Stick.
        let stick = tmp.path().join("stick.img");
        fs::write(&stick, b"fake stick").unwrap();

        let work = tmp.path().join("work");
        fs::create_dir_all(&work).unwrap();

        let inv = Invocation::new(&tpm20_persona(), &stick, &work, &fw, &swtpm).unwrap();

        // Per-run VARS copy should now exist + contain the template bytes.
        let vars = inv.vars_copy();
        assert!(vars.exists());
        let contents = fs::read(vars).unwrap();
        assert_eq!(contents, b"vars template");

        // The argv should reference the copy, not the template.
        let joined = inv.argv().join(" ");
        assert!(joined.contains(&vars.display().to_string()));
    }

    #[test]
    fn build_returns_qemu_command() {
        let tmp = tempfile::tempdir().unwrap();
        let swtpm = fake_swtpm(TpmVersion::None, tmp.path());
        let argv = build_argv(
            &no_tpm_persona(),
            Path::new("/fake/OVMF_CODE.fd"),
            Path::new("/fake/OVMF_VARS.fd"),
            Path::new("/fake/stick.img"),
            &swtpm,
        )
        .unwrap();
        let inv = Invocation {
            argv,
            vars_copy: PathBuf::from("/fake/OVMF_VARS.fd"),
        };
        let cmd = inv.build();
        assert_eq!(cmd.get_program().to_string_lossy(), "qemu-system-x86_64");
    }

    /// E2.7 path-boundary: a pre-existing symlink at the `OVMF_VARS`
    /// destination, pointing OUTSIDE the work root, must be rejected.
    /// `fs::copy` would otherwise follow the symlink and overwrite the
    /// target outside the run's sandbox.
    #[test]
    #[cfg(unix)]
    fn invocation_new_rejects_vars_copy_symlink_escape() {
        let tmp = tempfile::tempdir().unwrap();

        // Build a fake Debian firmware root.
        let fw = tmp.path().join("fw");
        fs::create_dir_all(&fw).unwrap();
        fs::write(fw.join("OVMF_CODE_4M.secboot.fd"), b"code").unwrap();
        fs::write(fw.join("OVMF_VARS_4M.ms.fd"), b"vars template").unwrap();

        let stick = tmp.path().join("stick.img");
        fs::write(&stick, b"fake stick").unwrap();

        // Pre-place a symlink at <work>/OVMF_VARS.fd that points
        // outside work_dir. fs::copy would otherwise follow it.
        let work = tmp.path().join("work");
        fs::create_dir_all(&work).unwrap();
        let escape_target = tmp.path().join("escape-target.fd");
        fs::write(&escape_target, b"would-be victim").unwrap();
        std::os::unix::fs::symlink(&escape_target, work.join("OVMF_VARS.fd")).unwrap();

        let swtpm = fake_swtpm(TpmVersion::None, tmp.path());
        let mut p = tpm20_persona();
        p.tpm.version = TpmVersion::None;

        let err = Invocation::new(&p, &stick, &work, &fw, &swtpm).unwrap_err();
        assert!(
            matches!(err, InvocationError::VarsCopyEscapedRoot { .. }),
            "expected VarsCopyEscapedRoot, got {err:?}"
        );

        // The would-be-victim file SHOULD have been overwritten by
        // fs::copy (that's the attack); the test's value is asserting
        // the boundary check FAILS the run so QEMU is never spawned
        // against the leaked path. Document the residual concern as
        // a known limitation: file::copy follows the symlink before we
        // can intercept it; defense is "refuse to proceed", not
        // "prevent write." Future hardening can switch to
        // open(O_NOFOLLOW) + write directly.
    }

    #[test]
    fn invocation_new_canonicalizes_vars_copy_through_relative_work_dir() {
        // A relative work_dir like "work/run-1" should canonicalize to
        // an absolute path; the resulting vars_copy must be absolute
        // and under the canonical work root.
        let tmp = tempfile::tempdir().unwrap();
        let fw = tmp.path().join("fw");
        fs::create_dir_all(&fw).unwrap();
        fs::write(fw.join("OVMF_CODE_4M.secboot.fd"), b"code").unwrap();
        fs::write(fw.join("OVMF_VARS_4M.ms.fd"), b"vars template").unwrap();

        let stick = tmp.path().join("stick.img");
        fs::write(&stick, b"fake stick").unwrap();

        let work = tmp.path().join("work");
        fs::create_dir_all(&work).unwrap();

        let swtpm = fake_swtpm(TpmVersion::Tpm20, tmp.path());
        let inv = Invocation::new(&tpm20_persona(), &stick, &work, &fw, &swtpm).unwrap();

        // Canonicalized path: must be absolute + under canonical work root.
        let canonical_work = fs::canonicalize(&work).unwrap();
        assert!(inv.vars_copy().is_absolute());
        assert!(
            inv.vars_copy().starts_with(&canonical_work),
            "vars_copy {} should start with canonical work root {}",
            inv.vars_copy().display(),
            canonical_work.display()
        );
    }
}