boxlite 0.10.1

Embeddable virtual machine runtime for secure, isolated code execution
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! Archive operations for box export and import.
//!
//! Handles `.boxlite` archive files: zstd-compressed tarballs containing
//! disk images and a JSON manifest.

use std::io::Write;
use std::path::Path;

use boxlite_shared::errors::{BoxliteError, BoxliteResult};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::disk::constants::filenames as disk_filenames;

/// Manifest filename inside the archive.
pub(crate) const MANIFEST_FILENAME: &str = "manifest.json";

/// Archive format version for configurations a v3 importer reads correctly.
pub(crate) const ARCHIVE_VERSION: u32 = 3;

/// First archive version that carries a custom Linux capability policy.
///
/// A pre-capability importer accepts up to v3 and would silently drop
/// `advanced.capabilities`, starting the box with wider privileges than the
/// archive asked for. Stamping v4 makes that importer refuse the archive.
pub(crate) const CAPABILITY_POLICY_ARCHIVE_VERSION: u32 = 4;

/// First archive version whose `ports` carry publication semantics.
///
/// Up to v4 an importer reused the guest port for a null `host_port` and
/// ignored `host_ip` and `protocol` entirely. It would read a v5 mapping under
/// those rules and bind the wrong port, or bind every interface where the
/// archive asked for one — so any archive that carries ports at all is stamped
/// v5, and the importer canonicalizes anything below it.
pub(crate) const PUBLISHED_PORTS_ARCHIVE_VERSION: u32 = 5;

/// Maximum archive version this build can import.
pub(crate) const MAX_SUPPORTED_VERSION: u32 = PUBLISHED_PORTS_ARCHIVE_VERSION;

/// Pick the archive format an exported box needs.
///
/// Any explicit policy — including an explicitly empty one — is stamped v4:
/// `capabilities()` returning `Some` means the caller configured something,
/// which a pre-capability importer has no way to represent and must refuse
/// rather than silently drop. Only `None` (the caller never touched the
/// field) is indistinguishable from what a v3 importer already does.
pub(crate) fn archive_version_for_options(options: &crate::runtime::options::BoxOptions) -> u32 {
    if !options.ports.is_empty() {
        PUBLISHED_PORTS_ARCHIVE_VERSION
    } else if options.advanced.capabilities().is_none() {
        ARCHIVE_VERSION
    } else {
        CAPABILITY_POLICY_ARCHIVE_VERSION
    }
}

/// Archive manifest stored as `manifest.json` inside exported archives.
///
/// v1: plain tar, no checksums
/// v2: tar.zst with checksums
/// v3: adds `box_options` for full configuration preservation
/// v4: `box_options.advanced` carries a custom capability policy
/// v5: `ports` carry publication semantics (automatic host port, bind IP)
#[derive(Debug, Serialize, Deserialize)]
pub struct ArchiveManifest {
    /// Archive format version (1 through 5).
    pub version: u32,
    /// Original box name (optional, may be renamed on import).
    pub box_name: Option<String>,
    /// Image reference used to create the box (e.g. "alpine:latest").
    pub image: String,
    /// Full box configuration (v3+). `None` for v1/v2 archives.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub box_options: Option<crate::runtime::options::BoxOptions>,
    /// SHA-256 checksum of the guest rootfs disk.
    ///
    /// Always empty: the guest rootfs is no longer bundled in archives (it ships
    /// as a shared base image). Kept in the schema so pre-minimal-rootfs
    /// importers, which require the field, can deserialize the manifest instead
    /// of failing with "missing field `guest_disk_checksum`".
    pub guest_disk_checksum: String,
    /// SHA-256 checksum of the container disk.
    pub container_disk_checksum: String,
    /// Timestamp when the archive was created.
    pub exported_at: String,
}

// ── Build ───────────────────────────────────────────────────────────────

/// Build a zstd-compressed tar archive.
pub(crate) fn build_zstd_tar_archive(
    output_path: &Path,
    manifest_path: &Path,
    container_disk: &Path,
    compression_level: i32,
) -> BoxliteResult<()> {
    let file = std::fs::File::create(output_path).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to create archive file {}: {}",
            output_path.display(),
            e
        ))
    })?;

    let encoder = zstd::Encoder::new(file, compression_level)
        .map_err(|e| BoxliteError::Storage(format!("Failed to create zstd encoder: {}", e)))?;

    let mut builder = tar::Builder::new(encoder);
    append_archive_files(&mut builder, manifest_path, container_disk)?;

    let encoder = builder
        .into_inner()
        .map_err(|e| BoxliteError::Storage(format!("Failed to finalize tar: {}", e)))?;
    encoder
        .finish()
        .map_err(|e| BoxliteError::Storage(format!("Failed to finish zstd compression: {}", e)))?;

    Ok(())
}

fn append_archive_files<W: Write>(
    builder: &mut tar::Builder<W>,
    manifest_path: &Path,
    container_disk: &Path,
) -> BoxliteResult<()> {
    builder
        .append_path_with_name(manifest_path, MANIFEST_FILENAME)
        .map_err(|e| BoxliteError::Storage(format!("Failed to add manifest to archive: {}", e)))?;

    builder
        .append_path_with_name(container_disk, disk_filenames::CONTAINER_DISK)
        .map_err(|e| {
            BoxliteError::Storage(format!("Failed to add container disk to archive: {}", e))
        })?;

    Ok(())
}

// ── Extract ─────────────────────────────────────────────────────────────

/// Zstd magic bytes: `0x28B52FFD` (little-endian in file).
const ZSTD_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD];

/// Extract an archive, detecting format via magic bytes (zstd or plain tar).
pub(crate) fn extract_archive(archive_path: &Path, dest_dir: &Path) -> BoxliteResult<()> {
    use std::io::Read;

    let mut file = std::fs::File::open(archive_path).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to open archive {}: {}",
            archive_path.display(),
            e
        ))
    })?;

    let mut magic = [0u8; 4];
    file.read_exact(&mut magic).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to read archive header {}: {}",
            archive_path.display(),
            e
        ))
    })?;
    drop(file);

    // Re-open for extraction (tar/zstd need the file from the beginning).
    let file = std::fs::File::open(archive_path).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to reopen archive {}: {}",
            archive_path.display(),
            e
        ))
    })?;

    if magic == ZSTD_MAGIC {
        let decoder = zstd::Decoder::new(file)
            .map_err(|e| BoxliteError::Storage(format!("Failed to create zstd decoder: {}", e)))?;
        unpack_file_members(decoder, dest_dir)
    } else {
        unpack_file_members(file, dest_dir)
    }
}

/// Member types that carry their own contents rather than a reference to
/// something else.
///
/// `Regular` is the common case. `Continuous` is its rarely used contiguous
/// variant. `GNUSparse` is what `tar::Builder` emits for a file with holes —
/// which on Linux is every exported qcow2 disk, since the builder reads sparse
/// information from disk by default. All three unpack as ordinary files.
///
/// The OCI layer extractor pairs the same two types for the same reason — see
/// the `EntryType::Regular | EntryType::GNUSparse` arm in
/// `images/archive/extractor.rs`.
fn carries_file_contents(entry_type: tar::EntryType) -> bool {
    matches!(
        entry_type,
        tar::EntryType::Regular | tar::EntryType::Continuous | tar::EntryType::GNUSparse
    )
}

/// Unpack an archive, accepting only members that carry their own contents.
///
/// tar checks where a member is *written* but copies a link's target verbatim,
/// so a link member lands in `dest_dir` pointing anywhere on the host and every
/// later step — exists, checksum, the backing-file scan, the rename that makes
/// it a box's disk — follows it there. Deciding on the member's own type is the
/// only point where the archive itself, rather than whatever it resolves to, is
/// what gets judged.
///
/// This costs no compatibility: `tar::Builder` dereferences symlinks by default
/// and boxlite has never turned that off, so no export has ever produced a link
/// member. Member *names* are deliberately not filtered — archives written
/// before the guest rootfs became a shared base image carry a third member that
/// the importer ignores, and rejecting it would strand them.
fn unpack_file_members<R: std::io::Read>(reader: R, dest_dir: &Path) -> BoxliteResult<()> {
    let mut archive = tar::Archive::new(reader);
    let entries = archive
        .entries()
        .map_err(|e| BoxliteError::Storage(format!("Failed to read archive: {}", e)))?;

    for entry in entries {
        let mut entry = entry
            .map_err(|e| BoxliteError::Storage(format!("Failed to read archive member: {}", e)))?;

        let entry_type = entry.header().entry_type();
        if !carries_file_contents(entry_type) {
            let name = entry
                .path()
                .map(|path| path.display().to_string())
                .unwrap_or_else(|_| "<unreadable>".to_string());
            return Err(BoxliteError::Storage(format!(
                "Invalid archive: member '{}' is {:?}, only files are allowed",
                name, entry_type
            )));
        }

        entry
            .unpack_in(dest_dir)
            .map_err(|e| BoxliteError::Storage(format!("Failed to extract archive: {}", e)))?;
    }

    Ok(())
}

// ── File Operations ─────────────────────────────────────────────────────

/// Move a file, falling back to copy+remove if rename fails with EXDEV
/// (cross-device link error, i.e. source and destination on different filesystems).
pub(crate) fn move_file(src: &Path, dst: &Path) -> BoxliteResult<()> {
    match std::fs::rename(src, dst) {
        Ok(()) => Ok(()),
        Err(e) if e.raw_os_error() == Some(libc::EXDEV) => {
            std::fs::copy(src, dst).map_err(|e| {
                BoxliteError::Storage(format!(
                    "Failed to copy {} to {}: {}",
                    src.display(),
                    dst.display(),
                    e
                ))
            })?;
            std::fs::remove_file(src).map_err(|e| {
                BoxliteError::Storage(format!(
                    "Failed to remove source after cross-fs copy {}: {}",
                    src.display(),
                    e
                ))
            })?;
            Ok(())
        }
        Err(e) => Err(BoxliteError::Storage(format!(
            "Failed to move {} to {}: {}",
            src.display(),
            dst.display(),
            e
        ))),
    }
}

// ── Checksums ───────────────────────────────────────────────────────────

/// Compute SHA-256 checksum of a file, returning "sha256:<hex>" string.
pub(crate) fn sha256_file(path: &Path) -> BoxliteResult<String> {
    use std::io::Read;

    let mut file = std::fs::File::open(path).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to open {} for checksum: {}",
            path.display(),
            e
        ))
    })?;

    let mut hasher = Sha256::new();
    let mut buf = [0u8; 64 * 1024];
    loop {
        let n = file.read(&mut buf).map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to read {} for checksum: {}",
                path.display(),
                e
            ))
        })?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }

    Ok(format!("sha256:{}", hex::encode(hasher.finalize())))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    /// An export must not be readable by an importer that would drop part of
    /// its configuration: capability policies are stamped v4, published ports
    /// v5, ordinary boxes v3.
    ///
    /// The literals are the compatibility boundary itself — a pre-capability
    /// importer accepts up to 3, a pre-publication one up to 4 — so pin them,
    /// not just the branch.
    #[test]
    fn configuration_an_older_importer_would_drop_raises_the_archive_version() {
        assert_eq!(ARCHIVE_VERSION, 3);
        assert_eq!(CAPABILITY_POLICY_ARCHIVE_VERSION, 4);
        assert_eq!(PUBLISHED_PORTS_ARCHIVE_VERSION, 5);

        let ordinary = crate::runtime::options::BoxOptions::default();
        assert_eq!(archive_version_for_options(&ordinary), ARCHIVE_VERSION);

        let mut custom_advanced = crate::runtime::advanced_options::AdvancedBoxOptions::default();
        custom_advanced
            .set_capabilities(Some(
                crate::runtime::advanced_options::ContainerCapabilities {
                    drop: vec!["NET_RAW".into()],
                    ..Default::default()
                },
            ))
            .unwrap();
        let custom = crate::runtime::options::BoxOptions {
            advanced: custom_advanced,
            ..Default::default()
        };
        assert_eq!(
            archive_version_for_options(&custom),
            CAPABILITY_POLICY_ARCHIVE_VERSION
        );

        // An explicit, empty capability policy is still an explicit policy,
        // not the same as never touching the field — a pre-capability
        // importer must not decide that distinction was safe to drop.
        let mut explicit_empty_advanced =
            crate::runtime::advanced_options::AdvancedBoxOptions::default();
        explicit_empty_advanced
            .set_capabilities(Some(
                crate::runtime::advanced_options::ContainerCapabilities::default(),
            ))
            .unwrap();
        let explicit_empty = crate::runtime::options::BoxOptions {
            advanced: explicit_empty_advanced,
            ..Default::default()
        };
        assert_eq!(
            archive_version_for_options(&explicit_empty),
            CAPABILITY_POLICY_ARCHIVE_VERSION
        );

        // Every port field gained meaning in v5. A fixed mapping with a bind IP
        // is the case a v3 stamp would lose silently: an older importer drops
        // host_ip and publishes on every interface.
        for ports in [
            vec![crate::runtime::options::PortSpec {
                host_port: None,
                guest_port: 3000,
                protocol: crate::runtime::options::PortProtocol::Tcp,
                host_ip: None,
            }],
            vec![crate::runtime::options::PortSpec {
                host_port: Some(18080),
                guest_port: 80,
                protocol: crate::runtime::options::PortProtocol::Tcp,
                host_ip: Some("127.0.0.1".to_string()),
            }],
        ] {
            let published = crate::runtime::options::BoxOptions {
                ports,
                ..Default::default()
            };
            assert_eq!(
                archive_version_for_options(&published),
                PUBLISHED_PORTS_ARCHIVE_VERSION
            );
        }
    }

    /// Regression: the export stamp and the importer's canonicalization window
    /// have to agree. When they drift, a box exported by this build re-imports
    /// through `normalize_legacy_ports`, which clears `host_ip` — turning a
    /// loopback publication into one on every interface.
    #[test]
    fn this_builds_port_exports_are_never_canonicalized_on_import() {
        let published = crate::runtime::options::BoxOptions {
            ports: vec![crate::runtime::options::PortSpec {
                host_port: Some(18080),
                guest_port: 80,
                protocol: crate::runtime::options::PortProtocol::Tcp,
                host_ip: Some("127.0.0.1".to_string()),
            }],
            ..Default::default()
        };

        assert!(
            archive_version_for_options(&published) >= PUBLISHED_PORTS_ARCHIVE_VERSION,
            "an export carrying ports must be stamped at or above the version \
             below which the importer rewrites them"
        );
    }

    #[test]
    fn test_extract_zstd_archive_via_magic_bytes() {
        let dir = tempdir().unwrap();
        let archive_path = dir.path().join("test.boxlite");
        let extract_dir = dir.path().join("extracted");
        std::fs::create_dir_all(&extract_dir).unwrap();

        // Create a small zstd-compressed tar with a test file.
        let test_content = b"hello from zstd archive";
        let test_file = dir.path().join("test.txt");
        std::fs::write(&test_file, test_content).unwrap();

        {
            let file = std::fs::File::create(&archive_path).unwrap();
            let encoder = zstd::Encoder::new(file, 3).unwrap();
            let mut builder = tar::Builder::new(encoder);
            builder
                .append_path_with_name(&test_file, "test.txt")
                .unwrap();
            let encoder = builder.into_inner().unwrap();
            encoder.finish().unwrap();
        }

        // Verify magic bytes
        let header = std::fs::read(&archive_path).unwrap();
        assert_eq!(&header[..4], &ZSTD_MAGIC);

        // Extract and verify
        extract_archive(&archive_path, &extract_dir).unwrap();
        let content = std::fs::read_to_string(extract_dir.join("test.txt")).unwrap();
        assert_eq!(content, "hello from zstd archive");
    }

    #[test]
    fn test_extract_plain_tar_via_magic_bytes() {
        let dir = tempdir().unwrap();
        let archive_path = dir.path().join("test.tar");
        let extract_dir = dir.path().join("extracted");
        std::fs::create_dir_all(&extract_dir).unwrap();

        let test_file = dir.path().join("test.txt");
        std::fs::write(&test_file, b"hello from plain tar").unwrap();

        {
            let file = std::fs::File::create(&archive_path).unwrap();
            let mut builder = tar::Builder::new(file);
            builder
                .append_path_with_name(&test_file, "test.txt")
                .unwrap();
            builder.finish().unwrap();
        }

        // Verify NOT zstd magic
        let header = std::fs::read(&archive_path).unwrap();
        assert_ne!(&header[..4], &ZSTD_MAGIC);

        extract_archive(&archive_path, &extract_dir).unwrap();
        let content = std::fs::read_to_string(extract_dir.join("test.txt")).unwrap();
        assert_eq!(content, "hello from plain tar");
    }

    #[test]
    fn test_move_file_same_filesystem() {
        let dir = tempdir().unwrap();
        let src = dir.path().join("src.txt");
        let dst = dir.path().join("dst.txt");
        std::fs::write(&src, "move me").unwrap();

        move_file(&src, &dst).unwrap();

        assert!(!src.exists());
        assert_eq!(std::fs::read_to_string(&dst).unwrap(), "move me");
    }

    #[test]
    fn test_move_file_nonexistent_source_errors() {
        let dir = tempdir().unwrap();
        let src = dir.path().join("nonexistent.txt");
        let dst = dir.path().join("dst.txt");

        assert!(move_file(&src, &dst).is_err());
    }

    #[test]
    fn test_sha256_file_deterministic() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("test.bin");
        std::fs::write(&path, b"deterministic content").unwrap();

        let hash1 = sha256_file(&path).unwrap();
        let hash2 = sha256_file(&path).unwrap();
        assert_eq!(hash1, hash2);
        assert!(hash1.starts_with("sha256:"));
    }

    #[test]
    fn test_build_and_extract_roundtrip() {
        let dir = tempdir().unwrap();
        let archive_path = dir.path().join("roundtrip.boxlite");
        let extract_dir = dir.path().join("extracted");
        std::fs::create_dir_all(&extract_dir).unwrap();

        // Create test files
        let manifest_path = dir.path().join(MANIFEST_FILENAME);
        let container_path = dir.path().join("container.qcow2");
        std::fs::write(&manifest_path, r#"{"version":2}"#).unwrap();
        std::fs::write(&container_path, "fake-container-disk").unwrap();

        build_zstd_tar_archive(&archive_path, &manifest_path, &container_path, 3).unwrap();
        extract_archive(&archive_path, &extract_dir).unwrap();

        assert_eq!(
            std::fs::read_to_string(extract_dir.join(MANIFEST_FILENAME)).unwrap(),
            r#"{"version":2}"#
        );
        assert_eq!(
            std::fs::read_to_string(extract_dir.join(disk_filenames::CONTAINER_DISK)).unwrap(),
            "fake-container-disk",
            "the container disk must be extracted"
        );
        assert!(
            !extract_dir.join(disk_filenames::GUEST_ROOTFS_DISK).exists(),
            "the archive must not contain a guest rootfs member"
        );
    }

    /// A `.boxlite` archive is untrusted input, and tar validates only where an
    /// entry is *written* — a symlink's target is copied verbatim. Without an
    /// entry-type check an archive can plant `disk.qcow2` as a link to any host
    /// path, and every later step (exists, checksum, backing-file scan, rename)
    /// follows it. The link must never reach the filesystem at all.
    #[test]
    fn extract_archive_rejects_symlink_entry() {
        let dir = tempdir().unwrap();
        let archive_path = dir.path().join("evil.boxlite");
        let extract_dir = dir.path().join("extracted");
        std::fs::create_dir_all(&extract_dir).unwrap();

        let victim = dir.path().join("victim-disk.qcow2");
        std::fs::write(&victim, b"victim bytes").unwrap();

        {
            let file = std::fs::File::create(&archive_path).unwrap();
            let mut builder = tar::Builder::new(file);
            let mut header = tar::Header::new_gnu();
            header.set_entry_type(tar::EntryType::Symlink);
            header.set_size(0);
            header.set_mode(0o777);
            builder
                .append_link(&mut header, disk_filenames::CONTAINER_DISK, &victim)
                .unwrap();
            builder.finish().unwrap();
        }

        let error = extract_archive(&archive_path, &extract_dir)
            .expect_err("a symlink archive member must be rejected");
        assert!(
            error.to_string().contains(disk_filenames::CONTAINER_DISK),
            "the error must name the offending member, got: {error}"
        );
        assert!(
            extract_dir
                .join(disk_filenames::CONTAINER_DISK)
                .symlink_metadata()
                .is_err(),
            "the link must never reach the filesystem"
        );
    }

    /// The same rule covers hard links. `symlink_metadata` reports a hard link
    /// as a regular file, so a check written against that would let this
    /// through; only the archive member's own type tells the truth.
    #[test]
    fn extract_archive_rejects_hardlink_entry() {
        let dir = tempdir().unwrap();
        let archive_path = dir.path().join("evil.boxlite");
        let extract_dir = dir.path().join("extracted");
        std::fs::create_dir_all(&extract_dir).unwrap();

        let manifest = dir.path().join(MANIFEST_FILENAME);
        std::fs::write(&manifest, br#"{"version":3}"#).unwrap();

        {
            let file = std::fs::File::create(&archive_path).unwrap();
            let mut builder = tar::Builder::new(file);
            builder
                .append_path_with_name(&manifest, MANIFEST_FILENAME)
                .unwrap();
            let mut header = tar::Header::new_gnu();
            header.set_entry_type(tar::EntryType::Link);
            header.set_size(0);
            header.set_mode(0o644);
            builder
                .append_link(
                    &mut header,
                    disk_filenames::CONTAINER_DISK,
                    MANIFEST_FILENAME,
                )
                .unwrap();
            builder.finish().unwrap();
        }

        let error = extract_archive(&archive_path, &extract_dir)
            .expect_err("a hard link archive member must be rejected");
        assert!(
            error.to_string().contains(disk_filenames::CONTAINER_DISK),
            "the error must name the offending member, got: {error}"
        );
        assert!(
            extract_dir
                .join(disk_filenames::CONTAINER_DISK)
                .symlink_metadata()
                .is_err(),
            "the link must never reach the filesystem"
        );
    }

    /// Archives written before the guest rootfs became a shared base image
    /// carry a third member. The importer ignores it, but extraction must
    /// still accept it — rejecting unknown *names* would strand every archive
    /// exported by a released build.
    #[test]
    fn extract_archive_accepts_legacy_guest_rootfs_member() {
        let dir = tempdir().unwrap();
        let archive_path = dir.path().join("legacy.boxlite");
        let extract_dir = dir.path().join("extracted");
        std::fs::create_dir_all(&extract_dir).unwrap();

        let manifest = dir.path().join(MANIFEST_FILENAME);
        let container = dir.path().join("container-src");
        let guest = dir.path().join("guest-src");
        std::fs::write(&manifest, br#"{"version":2}"#).unwrap();
        std::fs::write(&container, b"container-disk").unwrap();
        std::fs::write(&guest, b"guest-rootfs-disk").unwrap();

        {
            let file = std::fs::File::create(&archive_path).unwrap();
            let mut builder = tar::Builder::new(file);
            builder
                .append_path_with_name(&manifest, MANIFEST_FILENAME)
                .unwrap();
            builder
                .append_path_with_name(&container, disk_filenames::CONTAINER_DISK)
                .unwrap();
            builder
                .append_path_with_name(&guest, disk_filenames::GUEST_ROOTFS_DISK)
                .unwrap();
            builder.finish().unwrap();
        }

        extract_archive(&archive_path, &extract_dir)
            .expect("a legacy 3-member archive must import");
        assert_eq!(
            std::fs::read_to_string(extract_dir.join(disk_filenames::CONTAINER_DISK)).unwrap(),
            "container-disk"
        );
        assert_eq!(
            std::fs::read_to_string(extract_dir.join(disk_filenames::GUEST_ROOTFS_DISK)).unwrap(),
            "guest-rootfs-disk"
        );
    }
    /// Every exported disk is a sparse qcow2, and on Linux `tar::Builder`
    /// encodes a file with holes as a `GNUSparse` member rather than a plain
    /// regular one. A member-type check written against `Regular` alone reads
    /// as correct against small dense fixtures and rejects every real export,
    /// so the fixture here has to have a hole in it.
    #[test]
    fn extract_archive_accepts_sparse_disk_member() {
        use std::io::{Seek, SeekFrom, Write};

        const HOLE_END: u64 = 8 * 1024 * 1024;

        let dir = tempdir().unwrap();
        let archive_path = dir.path().join("sparse.boxlite");
        let extract_dir = dir.path().join("extracted");
        std::fs::create_dir_all(&extract_dir).unwrap();

        let manifest = dir.path().join(MANIFEST_FILENAME);
        std::fs::write(&manifest, br#"{"version":3}"#).unwrap();

        let disk = dir.path().join("sparse-disk");
        {
            let mut file = std::fs::File::create(&disk).unwrap();
            file.write_all(b"head").unwrap();
            file.seek(SeekFrom::Start(HOLE_END)).unwrap();
            file.write_all(b"tail").unwrap();
            file.sync_all().unwrap();
        }

        build_zstd_tar_archive(&archive_path, &manifest, &disk, 3).unwrap();

        // Where the builder reads hole information, assert the fixture really
        // did reproduce a real export's encoding — otherwise this test would
        // quietly stop covering the case it exists for.
        #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
        {
            let file = std::fs::File::open(&archive_path).unwrap();
            let decoder = zstd::Decoder::new(file).unwrap();
            let mut probe = tar::Archive::new(decoder);
            let mut disk_member_type = None;
            for entry in probe.entries().unwrap() {
                let entry = entry.unwrap();
                if entry.path().unwrap().to_string_lossy() == disk_filenames::CONTAINER_DISK {
                    disk_member_type = Some(entry.header().entry_type());
                }
            }
            assert_eq!(
                disk_member_type,
                Some(tar::EntryType::GNUSparse),
                "the fixture must be encoded the way a real exported disk is"
            );
        }

        extract_archive(&archive_path, &extract_dir).expect("a sparse disk member must extract");

        let extracted = std::fs::read(extract_dir.join(disk_filenames::CONTAINER_DISK)).unwrap();
        assert_eq!(extracted.len() as u64, HOLE_END + 4);
        assert_eq!(&extracted[..4], b"head");
        assert_eq!(&extracted[HOLE_END as usize..], b"tail");
    }
}