cellos-host-firecracker 0.5.1

Firecracker microVM backend for CellOS — jailer integration, warm pool with snapshot/restore, KVM nested-virtualisation aware.
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
//! FC-11 — Rootfs mounts at `/` before init starts.
//!
//! Acceptance gate (from `Plans/firecracker-release-readiness.md` line 55):
//!
//! > e2e workload reads `/proc/self/mountinfo`, asserts root mount source is
//! > `/dev/vda` (or scratch overlay device when `scratch_dir` set), and the
//! > mount line is present before any cellos-init log line in the captured
//! > serial log.
//!
//! # Test layout
//!
//! Two tiers, both in this file (per FC-11 doctrine — helper is local to the
//! test, not exported from `src/`):
//!
//!   1. Pure-Rust unit tier (always-on): a `validate_root_mount_source`
//!      parser plus a serial-log ordering check. These compile and run on
//!      every CI leg, including hosts without a Firecracker binary.
//!
//!   2. Linux integration tier (`#[cfg(target_os = "linux")] #[ignore = ...]`)
//!      that opt-in reads a captured `/proc/self/mountinfo` from inside the
//!      guest workload (path passed via `CELLOS_FIRECRACKER_FC11_MOUNTINFO_PATH`)
//!      and asserts the root device is in the FC-11 acceptance set
//!      `{ /dev/vda, /dev/root, /dev/vdb }`. `/dev/vdb` is the scratch
//!      overlay device when `scratch_dir` is configured (see
//!      `crates/cellos-host-firecracker/src/lib.rs` L1215: "Optional writable
//!      scratch drive (attached as /dev/vdb in the guest)").
//!
//! # Why these helpers live in the test file (not src/)
//!
//! The supervisor never parses guest mountinfo on the host side — the FC-11
//! gate is exclusively a CI assertion against captured artifacts. Promoting
//! the parser into `src/` would expand the public surface of the host crate
//! for no production caller. Keeping it test-local matches the FC-14
//! `extract_capbnd` / FC-19 vsock-ack precedent in this directory.

use std::fmt;

/// Errors surfaced by [`validate_root_mount_source`]. Each variant maps to a
/// distinct FC-11 failure mode so the e2e harness can attribute regressions.
#[derive(Debug, PartialEq, Eq)]
pub enum RootMountError {
    /// `/proc/self/mountinfo` did not contain a line whose mount-point is `/`.
    NoRootEntry,
    /// A root line existed but was missing the `<fs-type> <source>` post-`-`
    /// half — kernel format violation, treat as hard fail.
    MalformedLine(String),
    /// Root mount source is on the host-leak deny-list (overlay / 9p / etc).
    /// These would indicate the guest is reading a bind-mount of host state
    /// rather than its own virtio-blk image.
    DeniedSource {
        actual: String,
        reason: &'static str,
    },
    /// Root mount source did not match the expected device and was not on the
    /// accepted-alias list (`/dev/root` is the kernel's symbolic alias for
    /// `/dev/vda` when booted via `root=/dev/vda`).
    UnexpectedSource { actual: String, expected: String },
}

impl fmt::Display for RootMountError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoRootEntry => write!(
                f,
                "FC-11 violation: no `/` mount entry in /proc/self/mountinfo"
            ),
            Self::MalformedLine(line) => write!(
                f,
                "FC-11 violation: malformed mountinfo line for `/`: {line:?}"
            ),
            Self::DeniedSource { actual, reason } => write!(
                f,
                "FC-11 violation: root mount source {actual:?} is on deny-list ({reason}) — \
                 indicates host filesystem leak into guest"
            ),
            Self::UnexpectedSource { actual, expected } => write!(
                f,
                "FC-11 violation: root mount source is {actual:?}, expected {expected:?} \
                 (or `/dev/root` alias)"
            ),
        }
    }
}

impl std::error::Error for RootMountError {}

/// Source strings that — if observed as the root mount source — definitively
/// prove a host filesystem leak into the guest. These are checked *before*
/// the expected-device match so a misconfigured deny-list source can never
/// silently pass even if it accidentally equals `expected_device`.
const DENIED_SOURCES: &[(&str, &str)] = &[
    ("overlay", "host overlay leak"),
    ("9p", "host bind leak"),
    ("virtiofs", "host bind leak"),
    ("rootfs", "in-memory host rootfs leak"),
];

/// Validate the root mount source from a `/proc/self/mountinfo` blob.
///
/// `expected_device` is the device path the supervisor configured for the
/// guest's root drive — `/dev/vda` in the default case, `/dev/vdb` when
/// `scratch_dir` is set and the cell is using the writable overlay as root
/// (see `lib.rs` L1215). The kernel's `/dev/root` symlink is accepted as an
/// alias for `/dev/vda` because some kernels report mountinfo with the
/// symbolic name even when booted via `root=/dev/vda`.
pub fn validate_root_mount_source(
    mountinfo: &str,
    expected_device: &str,
) -> Result<(), RootMountError> {
    let root_line = find_root_line(mountinfo).ok_or(RootMountError::NoRootEntry)?;
    let (fstype, source) = parse_mount_fstype_and_source(root_line)
        .ok_or_else(|| RootMountError::MalformedLine(root_line.to_string()))?;

    // Check both fs-type and source: overlay/rootfs use identical values for
    // both fields, but 9p and virtiofs have arbitrary source names (the share
    // name). Either matching the deny-list is sufficient to hard-fail.
    // Report `actual` as whichever matched so error messages are clear.
    for (denied, reason) in DENIED_SOURCES {
        if fstype == *denied {
            return Err(RootMountError::DeniedSource {
                actual: fstype.to_string(),
                reason,
            });
        }
        if source == *denied {
            return Err(RootMountError::DeniedSource {
                actual: source.to_string(),
                reason,
            });
        }
    }

    if source == expected_device {
        return Ok(());
    }
    // /dev/root is the kernel's symbolic alias for the root virtio-blk device
    // when booted with `root=/dev/vda`. Some kernels report the alias in
    // mountinfo; both forms are FC-11-acceptable for the rootfs case.
    if expected_device == "/dev/vda" && source == "/dev/root" {
        return Ok(());
    }

    Err(RootMountError::UnexpectedSource {
        actual: source.to_string(),
        expected: expected_device.to_string(),
    })
}

/// Parse both the fs-type and source from a `/proc/self/mountinfo` line.
fn parse_mount_fstype_and_source(line: &str) -> Option<(&str, &str)> {
    let mut tokens = line.split_whitespace();
    for token in tokens.by_ref() {
        if token == "-" {
            break;
        }
    }
    let fstype = tokens.next()?;
    let source = tokens.next()?;
    Some((fstype, source))
}

/// Return the first mountinfo line whose mount-point (field 5, 1-indexed) is
/// exactly `/`. Returns `None` when no such line exists.
fn find_root_line(mountinfo: &str) -> Option<&str> {
    mountinfo.lines().find(|line| {
        // mountinfo format: "<id> <pid> <maj:min> <root> <mount-point> ..."
        // The mount-point is the 5th whitespace-separated field.
        let mut fields = line.split_whitespace();
        let mount_point = fields.nth(4);
        mount_point == Some("/")
    })
}

/// Parse the mount source out of a `/proc/self/mountinfo` line. The format,
/// per `proc(5)`, is:
///
/// ```text
/// <id> <pid> <maj:min> <root> <mount-point> <opts> <opt-fields>... - <fs-type> <source> <super-opts>
/// ```
///
/// The post-separator section starts after the literal `-` token; the second
/// token in that section is the mount source.
#[allow(dead_code)]
fn parse_mount_source(line: &str) -> Option<&str> {
    let mut tokens = line.split_whitespace();
    // Walk forward to the standalone "-" separator.
    for token in tokens.by_ref() {
        if token == "-" {
            break;
        }
    }
    // After "-": <fs-type> <source> <super-opts>.
    let _fs_type = tokens.next()?;
    tokens.next()
}

/// Locate the byte offset of the root-mount line in a captured serial log.
/// Returns `None` when no line in `serial_log` carries the mount marker the
/// guest emits during early boot. The marker we look for is conservative —
/// any line that mentions both `/` as a mount-point and the root device.
fn find_root_mount_log_offset(serial_log: &str, root_device: &str) -> Option<usize> {
    let mut byte_offset = 0usize;
    for line in serial_log.split_inclusive('\n') {
        // The kernel typically logs something like:
        //   "EXT4-fs (vda): mounted filesystem ... on /"
        // and then later:
        //   "VFS: Mounted root (ext4 filesystem) readonly on device 254:0."
        // We accept any line that names the root device or the bare `vda`
        // basename as evidence the rootfs mount happened.
        let basename = root_device.trim_start_matches("/dev/");
        if (line.contains(root_device) || line.contains(basename))
            && (line.contains("Mounted root")
                || line.contains("mounted filesystem")
                || line.contains(" on /"))
        {
            return Some(byte_offset);
        }
        byte_offset += line.len();
    }
    None
}

/// Locate the byte offset of the first `cellos-init` log line in a captured
/// serial log. `None` when init never logged (which would itself be a
/// separate failure caught by FC-12).
fn find_first_cellos_init_log_offset(serial_log: &str) -> Option<usize> {
    let mut byte_offset = 0usize;
    for line in serial_log.split_inclusive('\n') {
        if line.contains("cellos-init") {
            return Some(byte_offset);
        }
        byte_offset += line.len();
    }
    None
}

/// FC-11 ordering assertion: the rootfs mount line MUST appear in the serial
/// log before the first `cellos-init` line. If init logs first, the rootfs
/// mount happened post-init (or not at all) — that is a hard FC-11 fail.
pub fn assert_mount_line_before_init(serial_log: &str, root_device: &str) -> Result<(), String> {
    let mount_at = find_root_mount_log_offset(serial_log, root_device).ok_or_else(|| {
        format!(
            "FC-11 violation: no rootfs mount line for {root_device} in serial log \
             — kernel never reported the root mount"
        )
    })?;
    let init_at = find_first_cellos_init_log_offset(serial_log).ok_or_else(|| {
        "FC-11 ordering check inconclusive: no `cellos-init` line in serial log \
         (separate FC-12 failure — init did not log)"
            .to_string()
    })?;
    if mount_at >= init_at {
        return Err(format!(
            "FC-11 violation: rootfs mount line at byte {mount_at} appears at-or-after \
             first `cellos-init` log line at byte {init_at} — root mount must precede init"
        ));
    }
    Ok(())
}

// ── Unit tier ──────────────────────────────────────────────────────────────

/// Mountinfo line as the kernel emits it for the root mount on a stock
/// Firecracker boot with `root=/dev/vda rw`.
fn fixture_root_line(source: &str) -> String {
    format!(
        "29 1 254:0 / / rw,relatime shared:1 - ext4 {source} rw,errors=remount-ro\n\
         30 29 0:5 / /dev rw,nosuid,relatime shared:2 - devtmpfs devtmpfs rw,size=65536k\n",
        source = source
    )
}

#[test]
fn fc11_root_mount_source_dev_vda_passes() {
    let mountinfo = fixture_root_line("/dev/vda");
    validate_root_mount_source(&mountinfo, "/dev/vda")
        .expect("FC-11 must accept /dev/vda as root source");
}

#[test]
fn fc11_root_mount_source_dev_root_also_accepted() {
    // Some kernels report the symbolic alias even when booted via /dev/vda.
    let mountinfo = fixture_root_line("/dev/root");
    validate_root_mount_source(&mountinfo, "/dev/vda")
        .expect("FC-11 must treat /dev/root as alias for /dev/vda");
}

#[test]
fn fc11_root_mount_source_scratch_overlay_passes() {
    // When scratch_dir is set, the writable overlay is attached as /dev/vdb
    // (see crates/cellos-host-firecracker/src/lib.rs L1215). The supervisor
    // passes /dev/vdb as the expected device in that configuration.
    let mountinfo = fixture_root_line("/dev/vdb");
    validate_root_mount_source(&mountinfo, "/dev/vdb")
        .expect("FC-11 must accept /dev/vdb when scratch overlay is the root device");
}

#[test]
fn fc11_root_mount_source_overlay_fs_rejected() {
    // A bare `overlay` source on the root mount means the guest is reading
    // a host overlay — the exact host-leak FC-11 is built to detect.
    let mountinfo = fixture_root_line("overlay");
    let err = validate_root_mount_source(&mountinfo, "/dev/vda")
        .expect_err("overlay source on / must fail FC-11");
    match err {
        RootMountError::DeniedSource { actual, reason } => {
            assert_eq!(actual, "overlay");
            assert!(
                reason.contains("overlay"),
                "deny reason must name the leak class; got: {reason}"
            );
        }
        other => panic!("expected DeniedSource, got {other:?}"),
    }
}

#[test]
fn fc11_root_mount_source_9p_rejected() {
    // 9p on / is the canonical "host bind leaked into guest" signature —
    // it is what `firecracker --rootfs <hostdir>` would produce if someone
    // bypassed the virtio-blk path. Must hard-fail.
    let mut mountinfo = String::new();
    mountinfo.push_str("29 1 0:21 / / rw,relatime shared:1 - 9p host_share rw,trans=virtio\n");
    let err = validate_root_mount_source(&mountinfo, "/dev/vda")
        .expect_err("9p source on / must fail FC-11");
    assert!(
        matches!(err, RootMountError::DeniedSource { .. }),
        "expected DeniedSource for 9p; got {err:?}"
    );
    let msg = format!("{err}");
    assert!(
        msg.contains("9p"),
        "error must echo the offending source; got: {msg}"
    );
    assert!(
        msg.contains("host bind leak"),
        "error must classify 9p as host bind leak; got: {msg}"
    );
}

#[test]
fn fc11_root_mount_line_present_before_init_log() {
    // Stub a serial log in canonical kernel-then-init order. The mount line
    // must precede the first `cellos-init` line; the helper must agree.
    let serial_log = "\
[    0.000000] Linux version 6.1.0-cellos\n\
[    0.123456] Command line: console=ttyS0 root=/dev/vda rw\n\
[    0.234567] EXT4-fs (vda): mounted filesystem with ordered data mode on /\n\
[    0.345678] VFS: Mounted root (ext4 filesystem) readonly on device 254:0.\n\
[    0.456789] Run /sbin/init as init process\n\
[    0.567890] cellos-init: starting (pid=1)\n\
[    0.678901] cellos-init: drop_capabilities() complete\n";
    assert_mount_line_before_init(serial_log, "/dev/vda")
        .expect("mount line precedes cellos-init — FC-11 ordering must pass");

    // And the parser must agree the mountinfo half is also clean.
    let mountinfo = fixture_root_line("/dev/vda");
    validate_root_mount_source(&mountinfo, "/dev/vda")
        .expect("paired mountinfo must validate alongside ordering");
}

#[test]
fn fc11_root_mount_line_after_init_log_is_rejected() {
    // Inverse case: if the rootfs mount log is emitted only after cellos-init
    // has already started logging, FC-11 ordering must reject. Guards against
    // a regression where init starts before the kernel finishes mounting `/`.
    let serial_log = "\
[    0.100000] Linux version 6.1.0-cellos\n\
[    0.200000] cellos-init: starting (pid=1)\n\
[    0.300000] EXT4-fs (vda): mounted filesystem with ordered data mode on /\n";
    let err = assert_mount_line_before_init(serial_log, "/dev/vda")
        .expect_err("init-before-mount ordering must be rejected");
    assert!(
        err.contains("at-or-after"),
        "error must explain ordering; got: {err}"
    );
}

#[test]
fn fc11_no_root_entry_is_error() {
    // mountinfo with mounts but no `/` line: mid-boot snapshot or kernel bug.
    let mountinfo = "30 29 0:5 / /dev rw,nosuid,relatime shared:2 - devtmpfs devtmpfs rw\n";
    let err =
        validate_root_mount_source(mountinfo, "/dev/vda").expect_err("missing / entry must fail");
    assert_eq!(err, RootMountError::NoRootEntry);
}

#[test]
fn fc11_unexpected_source_is_distinguishable_from_deny_list() {
    // A source that is neither expected nor on the deny-list (e.g. an
    // unexpected device path) must surface as UnexpectedSource so the e2e
    // harness can distinguish "wrong device" from "host leak".
    let mountinfo = fixture_root_line("/dev/vdc");
    let err = validate_root_mount_source(&mountinfo, "/dev/vda")
        .expect_err("/dev/vdc when /dev/vda expected must fail");
    match err {
        RootMountError::UnexpectedSource { actual, expected } => {
            assert_eq!(actual, "/dev/vdc");
            assert_eq!(expected, "/dev/vda");
        }
        other => panic!("expected UnexpectedSource, got {other:?}"),
    }
}

// ── Linux integration tier ─────────────────────────────────────────────────
//
// Strict acceptance: read a captured `/proc/self/mountinfo` file produced by
// the firecracker-e2e workflow from inside the guest, and assert the root
// device is in the FC-11 acceptance set. Gated by:
//
//   * `#[cfg(target_os = "linux")]` — the parent crate is unix-only, so this
//     test does not even compile on the Windows authoring host.
//   * `#[ignore]` — must be opted into via `cargo test -- --ignored`, since
//     the assertion requires the e2e capture artifact.
//   * `CELLOS_FIRECRACKER_FC11_MOUNTINFO_PATH` env var — points at the
//     captured mountinfo file. Absent path → the test panics, signalling
//     misconfigured e2e harness rather than silently passing.

/// FC-11 e2e: validate a captured guest mountinfo against the acceptance
/// set `{ /dev/vda, /dev/root, /dev/vdb }`. `/dev/vdb` covers the
/// `scratch_dir`-enabled configuration where the writable overlay is the
/// root drive.
#[cfg(target_os = "linux")]
#[test]
#[ignore = "requires running guest + serial.log capture"]
fn fc11_root_mount_source_e2e_from_captured_mountinfo() {
    let path = std::env::var("CELLOS_FIRECRACKER_FC11_MOUNTINFO_PATH").expect(
        "CELLOS_FIRECRACKER_FC11_MOUNTINFO_PATH must point to a captured \
         /proc/self/mountinfo file from inside the guest workload",
    );
    let mountinfo = std::fs::read_to_string(&path).unwrap_or_else(|e| {
        panic!(
            "failed to read captured mountinfo at {path}: {e} \
             (expected the e2e workflow to drop the capture before invoking this test)"
        )
    });

    // Try every device in the FC-11 acceptance set; pass if any matches.
    // Order matters only for error reporting — try /dev/vda first since that
    // is the default-config root device.
    let candidates = ["/dev/vda", "/dev/vdb"];
    let mut last_err: Option<RootMountError> = None;
    for expected in candidates {
        match validate_root_mount_source(&mountinfo, expected) {
            Ok(()) => return,
            Err(e @ RootMountError::DeniedSource { .. }) => {
                // A deny-list hit is unconditional — no other expected device
                // could rescue it, so fail fast with the precise reason.
                panic!(
                    "FC-11 acceptance failed for capture at {path}: {e}\n\
                     ----- captured mountinfo -----\n{mountinfo}\n----- end -----"
                );
            }
            Err(other) => last_err = Some(other),
        }
    }
    panic!(
        "FC-11 acceptance failed for capture at {path}: root device not in \
         acceptance set {{/dev/vda, /dev/root, /dev/vdb}}; last error: {:?}\n\
         ----- captured mountinfo -----\n{mountinfo}\n----- end -----",
        last_err
    );
}