boxlite 0.9.3

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
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
//! SeatbeltSandbox — macOS isolation via sandbox-exec.
//!
//! Implements the [`Sandbox`] trait using Apple's Seatbelt sandbox
//! framework via `sandbox-exec` with SBPL profiles.
//!
//! ## Policy Design
//!
//! The sandbox policies are derived from:
//! - OpenAI Codex (Apache 2.0): https://github.com/openai/codex
//! - Chrome's macOS sandbox: https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/
//!
//! ## Security Model: Deny-by-default allowlist
//!
//! BoxLite starts from `(deny default)` and explicitly grants:
//!
//! | Category | Policy source |
//! |----------|---------------|
//! | Base capabilities (process, sysctl, mach, iokit) | `seatbelt_base_policy.sbpl` |
//! | Static system file read/write paths | `seatbelt_file_read_policy.sbpl`, `seatbelt_file_write_policy.sbpl` |
//! | Dynamic file read/write paths | Computed from [`PathAccess`] in `build_sandbox_policy()` |
//! | Network access (optional) | `seatbelt_network_policy.sbpl` when `network_enabled=true` |
//!
//! ## Debugging Sandbox Violations
//!
//! If the shim fails to start due to sandbox restrictions:
//! ```bash
//! log show --predicate 'subsystem == "com.apple.sandbox"' --last 5m
//! ```

use super::{PathAccess, Sandbox, SandboxContext};
use boxlite_shared::errors::BoxliteResult;
use std::ffi::CStr;
use std::path::{Path, PathBuf};
use std::process::Command;

// ============================================================================
// Constants
// ============================================================================

/// Hardcoded path to sandbox-exec to prevent PATH injection attacks.
pub const SANDBOX_EXEC_PATH: &str = "/usr/bin/sandbox-exec";

/// Base sandbox policy (deny-default with fine-grained allowlists).
const SEATBELT_BASE_POLICY: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/resources/seatbelt/seatbelt_base_policy.sbpl"
));

/// Network policy (added when network access is enabled).
const SEATBELT_NETWORK_POLICY: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/resources/seatbelt/seatbelt_network_policy.sbpl"
));

/// File read policy (static system paths).
const SEATBELT_FILE_READ_POLICY: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/resources/seatbelt/seatbelt_file_read_policy.sbpl"
));

/// File write policy (static tmp paths).
const SEATBELT_FILE_WRITE_POLICY: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/resources/seatbelt/seatbelt_file_write_policy.sbpl"
));

// ============================================================================
// SeatbeltSandbox
// ============================================================================

/// macOS sandbox using sandbox-exec (Seatbelt).
#[derive(Debug)]
pub struct SeatbeltSandbox;

impl SeatbeltSandbox {
    pub fn new() -> Self {
        Self
    }

    /// Platform constructor alias (used by [`JailerBuilder`](super::super::JailerBuilder)).
    pub fn platform_new() -> Self {
        Self::new()
    }
}

impl Default for SeatbeltSandbox {
    fn default() -> Self {
        Self::new()
    }
}

impl Sandbox for SeatbeltSandbox {
    fn is_available(&self) -> bool {
        is_sandbox_available()
    }

    fn setup(&self, ctx: &SandboxContext) -> BoxliteResult<()> {
        tracing::debug!(
            id = %ctx.id,
            "Pre-spawn isolation: no-op on macOS (no cgroups)"
        );
        Ok(())
    }

    fn apply(&self, ctx: &SandboxContext, cmd: &mut Command) {
        let binary = cmd.get_program().to_owned();
        let args: Vec<std::ffi::OsString> = cmd.get_args().map(|a| a.to_owned()).collect();

        let binary_path = std::path::Path::new(&binary);
        let (sandbox_cmd, sandbox_args) = build_sandbox_exec_args(
            &ctx.paths,
            binary_path,
            ctx.network_enabled,
            ctx.sandbox_profile,
        );
        let mut new_cmd = Command::new(sandbox_cmd);
        new_cmd.args(sandbox_args);
        new_cmd.arg(&binary);
        new_cmd.args(&args);
        *cmd = new_cmd;
    }

    fn name(&self) -> &'static str {
        "seatbelt"
    }
}

// ============================================================================
// Public API
// ============================================================================

/// Check if sandbox-exec is available on this system.
pub fn is_sandbox_available() -> bool {
    Path::new(SANDBOX_EXEC_PATH).exists()
}

/// Get the base policy for inspection/testing.
pub fn get_base_policy() -> &'static str {
    SEATBELT_BASE_POLICY
}

/// Get the network policy for inspection/testing.
pub fn get_network_policy() -> &'static str {
    SEATBELT_NETWORK_POLICY
}

// ============================================================================
// Sandbox-exec argument building
// ============================================================================

/// Build sandbox-exec arguments from pre-computed path access rules.
///
/// Returns the command and arguments to prepend when spawning the shim.
fn build_sandbox_exec_args(
    paths: &[PathAccess],
    binary_path: &Path,
    network_enabled: bool,
    sandbox_profile: Option<&Path>,
) -> (String, Vec<String>) {
    let mut args = Vec::new();

    // Use custom profile if specified, otherwise build strict policy
    if let Some(profile_path) = sandbox_profile {
        args.push("-f".to_string());
        args.push(profile_path.display().to_string());
    } else {
        // Build strict modular policy: base + file permissions + optional network
        let policy = build_sandbox_policy(paths, binary_path, network_enabled);
        if std::env::var_os("BOXLITE_DEBUG_PRINT_SEATBELT").is_some() {
            eprintln!(
                "BOXLITE_DEBUG seatbelt policy for {}:\n{}",
                binary_path.display(),
                policy
            );
        }
        if let Ok(debug_policy_file) = std::env::var("BOXLITE_DEBUG_POLICY_FILE") {
            let _ = std::fs::write(debug_policy_file, &policy);
        }
        args.push("-p".to_string());
        args.push(policy);
    }

    // Add Darwin user cache dir for network policy
    if let Some(cache_dir) = darwin_user_cache_dir() {
        args.push("-D".to_string());
        args.push(format!("DARWIN_USER_CACHE_DIR={}", cache_dir.display()));
    }

    // Use hardcoded path to prevent PATH injection
    (SANDBOX_EXEC_PATH.to_string(), args)
}

// ============================================================================
// Policy building (private)
// ============================================================================

/// Build the complete sandbox policy by combining static .sbpl files + dynamic paths.
fn build_sandbox_policy(paths: &[PathAccess], binary_path: &Path, network_enabled: bool) -> String {
    let mut policy = String::new();

    // Header
    policy.push_str(
        "; ============================================================================\n",
    );
    policy.push_str("; BoxLite Sandbox Policy\n");
    policy.push_str(
        "; ============================================================================\n",
    );
    policy
        .push_str("; Debug: log show --predicate 'subsystem == \"com.apple.sandbox\"' --last 5m\n");
    policy.push_str(
        "; ============================================================================\n\n",
    );

    // 1. Base policy (sysctls, mach, iokit, process ops)
    policy.push_str(SEATBELT_BASE_POLICY);
    policy.push('\n');

    // 2. Static file READ (system paths from .sbpl)
    policy.push_str(SEATBELT_FILE_READ_POLICY);
    policy.push('\n');

    // 3. Dynamic file READ (binary path + all pre-computed paths)
    policy.push_str(&build_dynamic_read_paths(binary_path, paths));
    policy.push('\n');

    // 4. Static file WRITE (tmp paths from .sbpl)
    policy.push_str(SEATBELT_FILE_WRITE_POLICY);
    policy.push('\n');

    // 5. Dynamic file WRITE (writable paths only)
    policy.push_str(&build_dynamic_write_paths(paths));
    policy.push('\n');

    // 6. Network policy (optional)
    if network_enabled {
        policy.push_str(SEATBELT_NETWORK_POLICY);
    } else {
        policy.push_str("; Network disabled\n");
    }

    policy
}

/// Generate dynamic file-read policy for binary path + all pre-computed paths.
fn build_dynamic_read_paths(binary_path: &Path, paths: &[PathAccess]) -> String {
    let mut policy = String::from("; Dynamic readable paths\n(allow file-read*\n");

    // Add binary's parent directory (copied shim + libkrunfw)
    if let Some(bin_dir) = binary_path.parent() {
        let bin_dir = canonicalize_or_original(bin_dir);
        policy.push_str(&format!(
            "    (subpath \"{}\")  ; shim binary + libkrunfw\n",
            bin_dir.display()
        ));
    } else {
        // Fallback: allow reading the binary itself
        let bin_path = canonicalize_or_original(binary_path);
        policy.push_str(&format!(
            "    (literal \"{}\")  ; shim binary\n",
            bin_path.display()
        ));
    }

    // All pre-computed paths (both rw and ro need read access)
    for pa in paths {
        let path = canonicalize_or_original(&pa.path);
        let marker = if pa.writable { "rw" } else { "ro" };
        if pa.path.is_dir() {
            // Directory access needs both:
            // - literal: the directory node itself (open/stat on root)
            // - subpath: descendants inside the directory
            policy.push_str(&format!(
                "    (literal \"{}\")  ; ({}) dir root\n",
                path.display(),
                marker
            ));
            policy.push_str(&format!(
                "    (subpath \"{}\")  ; ({}) dir tree\n",
                path.display(),
                marker
            ));
        } else {
            policy.push_str(&format!(
                "    (literal \"{}\")  ; ({})\n",
                path.display(),
                marker
            ));
        }
    }

    policy.push_str(")\n");
    policy
}

/// Generate dynamic file-write policy for writable paths only.
fn build_dynamic_write_paths(paths: &[PathAccess]) -> String {
    let mut policy = String::from("; Dynamic write paths\n(allow file-write*\n");

    for pa in paths.iter().filter(|p| p.writable) {
        let path = canonicalize_or_original(&pa.path);
        if pa.path.is_dir() {
            // See read policy rationale: allow both directory root and descendants.
            policy.push_str(&format!(
                "    (literal \"{}\")  ; writable dir root\n",
                path.display()
            ));
            policy.push_str(&format!(
                "    (subpath \"{}\")  ; writable dir tree\n",
                path.display()
            ));
        } else {
            policy.push_str(&format!(
                "    (literal \"{}\")  ; writable\n",
                path.display()
            ));
        }
    }

    policy.push_str(")\n");
    policy
}

// ============================================================================
// Utilities (private)
// ============================================================================

/// Canonicalize a path, falling back to the original if canonicalization fails.
fn canonicalize_or_original(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

/// Get the Darwin user cache directory using confstr.
fn darwin_user_cache_dir() -> Option<PathBuf> {
    let mut buf = vec![0_i8; (libc::PATH_MAX as usize) + 1];
    let len =
        unsafe { libc::confstr(libc::_CS_DARWIN_USER_CACHE_DIR, buf.as_mut_ptr(), buf.len()) };
    if len == 0 {
        return None;
    }
    let cstr = unsafe { CStr::from_ptr(buf.as_ptr()) };
    cstr.to_str()
        .ok()
        .map(PathBuf::from)
        .and_then(|p| p.canonicalize().ok().or(Some(p)))
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_sandbox_exec_path_is_absolute() {
        assert!(SANDBOX_EXEC_PATH.starts_with('/'));
        assert_eq!(SANDBOX_EXEC_PATH, "/usr/bin/sandbox-exec");
    }

    #[test]
    fn test_sandbox_available() {
        // sandbox-exec should be available on macOS
        #[cfg(target_os = "macos")]
        assert!(
            is_sandbox_available(),
            "sandbox-exec should be available on macOS"
        );
    }

    #[test]
    fn test_base_policy_is_valid_sbpl() {
        assert!(SEATBELT_BASE_POLICY.contains("(version 1)"));
        assert!(SEATBELT_BASE_POLICY.contains("(deny default)"));
        assert!(SEATBELT_BASE_POLICY.contains("(allow process-exec)"));
        assert!(SEATBELT_BASE_POLICY.contains("(allow process-fork)"));
        assert!(SEATBELT_BASE_POLICY.contains("(allow process-info* (target same-sandbox))"));
        assert!(
            SEATBELT_BASE_POLICY.contains("(iokit-registry-entry-class \"RootDomainUserClient\")")
        );
        assert!(
            SEATBELT_BASE_POLICY.contains("com.apple.system.opendirectoryd.libinfo"),
            "Base policy must allow OpenDirectory lookup"
        );
        assert!(
            SEATBELT_BASE_POLICY.contains("com.apple.PowerManagement.control"),
            "Base policy must allow power management lookup"
        );
        assert!(
            SEATBELT_BASE_POLICY.contains("com.apple.logd"),
            "Base policy must allow logd lookup for runtime logging"
        );
        assert!(
            SEATBELT_BASE_POLICY.contains("com.apple.system.notification_center"),
            "Base policy must allow notification center lookup used by macOS runtime components"
        );
        assert!(
            SEATBELT_BASE_POLICY.contains("(allow sysctl-read"),
            "Base policy must include a sysctl allowlist"
        );
    }

    #[test]
    fn test_network_policy_structure() {
        assert!(SEATBELT_NETWORK_POLICY.contains("(allow network-outbound)"));
        assert!(SEATBELT_NETWORK_POLICY.contains("(allow network-inbound)"));
        assert!(SEATBELT_NETWORK_POLICY.contains("DARWIN_USER_CACHE_DIR"));
    }

    #[test]
    fn test_get_sandbox_args_uses_hardcoded_path() {
        let paths = vec![PathAccess {
            path: PathBuf::from("/tmp/test/boxes/test-box"),
            writable: true,
        }];
        let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");

        let (cmd, _args) = build_sandbox_exec_args(&paths, &binary_path, true, None);

        assert_eq!(cmd, "/usr/bin/sandbox-exec");
    }

    #[test]
    fn test_canonicalize_handles_nonexistent() {
        let nonexistent = Path::new("/this/does/not/exist");
        let result = canonicalize_or_original(nonexistent);
        assert_eq!(result, nonexistent);
    }

    #[test]
    fn test_build_policy_includes_network_when_enabled() {
        let paths = vec![PathAccess {
            path: PathBuf::from("/tmp/test/boxes/test-box"),
            writable: true,
        }];
        let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");

        let policy = build_sandbox_policy(&paths, &binary_path, true);

        assert!(policy.contains("(allow network-outbound)"));
    }

    #[test]
    fn test_build_policy_excludes_network_when_disabled() {
        let paths = vec![PathAccess {
            path: PathBuf::from("/tmp/test/boxes/test-box"),
            writable: true,
        }];
        let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");

        let policy = build_sandbox_policy(&paths, &binary_path, false);

        assert!(!policy.contains("(allow network-outbound)"));
        assert!(policy.contains("Network disabled"));
    }

    #[test]
    fn test_file_read_policy_structure() {
        assert!(SEATBELT_FILE_READ_POLICY.contains("(subpath \"/usr/lib\")"));
        assert!(SEATBELT_FILE_READ_POLICY.contains("(subpath \"/System/Library\")"));
        assert!(SEATBELT_FILE_READ_POLICY.contains("(literal \"/tmp\")"));
        assert!(SEATBELT_FILE_READ_POLICY.contains("(literal \"/dev/null\")"));
        assert!(!SEATBELT_FILE_READ_POLICY.contains("(subpath \"/usr\")"));
    }

    #[test]
    fn test_file_write_policy_structure() {
        assert!(SEATBELT_FILE_WRITE_POLICY.contains("(subpath \"/private/tmp\")"));
        assert!(SEATBELT_FILE_WRITE_POLICY.contains("(subpath \"/private/var/tmp\")"));
    }

    #[test]
    fn test_dynamic_read_paths_empty() {
        let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");
        let policy = build_dynamic_read_paths(&binary_path, &[]);

        assert!(policy.contains("(allow file-read*"));
        assert!(policy.contains("/usr/local/bin"));
    }

    #[test]
    fn test_dynamic_read_paths_with_paths() {
        let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");
        let paths = vec![
            PathAccess {
                path: PathBuf::from("/data/input"),
                writable: false,
            },
            PathAccess {
                path: PathBuf::from("/data/output"),
                writable: true,
            },
        ];

        let policy = build_dynamic_read_paths(&binary_path, &paths);

        assert!(policy.contains("/usr/local/bin"));
        assert!(policy.contains("/data/input"));
        assert!(policy.contains("/data/output"));
        assert!(policy.contains("(allow file-read*"));
        assert!(policy.contains("(ro)"));
        assert!(policy.contains("(rw)"));
    }

    #[test]
    fn test_dynamic_write_paths_only_writable() {
        let paths = vec![
            PathAccess {
                path: PathBuf::from("/data/input"),
                writable: false,
            },
            PathAccess {
                path: PathBuf::from("/data/output"),
                writable: true,
            },
            PathAccess {
                path: PathBuf::from("/tmp/test/boxes/test-box"),
                writable: true,
            },
        ];

        let policy = build_dynamic_write_paths(&paths);

        assert!(!policy.contains("/data/input"));
        assert!(policy.contains("/data/output"));
        assert!(policy.contains("boxes/test-box"));
    }

    #[test]
    fn test_policy_no_blanket_system_paths() {
        let paths = vec![PathAccess {
            path: PathBuf::from("/tmp/boxes/test"),
            writable: true,
        }];
        let binary_path = PathBuf::from("/tmp/test/boxlite-shim");

        let policy = build_sandbox_policy(&paths, &binary_path, false);

        assert!(
            !policy.contains("(subpath \"/usr\")"),
            "Should not allow entire /usr"
        );
        assert!(
            !policy.contains("(subpath \"/System\")"),
            "Should not allow entire /System"
        );
        assert!(policy.contains("(subpath \"/usr/lib\")"));
        assert!(policy.contains("(subpath \"/System/Library\")"));
        assert!(policy.contains("/tmp/test"));
    }

    #[test]
    fn test_dynamic_paths_file_vs_dir_sbpl_rule() {
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let box_dir = dir.path();

        // Create a real directory and a real file
        let rw_dir = box_dir.join("sockets");
        std::fs::create_dir_all(&rw_dir).unwrap();
        let rw_file = box_dir.join("exit");
        std::fs::File::create(&rw_file).unwrap();

        let paths = vec![
            PathAccess {
                path: rw_dir.clone(),
                writable: true,
            },
            PathAccess {
                path: rw_file.clone(),
                writable: true,
            },
        ];
        let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");

        let read_policy = build_dynamic_read_paths(&binary_path, &paths);
        let write_policy = build_dynamic_write_paths(&paths);

        // Directories should use (subpath ...)
        assert!(
            read_policy.contains("(subpath"),
            "Dirs should use (subpath) in read policy"
        );
        // Files should use (literal ...)
        assert!(
            read_policy.contains("(literal"),
            "Files should use (literal) in read policy"
        );
        assert!(
            write_policy.contains("(subpath"),
            "Dirs should use (subpath) in write policy"
        );
        assert!(
            write_policy.contains("(literal"),
            "Files should use (literal) in write policy"
        );
    }

    #[test]
    fn test_dynamic_read_paths_do_not_include_parent_traversal_literals() {
        let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");
        let dir = tempfile::tempdir().unwrap();
        let shared_dir = dir.path().join("case/boxes/box-1/shared");
        std::fs::create_dir_all(&shared_dir).unwrap();
        let shared_dir = canonicalize_or_original(&shared_dir);
        let box_dir = shared_dir.parent().unwrap();
        let boxes_dir = box_dir.parent().unwrap();
        let case_dir = boxes_dir.parent().unwrap();

        let paths = vec![PathAccess {
            path: shared_dir.clone(),
            writable: true,
        }];

        let policy = build_dynamic_read_paths(&binary_path, &paths);

        // Dynamic read policy should include explicit target path grants.
        assert!(
            policy.contains(&format!("(literal \"{}\")", shared_dir.display())),
            "Expected target directory literal grant: {policy}"
        );
        assert!(
            policy.contains(&format!("(subpath \"{}\")", shared_dir.display())),
            "Expected target directory subpath grant: {policy}"
        );

        // Parent traversal literals are intentionally omitted.
        assert!(
            !policy.contains(&format!("(literal \"{}\")", box_dir.display())),
            "Did not expect parent traversal literal for box directory: {policy}"
        );
        assert!(
            !policy.contains(&format!("(literal \"{}\")", boxes_dir.display())),
            "Did not expect parent traversal literal for boxes directory: {policy}"
        );
        assert!(
            !policy.contains(&format!("(literal \"{}\")", case_dir.display())),
            "Did not expect parent traversal literal for case directory: {policy}"
        );
    }

    #[test]
    fn test_seatbelt_sandbox_name() {
        let sandbox = SeatbeltSandbox::new();
        assert_eq!(sandbox.name(), "seatbelt");
    }

    /// Empty path list must produce a valid SBPL write policy with no grants.
    #[test]
    fn test_dynamic_write_paths_empty_list() {
        let policy = build_dynamic_write_paths(&[]);

        // Must be syntactically valid (has allow block)
        assert!(
            policy.contains("(allow file-write*"),
            "Should contain file-write allow block"
        );
        // Must NOT grant any paths
        assert!(
            !policy.contains("(subpath"),
            "Empty list should have no subpath rules"
        );
        assert!(
            !policy.contains("(literal"),
            "Empty list should have no literal rules"
        );
    }

    /// Nonexistent paths must use (literal ...) — the most restrictive rule.
    /// A nonexistent path is never treated as a directory (which would grant
    /// access to all children via subpath).
    #[test]
    fn test_seatbelt_nonexistent_path_uses_literal() {
        let paths = vec![PathAccess {
            path: PathBuf::from("/nonexistent/sandbox/path"),
            writable: true,
        }];

        let binary_path = PathBuf::from("/usr/local/bin/boxlite-shim");

        let read_policy = build_dynamic_read_paths(&binary_path, &paths);
        let write_policy = build_dynamic_write_paths(&paths);

        // Nonexistent path → is_dir() returns false → must use (literal)
        assert!(
            read_policy.contains("(literal \"/nonexistent/sandbox/path\")"),
            "Nonexistent path should use (literal) in read policy: {}",
            read_policy
        );
        assert!(
            write_policy.contains("(literal \"/nonexistent/sandbox/path\")"),
            "Nonexistent path should use (literal) in write policy: {}",
            write_policy
        );
    }

    /// Full sandbox policy generated from build_path_access must NOT contain
    /// the mounts_dir path string anywhere.
    #[test]
    fn test_seatbelt_policy_excludes_mounts_dir() {
        use crate::runtime::layout::{BoxFilesystemLayout, FsLayoutConfig};
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let layout = BoxFilesystemLayout::new(
            dir.path().to_path_buf(),
            FsLayoutConfig::with_bind_mount(),
            true,
        );
        let mounts_base = layout.shared_layout().base().to_path_buf();

        // Create mounts_dir on disk (it exists but should be excluded)
        std::fs::create_dir_all(&mounts_base).unwrap();
        // Also create dirs that SHOULD appear
        std::fs::create_dir_all(layout.sockets_dir()).unwrap();
        std::fs::create_dir_all(layout.logs_dir()).unwrap();

        let paths = crate::jailer::build_path_access(&layout, &[]);
        let binary = PathBuf::from("/usr/local/bin/boxlite-shim");
        let policy = build_sandbox_policy(&paths, &binary, false);

        let mounts_str = mounts_base.to_string_lossy().to_string();
        assert!(
            !policy.contains(&mounts_str),
            "mounts_dir path must not appear anywhere in sandbox policy\nmounts_dir={}\npolicy=\n{}",
            mounts_str,
            policy
        );
    }

    /// Every PathAccess entry must appear in the read policy.
    /// Only writable entries should appear in the write policy.
    #[test]
    fn test_seatbelt_policy_read_includes_all_paths() {
        use tempfile::tempdir;

        let dir = tempdir().unwrap();

        // Create a mix of RO dirs, RW dirs, and RW files
        let ro_dir = dir.path().join("bin");
        let rw_dir = dir.path().join("sockets");
        let rw_file = dir.path().join("exit");
        std::fs::create_dir_all(&ro_dir).unwrap();
        std::fs::create_dir_all(&rw_dir).unwrap();
        std::fs::File::create(&rw_file).unwrap();

        let paths = vec![
            PathAccess {
                path: ro_dir.clone(),
                writable: false,
            },
            PathAccess {
                path: rw_dir.clone(),
                writable: true,
            },
            PathAccess {
                path: rw_file.clone(),
                writable: true,
            },
        ];

        let binary = PathBuf::from("/usr/local/bin/boxlite-shim");
        let read_policy = build_dynamic_read_paths(&binary, &paths);
        let write_policy = build_dynamic_write_paths(&paths);

        // All paths should appear in read policy
        for pa in &paths {
            let path_str = pa.path.to_string_lossy();
            assert!(
                read_policy.contains(path_str.as_ref()),
                "Read policy should contain {}",
                path_str
            );
        }

        // Only writable paths should appear in write policy
        assert!(
            write_policy.contains(rw_dir.to_string_lossy().as_ref()),
            "Write policy should contain writable dir"
        );
        assert!(
            write_policy.contains(rw_file.to_string_lossy().as_ref()),
            "Write policy should contain writable file"
        );
        assert!(
            !write_policy.contains(ro_dir.to_string_lossy().as_ref()),
            "Write policy should NOT contain read-only dir"
        );
    }

    #[cfg(target_os = "macos")]
    fn run_sandboxed_sh(
        paths: &[PathAccess],
        shell_snippet: &str,
        arg: &std::path::Path,
    ) -> std::process::Output {
        let (sandbox_cmd, sandbox_args) =
            build_sandbox_exec_args(paths, std::path::Path::new("/bin/sh"), false, None);
        std::process::Command::new(sandbox_cmd)
            .args(sandbox_args)
            .arg("/bin/sh")
            .arg("-c")
            .arg(shell_snippet)
            .arg("sh")
            .arg(arg)
            .output()
            .expect("Failed to execute sandboxed shell command")
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_seatbelt_runtime_allows_write_to_writable_path() {
        if !is_sandbox_available() {
            eprintln!("Skipping: sandbox-exec not available");
            return;
        }

        let cwd = std::env::current_dir().expect("cwd");
        let dir = tempfile::tempdir_in(cwd).expect("tempdir in workspace");
        let allowed_dir = dir.path().join("allowed");
        std::fs::create_dir_all(&allowed_dir).expect("create allowed dir");
        let allowed_file = allowed_dir.join("ok.txt");

        let paths = vec![PathAccess {
            path: allowed_dir.clone(),
            writable: true,
        }];

        let output = run_sandboxed_sh(&paths, "echo ok > \"$1\"", &allowed_file);
        assert!(
            output.status.success(),
            "Expected write to allowed path to succeed, stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let written = std::fs::read_to_string(&allowed_file).expect("read allowed file");
        assert_eq!(written, "ok\n");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_seatbelt_runtime_allows_exec_from_tmp_dynamic_path() {
        if !is_sandbox_available() {
            eprintln!("Skipping: sandbox-exec not available");
            return;
        }

        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir_in("/tmp").expect("tempdir in /tmp");
        let script_path = dir.path().join("probe.sh");
        std::fs::write(&script_path, "#!/bin/sh\necho tmp-exec-ok\n").expect("write /tmp script");
        std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755))
            .expect("set exec bit");

        let paths = vec![PathAccess {
            path: dir.path().to_path_buf(),
            writable: false,
        }];

        let (sandbox_cmd, sandbox_args) =
            build_sandbox_exec_args(&paths, std::path::Path::new("/bin/sh"), false, None);
        let output = std::process::Command::new(sandbox_cmd)
            .args(sandbox_args)
            .arg("/bin/sh")
            .arg(&script_path)
            .output()
            .expect("Failed to execute sandboxed /tmp script");
        assert!(
            output.status.success(),
            "Expected /tmp script exec to succeed, stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(String::from_utf8_lossy(&output.stdout), "tmp-exec-ok\n");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_seatbelt_runtime_denies_write_outside_writable_path() {
        if !is_sandbox_available() {
            eprintln!("Skipping: sandbox-exec not available");
            return;
        }

        let cwd = std::env::current_dir().expect("cwd");
        let dir = tempfile::tempdir_in(cwd).expect("tempdir in workspace");
        let allowed_dir = dir.path().join("allowed");
        std::fs::create_dir_all(&allowed_dir).expect("create allowed dir");
        let blocked_file = dir.path().join("blocked.txt");

        let paths = vec![PathAccess {
            path: allowed_dir,
            writable: true,
        }];

        let output = run_sandboxed_sh(&paths, "echo blocked > \"$1\"", &blocked_file);
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            !output.status.success(),
            "Expected write outside allowlist to fail"
        );
        assert!(
            stderr.contains("Operation not permitted"),
            "Expected sandbox denial, got stderr: {}",
            stderr
        );
        assert!(
            !blocked_file.exists(),
            "Blocked file must not be created outside writable allowlist"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_seatbelt_runtime_denies_read_outside_allowlist() {
        if !is_sandbox_available() {
            eprintln!("Skipping: sandbox-exec not available");
            return;
        }

        let cwd = std::env::current_dir().expect("cwd");
        let dir = tempfile::tempdir_in(cwd).expect("tempdir in workspace");
        let allowed_dir = dir.path().join("allowed");
        std::fs::create_dir_all(&allowed_dir).expect("create allowed dir");
        let blocked_file = dir.path().join("secret.txt");
        std::fs::write(&blocked_file, "secret").expect("write blocked file");

        let paths = vec![PathAccess {
            path: allowed_dir,
            writable: true,
        }];

        let output = run_sandboxed_sh(&paths, "cat \"$1\" >/dev/null", &blocked_file);
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            !output.status.success(),
            "Expected read outside allowlist to fail"
        );
        assert!(
            stderr.contains("Operation not permitted"),
            "Expected sandbox denial, got stderr: {}",
            stderr
        );
    }
}