a3s-box-runtime 3.0.10

MicroVM runtime engine — VM lifecycle, OCI images, attestation, networking
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
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! Host-side rootfs ownership preparation for user-namespace execution.

#[cfg(target_os = "linux")]
use std::collections::HashSet;
#[cfg(any(target_os = "linux", test))]
use std::path::Component;
use std::path::{Path, PathBuf};

use a3s_box_core::error::{BoxError, Result};
use a3s_box_core::rootfs_metadata::{
    runtime_managed_rootfs_mode, RootfsMetadataManifest, IMAGE_ROOTFS_METADATA_PATH,
    ROOTFS_METADATA_PATH,
};
#[cfg(any(target_os = "linux", test))]
use a3s_box_core::rootfs_metadata::{RootfsEntryKind, RootfsMetadataEntry};
#[cfg(any(target_os = "linux", test))]
use base64::Engine;

use super::capability::{IdMapping, SandboxIdMappingPlan};

/// Container IDs discovered in the authoritative rootfs metadata manifest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RootfsIdentityRequirements {
    pub maximum_uid: u32,
    pub maximum_gid: u32,
    pub manifest_path: PathBuf,
}

/// Host IDs representing container root for one mapping plan.
pub fn mapped_root_ids(plan: &SandboxIdMappingPlan) -> Result<(u32, u32)> {
    Ok((
        map_container_id(&plan.uid_mappings, 0, "UID")?,
        map_container_id(&plan.gid_mappings, 0, "GID")?,
    ))
}

/// Make an A3S-owned workspace or anonymous volume accessible as container
/// root without ever changing an arbitrary caller-provided host tree.
#[cfg(target_os = "linux")]
pub fn prepare_managed_mount_source(path: &Path, plan: &SandboxIdMappingPlan) -> Result<()> {
    ensure_no_nested_mounts(path)?;
    let (root_uid, root_gid) = mapped_root_ids(plan)?;
    prepare_managed_tree(path, plan, root_uid, root_gid)
}

#[cfg(not(target_os = "linux"))]
pub fn prepare_managed_mount_source(_path: &Path, _plan: &SandboxIdMappingPlan) -> Result<()> {
    Err(BoxError::ConfigError(
        "Sandbox mount ownership preparation requires Linux".to_string(),
    ))
}

/// Verify that an external bind source's root is usable by the mapped root
/// identity. The runtime refuses to chown external host data implicitly.
#[cfg(unix)]
pub fn validate_external_mount_access(
    path: &Path,
    plan: &SandboxIdMappingPlan,
    read_only: bool,
) -> Result<()> {
    use std::os::unix::fs::MetadataExt;

    let (uid, gid) = mapped_root_ids(plan)?;
    let metadata = std::fs::metadata(path).map_err(BoxError::IoError)?;
    let mode = metadata.mode();
    let permission_bits = if metadata.uid() == uid {
        (mode >> 6) & 0o7
    } else if metadata.gid() == gid {
        (mode >> 3) & 0o7
    } else {
        mode & 0o7
    };
    let required = if metadata.is_dir() {
        if read_only {
            0o5
        } else {
            0o7
        }
    } else if read_only {
        0o4
    } else {
        0o6
    };
    if permission_bits & required != required {
        return Err(BoxError::ConfigError(format!(
            "External Sandbox mount {} is not {} by mapped container root {uid}:{gid}; adjust host ownership/permissions or use an A3S-managed volume",
            path.display(),
            if read_only { "readable" } else { "writable" }
        )));
    }
    Ok(())
}

#[cfg(not(unix))]
pub fn validate_external_mount_access(
    _path: &Path,
    _plan: &SandboxIdMappingPlan,
    _read_only: bool,
) -> Result<()> {
    Err(BoxError::ConfigError(
        "Sandbox bind mount validation requires Linux".to_string(),
    ))
}

#[cfg(target_os = "linux")]
struct DecodedEntry {
    metadata: RootfsMetadataEntry,
    relative: PathBuf,
    target: PathBuf,
}

/// Read the terminal persistent manifest when present, otherwise the immutable
/// image manifest. The mapping plan must cover every ID before `crun` starts.
pub fn inspect_rootfs_identity_requirements(root: &Path) -> Result<RootfsIdentityRequirements> {
    let (manifest_path, manifest) = load_authoritative_manifest(root)?;
    let mut maximum_uid = 0u32;
    let mut maximum_gid = 0u32;
    for entry in manifest.entries {
        let uid = u32::try_from(entry.uid).map_err(|_| {
            BoxError::OciImageError("rootfs metadata UID exceeds the Linux range".to_string())
        })?;
        let gid = u32::try_from(entry.gid).map_err(|_| {
            BoxError::OciImageError("rootfs metadata GID exceeds the Linux range".to_string())
        })?;
        maximum_uid = maximum_uid.max(uid);
        maximum_gid = maximum_gid.max(gid);
    }
    Ok(RootfsIdentityRequirements {
        maximum_uid,
        maximum_gid,
        manifest_path,
    })
}

/// Prepare one per-box rootfs for the exact user-namespace mapping.
///
/// A root-run service can translate OCI container ownership to subordinate
/// host IDs directly. A non-root service leaves ownership replay to PID 1 from
/// inside the user namespace. Read-only rootfs is rejected for the latter until
/// an idmapped-mount path can guarantee replay before the read-only transition.
#[cfg(target_os = "linux")]
pub fn prepare_rootfs_ownership(
    root: &Path,
    plan: &SandboxIdMappingPlan,
    effective_uid: u32,
    read_only: bool,
) -> Result<()> {
    if effective_uid != 0 {
        if read_only {
            return Err(BoxError::ConfigError(
                "Sandbox read-only rootfs requires a root-run service until idmapped rootfs preparation is available"
                    .to_string(),
            ));
        }
        return Ok(());
    }

    ensure_no_nested_mounts(root)?;
    let (_, manifest) = load_authoritative_manifest(root)?;
    let entries = decode_and_validate_entries(root, manifest)?;
    let authoritative_paths: HashSet<PathBuf> =
        entries.iter().map(|entry| entry.relative.clone()).collect();

    for entry in &entries {
        let uid = map_container_id(
            &plan.uid_mappings,
            u32::try_from(entry.metadata.uid).map_err(|_| {
                BoxError::OciImageError("rootfs metadata UID exceeds the Linux range".to_string())
            })?,
            "UID",
        )?;
        let gid = map_container_id(
            &plan.gid_mappings,
            u32::try_from(entry.metadata.gid).map_err(|_| {
                BoxError::OciImageError("rootfs metadata GID exceeds the Linux range".to_string())
            })?,
            "GID",
        )?;
        lchown_if_needed(&entry.target, uid, gid)?;
    }

    // Files written by the runtime after manifest generation (DNS, hostname,
    // env staging, refreshed init, and the manifests themselves) are not all
    // represented in the selected generation. Walk without following symlinks:
    // already-mapped IDs are left untouched, while raw OCI IDs are translated.
    shift_unlisted_entries(root, root, &authoritative_paths, plan)?;

    // chown clears setuid/setgid bits on regular files. Restore exact manifest
    // modes deepest-first after every ownership change.
    let mut modes: Vec<_> = entries
        .iter()
        .filter(|entry| entry.metadata.kind != RootfsEntryKind::Symlink)
        .collect();
    modes.sort_by_key(|entry| std::cmp::Reverse(entry.relative.components().count()));
    for entry in modes {
        use std::os::unix::fs::PermissionsExt;
        let mode =
            runtime_managed_rootfs_mode(&entry.relative).unwrap_or(entry.metadata.mode & 0o7777);
        std::fs::set_permissions(&entry.target, std::fs::Permissions::from_mode(mode)).map_err(
            |error| BoxError::BoxBootError {
                message: format!(
                    "Failed to restore Sandbox rootfs mode at {}: {error}",
                    entry.target.display()
                ),
                hint: None,
            },
        )?;
    }

    Ok(())
}

/// Capture authoritative guest-visible metadata for a quiesced Sandbox rootfs.
///
/// The host sees user-namespace IDs, so every UID/GID is translated back
/// through the exact OCI mappings before the manifest is stored in a
/// filesystem Snapshot. The walk never follows symlinks and rejects special
/// files, preventing a FIFO or device node from entering the copy path.
#[cfg(target_os = "linux")]
pub(crate) fn capture_snapshot_rootfs_metadata(
    root: &Path,
    plan: &SandboxIdMappingPlan,
) -> Result<RootfsMetadataManifest> {
    ensure_no_nested_mounts(root)?;
    let mut entries = Vec::new();
    collect_snapshot_rootfs_metadata(root, root, Path::new("."), plan, &mut entries)?;
    entries.sort_by(|left, right| left.path_base64.cmp(&right.path_base64));
    Ok(RootfsMetadataManifest::new(entries))
}

#[cfg(target_os = "linux")]
fn collect_snapshot_rootfs_metadata(
    root: &Path,
    source: &Path,
    manifest_path: &Path,
    plan: &SandboxIdMappingPlan,
    entries: &mut Vec<RootfsMetadataEntry>,
) -> Result<()> {
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::{FileTypeExt, MetadataExt};

    let relative = source
        .strip_prefix(root)
        .map_err(|_| BoxError::OciImageError("Sandbox Snapshot walk escaped its root".into()))?;
    if matches!(
        relative.to_str(),
        Some(".a3s_rootfs_metadata_v1.json")
            | Some(".a3s_rootfs_metadata_v1.json.tmp")
            | Some(".a3s_image_metadata_v1.json")
            | Some(".a3s_image_metadata_v1.json.tmp")
            | Some(".a3s_exit_code")
            | Some("init.trace.log")
    ) {
        return Ok(());
    }

    let metadata = std::fs::symlink_metadata(source).map_err(BoxError::IoError)?;
    let file_type = metadata.file_type();
    let (kind, link_target_base64) = if file_type.is_dir() {
        (RootfsEntryKind::Directory, None)
    } else if file_type.is_file() {
        (RootfsEntryKind::Regular, None)
    } else if file_type.is_symlink() {
        let target = std::fs::read_link(source).map_err(BoxError::IoError)?;
        (
            RootfsEntryKind::Symlink,
            Some(base64::engine::general_purpose::STANDARD.encode(target.as_os_str().as_bytes())),
        )
    } else {
        let kind = if file_type.is_fifo() {
            "fifo"
        } else if file_type.is_socket() {
            "socket"
        } else if file_type.is_char_device() {
            "character device"
        } else if file_type.is_block_device() {
            "block device"
        } else {
            "unknown"
        };
        return Err(BoxError::OciImageError(format!(
            "Sandbox Snapshot rootfs contains unsupported special file {} ({kind})",
            source.display()
        )));
    };
    entries.push(RootfsMetadataEntry {
        path_base64: base64::engine::general_purpose::STANDARD
            .encode(manifest_path.as_os_str().as_bytes()),
        kind,
        mode: metadata.mode(),
        uid: unmap_host_id(&plan.uid_mappings, metadata.uid(), "UID")? as u64,
        gid: unmap_host_id(&plan.gid_mappings, metadata.gid(), "GID")? as u64,
        mtime: metadata.mtime().max(0) as u64,
        size: metadata.size(),
        link_target_base64,
    });

    if file_type.is_dir() {
        let mut children: Vec<_> = std::fs::read_dir(source)
            .map_err(BoxError::IoError)?
            .collect::<std::result::Result<_, _>>()
            .map_err(BoxError::IoError)?;
        children.sort_by_key(std::fs::DirEntry::file_name);
        for child in children {
            collect_snapshot_rootfs_metadata(
                root,
                &child.path(),
                &manifest_path.join(child.file_name()),
                plan,
                entries,
            )?;
        }
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn unmap_host_id(mappings: &[IdMapping], id: u32, kind: &str) -> Result<u32> {
    for mapping in mappings {
        let Some(end) = mapping.host_id.checked_add(mapping.size) else {
            continue;
        };
        if mapping.host_id <= id && id < end {
            return mapping
                .container_id
                .checked_add(id - mapping.host_id)
                .ok_or_else(|| {
                    BoxError::ConfigError(format!(
                        "Sandbox Snapshot {kind} reverse mapping overflows u32"
                    ))
                });
        }
    }
    Err(BoxError::ConfigError(format!(
        "Sandbox Snapshot host {kind} {id} is outside the OCI mappings"
    )))
}

#[cfg(not(target_os = "linux"))]
pub fn prepare_rootfs_ownership(
    _root: &Path,
    _plan: &SandboxIdMappingPlan,
    _effective_uid: u32,
    _read_only: bool,
) -> Result<()> {
    Err(BoxError::ConfigError(
        "Sandbox rootfs ownership preparation requires Linux".to_string(),
    ))
}

fn load_authoritative_manifest(root: &Path) -> Result<(PathBuf, RootfsMetadataManifest)> {
    let terminal = root.join(ROOTFS_METADATA_PATH.trim_start_matches('/'));
    let image = root.join(IMAGE_ROOTFS_METADATA_PATH.trim_start_matches('/'));
    let path = if terminal.exists() { terminal } else { image };
    let bytes = std::fs::read(&path).map_err(|error| BoxError::BoxBootError {
        message: format!(
            "Sandbox rootfs metadata is unavailable at {}: {error}",
            path.display()
        ),
        hint: Some("Rebuild the per-box rootfs from its OCI image".to_string()),
    })?;
    let manifest: RootfsMetadataManifest = serde_json::from_slice(&bytes).map_err(|error| {
        BoxError::OciImageError(format!(
            "Invalid Sandbox rootfs metadata {}: {error}",
            path.display()
        ))
    })?;
    manifest.validate().map_err(BoxError::OciImageError)?;
    Ok((path, manifest))
}

#[cfg(target_os = "linux")]
fn decode_and_validate_entries(
    root: &Path,
    manifest: RootfsMetadataManifest,
) -> Result<Vec<DecodedEntry>> {
    let mut decoded = Vec::with_capacity(manifest.entries.len());
    let mut unique = HashSet::with_capacity(manifest.entries.len());
    for metadata in manifest.entries {
        let raw = base64::engine::general_purpose::STANDARD
            .decode(&metadata.path_base64)
            .map_err(|error| {
                BoxError::OciImageError(format!("Invalid rootfs metadata path: {error}"))
            })?;
        // Manifests are produced and consumed on the same host, so the encoded
        // platform path bytes can be reconstructed losslessly.
        let encoded = unsafe { std::ffi::OsString::from_encoded_bytes_unchecked(raw) };
        let relative = safe_relative_path(Path::new(&encoded))?;
        if relative == Path::new(IMAGE_ROOTFS_METADATA_PATH.trim_start_matches('/'))
            || relative == Path::new(ROOTFS_METADATA_PATH.trim_start_matches('/'))
            || !unique.insert(relative.clone())
        {
            return Err(BoxError::OciImageError(
                "Duplicate or reserved Sandbox rootfs metadata path".to_string(),
            ));
        }
        let target = resolve_without_symlink_parent(root, &relative)?;
        let filesystem =
            std::fs::symlink_metadata(&target).map_err(|error| BoxError::BoxBootError {
                message: format!(
                    "Sandbox rootfs metadata target {} is unavailable: {error}",
                    target.display()
                ),
                hint: None,
            })?;
        let actual_kind = if filesystem.file_type().is_dir() {
            RootfsEntryKind::Directory
        } else if filesystem.file_type().is_file() {
            RootfsEntryKind::Regular
        } else if filesystem.file_type().is_symlink() {
            RootfsEntryKind::Symlink
        } else {
            return Err(BoxError::OciImageError(format!(
                "Unsupported rootfs entry at {}",
                target.display()
            )));
        };
        if actual_kind != metadata.kind {
            return Err(BoxError::OciImageError(format!(
                "Sandbox rootfs metadata type mismatch at {}",
                target.display()
            )));
        }
        if actual_kind == RootfsEntryKind::Symlink {
            let expected = metadata.link_target_base64.as_ref().ok_or_else(|| {
                BoxError::OciImageError("Symlink metadata is missing its target".to_string())
            })?;
            let expected = base64::engine::general_purpose::STANDARD
                .decode(expected)
                .map_err(|error| {
                    BoxError::OciImageError(format!("Invalid symlink target metadata: {error}"))
                })?;
            if std::fs::read_link(&target)
                .map_err(BoxError::IoError)?
                .as_os_str()
                .as_encoded_bytes()
                != expected
            {
                return Err(BoxError::OciImageError(format!(
                    "Sandbox rootfs symlink mismatch at {}",
                    target.display()
                )));
            }
        }
        decoded.push(DecodedEntry {
            metadata,
            relative,
            target,
        });
    }
    Ok(decoded)
}

#[cfg(any(target_os = "linux", test))]
fn safe_relative_path(path: &Path) -> Result<PathBuf> {
    let mut result = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::Normal(name) => result.push(name),
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return Err(BoxError::OciImageError(
                    "Unsafe Sandbox rootfs metadata path".to_string(),
                ))
            }
        }
    }
    Ok(result)
}

#[cfg(target_os = "linux")]
fn resolve_without_symlink_parent(root: &Path, relative: &Path) -> Result<PathBuf> {
    let mut current = root.to_path_buf();
    let components: Vec<_> = relative.components().collect();
    for (index, component) in components.iter().enumerate() {
        let Component::Normal(name) = component else {
            continue;
        };
        current.push(name);
        if index + 1 < components.len()
            && std::fs::symlink_metadata(&current)
                .map_err(BoxError::IoError)?
                .file_type()
                .is_symlink()
        {
            return Err(BoxError::OciImageError(format!(
                "Symlink parent in Sandbox rootfs metadata path: {}",
                current.display()
            )));
        }
    }
    Ok(current)
}

#[cfg(target_os = "linux")]
fn shift_unlisted_entries(
    root: &Path,
    source: &Path,
    authoritative: &HashSet<PathBuf>,
    plan: &SandboxIdMappingPlan,
) -> Result<()> {
    use std::os::unix::fs::MetadataExt;

    let relative = source
        .strip_prefix(root)
        .map_err(|_| BoxError::OciImageError("Sandbox rootfs walk escaped its root".to_string()))?;
    let metadata = std::fs::symlink_metadata(source).map_err(BoxError::IoError)?;
    if !authoritative.contains(relative) {
        let uid = map_current_or_container_id(&plan.uid_mappings, metadata.uid(), "UID")?;
        let gid = map_current_or_container_id(&plan.gid_mappings, metadata.gid(), "GID")?;
        lchown_if_needed(source, uid, gid)?;
    }
    if metadata.file_type().is_dir() {
        for child in std::fs::read_dir(source).map_err(BoxError::IoError)? {
            shift_unlisted_entries(
                root,
                &child.map_err(BoxError::IoError)?.path(),
                authoritative,
                plan,
            )?;
        }
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn prepare_managed_tree(
    path: &Path,
    plan: &SandboxIdMappingPlan,
    root_uid: u32,
    root_gid: u32,
) -> Result<()> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};

    let metadata = std::fs::symlink_metadata(path).map_err(BoxError::IoError)?;
    let uid = if id_is_mapped(&plan.uid_mappings, metadata.uid()) {
        metadata.uid()
    } else {
        root_uid
    };
    let gid = if id_is_mapped(&plan.gid_mappings, metadata.gid()) {
        metadata.gid()
    } else {
        root_gid
    };
    let mode = metadata.mode() & 0o7777;
    lchown_if_needed(path, uid, gid)?;
    if !metadata.file_type().is_symlink() {
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
            .map_err(BoxError::IoError)?;
    }
    if metadata.file_type().is_dir() {
        for child in std::fs::read_dir(path).map_err(BoxError::IoError)? {
            prepare_managed_tree(
                &child.map_err(BoxError::IoError)?.path(),
                plan,
                root_uid,
                root_gid,
            )?;
        }
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn id_is_mapped(mappings: &[IdMapping], id: u32) -> bool {
    mappings.iter().any(|mapping| {
        mapping
            .host_id
            .checked_add(mapping.size)
            .is_some_and(|end| mapping.host_id <= id && id < end)
    })
}

#[cfg(target_os = "linux")]
fn ensure_no_nested_mounts(root: &Path) -> Result<()> {
    let root = root.canonicalize().map_err(BoxError::IoError)?;
    let mountinfo = std::fs::read_to_string("/proc/self/mountinfo").map_err(BoxError::IoError)?;
    for mount in mountinfo
        .lines()
        .filter_map(|line| line.split_whitespace().nth(4))
        .map(decode_mountinfo_path)
        .map(PathBuf::from)
    {
        if mount != root && mount.starts_with(&root) {
            return Err(BoxError::BoxBootError {
                message: format!(
                    "Refusing Sandbox ownership preparation across nested mount {} under {}",
                    mount.display(),
                    root.display()
                ),
                hint: Some("Reconcile the stale mount before restarting the Sandbox".to_string()),
            });
        }
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn decode_mountinfo_path(value: &str) -> String {
    value
        .replace("\\040", " ")
        .replace("\\011", "\t")
        .replace("\\012", "\n")
        .replace("\\134", "\\")
}

#[cfg(target_os = "linux")]
fn map_current_or_container_id(mappings: &[IdMapping], id: u32, kind: &str) -> Result<u32> {
    if mappings.iter().any(|mapping| {
        mapping
            .host_id
            .checked_add(mapping.size)
            .is_some_and(|end| mapping.host_id <= id && id < end)
    }) {
        return Ok(id);
    }
    map_container_id(mappings, id, kind)
}

fn map_container_id(mappings: &[IdMapping], id: u32, kind: &str) -> Result<u32> {
    for mapping in mappings {
        let Some(end) = mapping.container_id.checked_add(mapping.size) else {
            continue;
        };
        if mapping.container_id <= id && id < end {
            return mapping
                .host_id
                .checked_add(id - mapping.container_id)
                .ok_or_else(|| {
                    BoxError::ConfigError(format!("Sandbox {kind} mapping overflows u32"))
                });
        }
    }
    Err(BoxError::ConfigError(format!(
        "Sandbox {kind} mappings do not cover container ID {id}"
    )))
}

#[cfg(target_os = "linux")]
fn lchown_if_needed(path: &Path, uid: u32, gid: u32) -> Result<()> {
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::fs::MetadataExt;

    let current = std::fs::symlink_metadata(path).map_err(BoxError::IoError)?;
    if current.uid() == uid && current.gid() == gid {
        return Ok(());
    }
    let path_bytes = std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(|_| {
        BoxError::OciImageError(format!(
            "NUL byte in Sandbox rootfs path {}",
            path.display()
        ))
    })?;
    if unsafe { libc::lchown(path_bytes.as_ptr(), uid, gid) } != 0 {
        return Err(BoxError::BoxBootError {
            message: format!(
                "Failed to map Sandbox rootfs ownership at {} to {uid}:{gid}: {}",
                path.display(),
                std::io::Error::last_os_error()
            ),
            hint: None,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use a3s_box_core::rootfs_metadata::ROOTFS_METADATA_SCHEMA;

    #[test]
    fn mapping_translation_is_complete_and_exact() {
        let mappings = vec![
            IdMapping {
                container_id: 0,
                host_id: 100_000,
                size: 10,
            },
            IdMapping {
                container_id: 10,
                host_id: 200_000,
                size: 6,
            },
        ];
        assert_eq!(map_container_id(&mappings, 0, "UID").unwrap(), 100_000);
        assert_eq!(map_container_id(&mappings, 12, "UID").unwrap(), 200_002);
        assert!(map_container_id(&mappings, 16, "UID").is_err());
    }

    #[test]
    fn terminal_manifest_takes_precedence_for_identity_planning() {
        let directory = tempfile::tempdir().unwrap();
        let manifest = |uid, gid| RootfsMetadataManifest {
            schema: ROOTFS_METADATA_SCHEMA.to_string(),
            entries: vec![RootfsMetadataEntry {
                path_base64: base64::engine::general_purpose::STANDARD.encode("."),
                kind: RootfsEntryKind::Directory,
                mode: 0o755,
                uid,
                gid,
                mtime: 0,
                size: 0,
                link_target_base64: None,
            }],
        };
        std::fs::write(
            directory
                .path()
                .join(IMAGE_ROOTFS_METADATA_PATH.trim_start_matches('/')),
            serde_json::to_vec(&manifest(1, 2)).unwrap(),
        )
        .unwrap();
        std::fs::write(
            directory
                .path()
                .join(ROOTFS_METADATA_PATH.trim_start_matches('/')),
            serde_json::to_vec(&manifest(42, 43)).unwrap(),
        )
        .unwrap();

        let requirements = inspect_rootfs_identity_requirements(directory.path()).unwrap();
        assert_eq!(requirements.maximum_uid, 42);
        assert_eq!(requirements.maximum_gid, 43);
        assert!(requirements
            .manifest_path
            .ends_with(".a3s_rootfs_metadata_v1.json"));
    }

    #[test]
    fn unsafe_manifest_path_is_rejected() {
        assert!(safe_relative_path(Path::new("../escape")).is_err());
        assert!(safe_relative_path(Path::new("/host")).is_err());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn ownership_preparation_keeps_runtime_managed_files_readable() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};

        let directory = tempfile::tempdir().unwrap();
        let etc = directory.path().join("etc");
        std::fs::create_dir(&etc).unwrap();
        let hosts = etc.join("hosts");
        let probe = etc.join("probe");
        let init = directory.path().join("usr/sbin/init");
        std::fs::create_dir_all(init.parent().unwrap()).unwrap();
        std::fs::write(&hosts, "127.0.0.1 localhost\n").unwrap();
        std::fs::write(&probe, "probe\n").unwrap();
        for path in [&hosts, &probe] {
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644)).unwrap();
        }
        std::fs::write(&init, "guest init\n").unwrap();
        std::fs::set_permissions(&init, std::fs::Permissions::from_mode(0o755)).unwrap();

        let owner = std::fs::metadata(directory.path()).unwrap();
        let entry = |path: &str, size: u64| RootfsMetadataEntry {
            path_base64: base64::engine::general_purpose::STANDARD.encode(path),
            kind: RootfsEntryKind::Regular,
            mode: 0o100600,
            uid: 0,
            gid: 0,
            mtime: 0,
            size,
            link_target_base64: None,
        };
        let manifest = RootfsMetadataManifest {
            schema: ROOTFS_METADATA_SCHEMA.to_string(),
            entries: vec![
                entry("./etc/hosts", 20),
                entry("./etc/probe", 6),
                entry("./usr/sbin/init", 1),
            ],
        };
        std::fs::write(
            directory
                .path()
                .join(IMAGE_ROOTFS_METADATA_PATH.trim_start_matches('/')),
            serde_json::to_vec(&manifest).unwrap(),
        )
        .unwrap();
        let plan = SandboxIdMappingPlan {
            uid_mappings: vec![IdMapping {
                container_id: 0,
                host_id: owner.uid(),
                size: 1,
            }],
            gid_mappings: vec![IdMapping {
                container_id: 0,
                host_id: owner.gid(),
                size: 1,
            }],
            maximum_container_uid: 0,
            maximum_container_gid: 0,
        };

        prepare_rootfs_ownership(directory.path(), &plan, 0, false).unwrap();

        assert_eq!(
            std::fs::metadata(hosts).unwrap().permissions().mode() & 0o7777,
            0o644
        );
        assert_eq!(
            std::fs::metadata(probe).unwrap().permissions().mode() & 0o7777,
            0o600
        );
        assert_eq!(
            std::fs::metadata(init).unwrap().permissions().mode() & 0o7777,
            0o755
        );
    }
}