mermaid-runtime 0.30.0

Daemon-safe runtime core for Mermaid
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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
//! Optional OS sandboxing for model-driven shell commands.
//!
//! Two independent confinement dimensions, one platform-neutral facade:
//!
//! - A **network kill-switch** (`--no-network` / `safety.network = "deny"`).
//!   Linux: a seccomp-BPF filter — creating an internet socket (`AF_INET` /
//!   `AF_INET6`) dies with `SIGSYS`, while `AF_UNIX` and other local socket
//!   domains keep working so nscd / D-Bus / X11 are unaffected. `SIGSYS` is a
//!   distinctive, catchable signal, which the exec tool maps to a clear
//!   "blocked by the network sandbox" outcome. macOS: a Seatbelt
//!   `(deny network*)` sparing `AF_UNIX`, denied at use time with `EPERM`
//!   (no signal — detection is a hedged text signature).
//! - A **filesystem write-confinement** (`--confine-fs` /
//!   `safety.filesystem = "project"`). Write-class access (create / write /
//!   truncate / remove / rename) is allowed only beneath an explicit set of
//!   directories; everything else fails with a permission error. Reads and
//!   execution stay unrestricted. Linux: Landlock, best-effort by design — a
//!   kernel without it (pre-5.13) degrades to a warned no-op rather than
//!   refusing to run. macOS: Seatbelt `deny file-write*` outside the roots.
//!
//! Everything funnels through [`enforce`], called from the
//! `mermaid __sandbox-exec` launcher — ordinary, single-threaded code — just
//! before it runs the real command. On Linux the restrictions are applied to
//! the launcher itself ([`Enforcement::SelfApplied`]) and survive `execve` and
//! `fork`; on macOS the argv is rewritten to run under `/usr/bin/sandbox-exec`
//! ([`Enforcement::ExecArgv`]), whose profile is likewise inherited by
//! everything the command spawns. Platforms without a backend return `Err`
//! when confinement was requested, so the launcher fails closed (exit 126)
//! instead of ever running the command unconfined.
//!
//! A third, fixed policy backs `read_only` mode: [`enforce_read_only`] denies
//! writes, sockets, IPC, outward signals and privileges all at once, so a
//! command runs read-only because the kernel says so rather than because a
//! parser predicted it would.

use std::ffi::OsString;
use std::path::PathBuf;

/// What the caller asked the OS to confine. Both dimensions are independent;
/// an all-off policy enforces nothing (and [`enforce`] is a no-op for it on
/// every platform).
#[derive(Debug, Clone, Default)]
pub struct SandboxPolicy {
    /// Deny network access (internet sockets; local `AF_UNIX` is spared).
    pub deny_network: bool,
    /// `Some` confines write-class filesystem access to (beneath) these
    /// directories; `None` leaves writes unrestricted. Roots that don't exist
    /// are skipped, narrowing the sandbox rather than erroring.
    ///
    /// The `Option` is load-bearing: `Some(vec![])` means "confine writes to
    /// nowhere" (deny every write) and MUST NOT be read as "no confinement
    /// requested". A plain `Vec` could not tell those apart, and the
    /// all-off short-circuit in [`enforce`] then ran the command unconfined
    /// while reporting `fs_enforced: true`.
    pub confine_writes: Option<Vec<PathBuf>>,
}

/// How the platform enforced a [`SandboxPolicy`] — the contract between
/// [`enforce`] and the `__sandbox-exec` launcher.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Enforcement {
    /// The restrictions were installed on the *current* process (Linux
    /// seccomp + Landlock); the caller must now exec its own argv.
    /// `fs_enforced` is `false` when write-confinement was requested but the
    /// kernel cannot enforce it (documented best-effort — the caller warns
    /// and continues).
    SelfApplied { fs_enforced: bool },
    /// The caller must exec this rewritten argv instead (macOS: the command
    /// wrapped in `/usr/bin/sandbox-exec`).
    ExecArgv(Vec<OsString>),
    /// The platform ran the child itself and this is its exit code
    /// (Windows AppContainer follow-up; no constructor yet).
    Ran(i32),
}

/// Enforce `policy` for the command `argv`. Called from single-threaded
/// launcher code. Any `Err` means the requested confinement could not be
/// applied — the caller MUST fail closed (exit 126), never run unconfined.
///
/// # Errors
///
/// The platform refusing to install a *requested* restriction: on Linux a
/// Landlock or seccomp setup failure, on macOS a profile that
/// `sandbox-exec` will not take. An empty policy is `Ok` everywhere, and a
/// kernel too old for write-confinement is `Ok` with `fs_enforced: false`
/// rather than an error — that one case is the documented best-effort, and it
/// is why `Ok` alone is not proof the filesystem is confined.
pub fn enforce(policy: &SandboxPolicy, argv: &[OsString]) -> anyhow::Result<Enforcement> {
    if !policy.deny_network && policy.confine_writes.is_none() {
        // Nothing requested: nothing to enforce, on any platform.
        return Ok(Enforcement::SelfApplied { fs_enforced: true });
    }
    #[cfg(target_os = "linux")]
    {
        use anyhow::Context as _;
        // Self-applied: the caller execs its own argv afterwards.
        let _ = argv;
        // Landlock first (its setup opens the allowed dirs), then seccomp.
        let mut fs_enforced = true;
        if let Some(roots) = &policy.confine_writes {
            // An empty `roots` installs a write-handling ruleset with no allow
            // rules, i.e. every write is denied. That is the intended reading
            // of `Some(vec![])`, not a no-op.
            fs_enforced =
                linux::apply_fs_confinement(roots).context("filesystem sandbox unavailable")?;
        }
        if policy.deny_network {
            linux::apply_network_killswitch().context("network sandbox unavailable")?;
        }
        Ok(Enforcement::SelfApplied { fs_enforced })
    }
    #[cfg(target_os = "macos")]
    {
        anyhow::ensure!(
            macos::sandbox_exec_present(),
            "{} not found; refusing to run the command unconfined",
            macos::SANDBOX_EXEC
        );
        Ok(Enforcement::ExecArgv(macos::wrap_argv(policy, argv)))
    }
    #[cfg(target_os = "windows")]
    {
        use anyhow::Context as _;
        anyhow::ensure!(
            windows::appcontainer_available(),
            "Windows AppContainer is unavailable on this system; refusing to run unconfined"
        );
        let exit_code = windows::run_in_appcontainer(policy, argv)
            .context("Windows AppContainer sandbox execution failed")?;
        Ok(Enforcement::Ran(exit_code))
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        let _ = argv;
        anyhow::bail!("no OS sandbox backend on this platform; refusing to run unconfined")
    }
}

/// Enforce read-only containment for the command `argv`.
///
/// The OS, not a command parser, is what keeps a `read_only`-mode command
/// from changing anything. Called from single-threaded launcher code, like
/// [`enforce`].
///
/// The contract is "the command may read, and nothing else": no filesystem
/// writes (bar the discard and terminal devices a shell redirects to), no
/// metadata changes, no sockets of any family (so no network and no local
/// daemons such as Docker, D-Bus or a database socket), no System V or POSIX
/// IPC, no signals to processes outside the sandbox, and no capabilities even
/// when run as root. Every part is a hard requirement: unlike `--confine-fs`
/// there is no best-effort degrade, because `read_only` mode lets any command
/// through on the strength of this containment.
///
/// Linux applies it to the launcher itself (Landlock ABI 6, kernel 6.12+,
/// plus seccomp); macOS rewrites the argv onto `sandbox-exec` with a
/// deny-default Seatbelt profile. Windows keeps the shell allowlists until
/// its backend is verified to meet the same contract, so
/// [`read_only_containment_available`] is `false` there.
///
/// # Errors
///
/// The platform cannot install every restriction. The caller MUST fail
/// closed (exit 126), never run the command unconfined.
pub fn enforce_read_only(argv: &[OsString]) -> anyhow::Result<Enforcement> {
    #[cfg(target_os = "linux")]
    {
        // Self-applied: the caller execs its own argv afterwards.
        let _ = argv;
        linux::apply_read_only()?;
        Ok(Enforcement::SelfApplied { fs_enforced: true })
    }
    #[cfg(target_os = "macos")]
    {
        anyhow::ensure!(
            macos::sandbox_exec_present(),
            "{} not found; refusing to run the command unconfined",
            macos::SANDBOX_EXEC
        );
        Ok(Enforcement::ExecArgv(macos::wrap_read_only_argv(argv)))
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        let _ = argv;
        anyhow::bail!("read-only containment is not available on this platform")
    }
}

/// Whether [`enforce_read_only`] can succeed here.
///
/// On Linux, the kernel must support Landlock ABI 6 (write rights plus
/// signal scoping) and both seccomp filters must assemble; that probe creates
/// a ruleset fd and drops it, restricting nothing. On macOS, `sandbox-exec`
/// must accept the read-only profile and run a shell under it; that probe
/// spawns one short-lived process, so callers cache the answer. `false`
/// everywhere else. `read_only` mode lets arbitrary shell commands run only
/// when this is `true`, and falls back to the shell allowlists otherwise.
#[must_use]
pub fn read_only_containment_available() -> bool {
    #[cfg(target_os = "linux")]
    {
        linux::read_only_supported()
    }
    #[cfg(target_os = "macos")]
    {
        macos::read_only_supported()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        false
    }
}

/// Whether the network kill-switch is really available on this platform:
/// Linux when the seccomp filter assembles (supported arch), macOS when
/// `/usr/bin/sandbox-exec` exists, Windows when AppContainer is supported.
/// Used by `mermaid self-test` and the exec tool as a safe, fork-free probe —
/// it installs nothing.
#[must_use]
pub fn network_killswitch_available() -> bool {
    #[cfg(target_os = "linux")]
    {
        linux::network_filter().is_ok()
    }
    #[cfg(target_os = "macos")]
    {
        macos::sandbox_exec_present()
    }
    #[cfg(target_os = "windows")]
    {
        windows::appcontainer_available()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        false
    }
}

/// Whether filesystem write-confinement is really available on this platform:
/// Linux when the Landlock ruleset assembles, macOS when
/// `/usr/bin/sandbox-exec` exists, Windows when AppContainer is supported.
/// Like [`network_killswitch_available`]: a safe probe that restricts nothing.
/// (On Linux enforcement remains best-effort at apply time — a pre-Landlock
/// kernel builds the ruleset but cannot enforce it.)
#[must_use]
pub fn fs_confinement_available() -> bool {
    #[cfg(target_os = "linux")]
    {
        linux::fs_ruleset_builds()
    }
    #[cfg(target_os = "macos")]
    {
        macos::sandbox_exec_present()
    }
    #[cfg(target_os = "windows")]
    {
        windows::appcontainer_available()
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        false
    }
}

#[cfg(target_os = "windows")]
mod windows;

/// macOS Seatbelt backend: generate an allow-default SBPL profile and rewrite
/// the command argv to run under `/usr/bin/sandbox-exec`.
///
/// Profile generation and argv rewriting are PURE functions, compiled (and
/// unit-tested) on every platform — only [`enforce`] reaches them at runtime,
/// and only on macOS. Security invariant: no caller-controlled path is ever
/// spliced into the profile string; paths travel exclusively through `-D`
/// parameters that the profile references as `(param "WRn")`, so a hostile
/// directory name cannot inject SBPL.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
mod macos {
    use std::ffi::OsString;
    use std::path::{Path, PathBuf};

    use super::SandboxPolicy;

    /// Fixed, absolute path — deliberately not resolved via `PATH`.
    pub(super) const SANDBOX_EXEC: &str = "/usr/bin/sandbox-exec";

    pub(super) fn sandbox_exec_present() -> bool {
        Path::new(SANDBOX_EXEC).exists()
    }

    /// Build the SBPL profile for `policy`, plus the `-D` parameters it
    /// references (name → path). Allow-default so toolchains keep working;
    /// only the requested dimensions are denied.
    ///
    /// Each existing allowed root yields a literal param (`WRn`) and, when it
    /// differs, a canonicalized one (`WRnC`): on macOS `TMPDIR` lives under
    /// the `/var` firmlink while Seatbelt sees `/private/var`, so matching on
    /// only one form would deny legitimate temp writes (or under-match).
    /// Nonexistent roots are skipped — parity with Landlock's
    /// `path_beneath_rules`, which silently narrows the sandbox for paths it
    /// cannot open.
    pub(super) fn profile(policy: &SandboxPolicy) -> (String, Vec<(String, PathBuf)>) {
        let mut sbpl = String::from("(version 1)\n(allow default)\n");
        if policy.deny_network {
            // Deny all network, then re-allow AF_UNIX sockets (later SBPL
            // rules win) — parity with the Linux seccomp filter, which only
            // kills AF_INET/AF_INET6 so D-Bus/nscd-style local IPC survives.
            // If macOS ever rejects this filter grammar, the CI
            // profile-compile canary fails loudly; the fallback is deleting
            // the two `allow` lines (stricter than Linux, documented delta).
            sbpl.push_str("(deny network*)\n");
            sbpl.push_str("(allow network* (remote unix))\n");
            sbpl.push_str("(allow network* (local unix))\n");
        }
        let mut params: Vec<(String, PathBuf)> = Vec::new();
        if let Some(roots) = &policy.confine_writes {
            for (n, root) in roots.iter().enumerate() {
                if !root.exists() {
                    continue;
                }
                params.push((format!("WR{n}"), root.clone()));
                if let Ok(canonical) = std::fs::canonicalize(root)
                    && canonical != *root
                {
                    params.push((format!("WR{n}C"), canonical));
                }
            }
            if params.is_empty() {
                // Confinement was requested but every allowed root is missing
                // (or the list was empty): deny all writes (Landlock parity —
                // missing dirs narrow the sandbox) rather than emit an empty
                // require-all.
                sbpl.push_str("(deny file-write*)\n");
            } else {
                // FOOTGUN: the require-nots MUST be wrapped in `require-all`.
                // A bare filter list ORs its members, and "not under root A
                // OR not under root B" is true for every path once there are
                // two roots — denying ALL writes. `require-all` makes it
                // "outside every allowed root", which is the intent.
                sbpl.push_str("(deny file-write* (require-all");
                for (name, _) in &params {
                    // Param NAMES are generated here (WRn/WRnC, never from
                    // input); path VALUES ride the -D argv, not this string.
                    sbpl.push_str(&format!(" (require-not (subpath (param \"{name}\")))"));
                }
                sbpl.push_str("))\n");
            }
        }
        (sbpl, params)
    }

    /// The Seatbelt profile behind `read_only` mode. Deny-default, the shape
    /// of Chromium's and Apple's own App Sandbox, rather than the
    /// allow-default profile above: on macOS a file-write deny alone is not
    /// read-only, because Mach IPC lets a command change state through a
    /// daemon without writing a file itself (`launchctl`, Apple Events to
    /// another app). So everything is refused unless listed:
    ///
    /// - running programs, and signals only to processes in this sandbox;
    /// - every read, including sysctls and the command's own process info;
    /// - the Mach services reads need: user and group lookups, and the
    ///   preferences daemon, which itself refuses writes from a sandbox that
    ///   lacks `user-preference-write` (the integration suite checks that a
    ///   `defaults write` fails);
    /// - writing to the discard devices and the command's terminal, and the
    ///   terminal `ioctl`s a shell uses to see that it has one.
    ///
    /// Not listed, so denied: every other write (data, metadata, xattrs,
    /// times), all networking including unix sockets, other Mach services,
    /// Apple Events, IPC, and `IOKit`. Constant: no path or other input is ever
    /// spliced in.
    pub(super) const READ_ONLY_PROFILE: &str = r#"(version 1)
(deny default)
(allow process-exec)
(allow process-fork)
(allow process-info* (target same-sandbox))
(allow signal (target same-sandbox))
(allow file-read*)
(allow sysctl-read)
(allow mach-lookup
  (global-name "com.apple.system.opendirectoryd.libinfo")
  (global-name "com.apple.cfprefsd.daemon")
  (global-name "com.apple.cfprefsd.agent"))
(allow user-preference-read)
(allow file-write-data
  (literal "/dev/null")
  (literal "/dev/zero")
  (literal "/dev/tty")
  (regex #"^/dev/ttys[0-9]+$"))
(allow file-ioctl
  (literal "/dev/tty")
  (regex #"^/dev/ttys[0-9]+$"))
"#;

    /// Rewrite `argv` to run under `sandbox-exec` with the read-only profile:
    /// `/usr/bin/sandbox-exec -p <profile> -- <argv...>`.
    pub(super) fn wrap_read_only_argv(argv: &[OsString]) -> Vec<OsString> {
        let mut wrapped: Vec<OsString> = vec![
            SANDBOX_EXEC.into(),
            "-p".into(),
            READ_ONLY_PROFILE.into(),
            "--".into(),
        ];
        wrapped.extend(argv.iter().cloned());
        wrapped
    }

    /// Whether `sandbox-exec` takes the read-only profile and a shell runs
    /// under it. Checked by running `/bin/sh -c :` confined, because a
    /// profile this macOS rejects, or one a shell cannot start under, would
    /// otherwise fail every command in `read_only` mode instead of falling
    /// back to the allowlists.
    pub(super) fn read_only_supported() -> bool {
        sandbox_exec_present()
            && std::process::Command::new(SANDBOX_EXEC)
                .args(["-p", READ_ONLY_PROFILE, "--", "/bin/sh", "-c", ":"])
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .is_ok_and(|status| status.success())
    }

    /// Rewrite `argv` to run under `sandbox-exec` with the policy's profile:
    /// `/usr/bin/sandbox-exec -p <profile> [-D WRn=<path>]... -- <argv...>`.
    pub(super) fn wrap_argv(policy: &SandboxPolicy, argv: &[OsString]) -> Vec<OsString> {
        let (sbpl, params) = profile(policy);
        let mut wrapped: Vec<OsString> = vec![SANDBOX_EXEC.into(), "-p".into(), sbpl.into()];
        for (name, value) in params {
            wrapped.push("-D".into());
            let mut kv = OsString::from(format!("{name}="));
            kv.push(value.as_os_str());
            wrapped.push(kv);
        }
        // `--` ends option parsing so a command starting with `-` cannot be
        // taken for a sandbox-exec flag.
        wrapped.push("--".into());
        wrapped.extend(argv.iter().cloned());
        wrapped
    }

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

        /// `confine_writes` is deliberately an `Option` here rather than a
        /// slice that collapses empty to "off": `None` is "write confinement
        /// not requested", `Some(&[])` is "confine writes to nowhere" (a
        /// deny-all). Conflating them is the bug this shape exists to prevent.
        fn policy(deny_network: bool, confine_writes: Option<&[PathBuf]>) -> SandboxPolicy {
            SandboxPolicy {
                deny_network,
                confine_writes: confine_writes.map(<[PathBuf]>::to_vec),
            }
        }

        /// A fresh existing directory under the temp dir.
        fn tempdir(tag: &str) -> PathBuf {
            let dir = std::env::temp_dir().join(format!(
                "mermaid-sbpl-test-{tag}-{}-{}",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            ));
            std::fs::create_dir_all(&dir).unwrap();
            dir
        }

        #[test]
        fn network_denial_lines_present_iff_requested() {
            let (with_net, _) = profile(&policy(true, None));
            assert!(with_net.contains("(deny network*)"));
            // AF_UNIX-sparing allows ship with the deny (Linux parity).
            assert!(with_net.contains("(allow network* (remote unix))"));
            assert!(with_net.contains("(allow network* (local unix))"));
            // deny_network-only: no write confinement may leak into the profile.
            assert!(!with_net.contains("file-write"));

            let dir = tempdir("no-net");
            let (without_net, _) = profile(&policy(false, Some(std::slice::from_ref(&dir))));
            assert!(!without_net.contains("network"));
            let _ = std::fs::remove_dir_all(&dir);
        }

        #[test]
        fn empty_confinement_denies_every_write() {
            // `Some(&[])` grants no roots, so the profile must deny writes
            // outright. Reading it as "no confinement requested" — which a
            // bare `Vec` forced — would emit no `file-write` rule at all and
            // leave the command able to write anywhere.
            let (sbpl, params) = profile(&policy(false, Some(&[])));
            assert!(params.is_empty(), "no roots to parameterize: {params:?}");
            assert!(
                sbpl.contains("(deny file-write*)"),
                "an empty allowlist is a deny-all, not a no-op: {sbpl:?}"
            );
        }

        #[test]
        fn write_denial_nests_require_nots_under_require_all() {
            let a = tempdir("ra-a");
            let b = tempdir("ra-b");
            let (sbpl, params) = profile(&policy(false, Some(&[a.clone(), b.clone()])));
            // Both roots exist and are already canonical-ish; at least the
            // two literal params must be present and referenced.
            assert!(params.iter().any(|(n, _)| n == "WR0"));
            assert!(params.iter().any(|(n, _)| n == "WR1"));
            // The require-nots are wrapped in ONE require-all (a bare list
            // would OR and deny everything — see the generator comment).
            let deny = sbpl
                .lines()
                .find(|l| l.starts_with("(deny file-write*"))
                .expect("deny file-write* line");
            assert!(deny.starts_with("(deny file-write* (require-all (require-not"));
            assert_eq!(
                deny.matches("(require-not (subpath (param ").count(),
                params.len(),
                "one require-not per emitted param: {deny}"
            );
            let _ = std::fs::remove_dir_all(&a);
            let _ = std::fs::remove_dir_all(&b);
        }

        #[test]
        fn dual_literal_and_canonical_params_when_they_differ() {
            let real = tempdir("canon");
            let sub = real.join("sub");
            std::fs::create_dir_all(&sub).unwrap();
            // `<real>/sub/..` exists but canonicalizes to `<real>` — a
            // platform-neutral stand-in for the macOS TMPDIR firmlink
            // (/var/... vs /private/var/...).
            let alias = sub.join("..");
            let (sbpl, params) = profile(&policy(false, Some(std::slice::from_ref(&alias))));
            let literal = params.iter().find(|(n, _)| n == "WR0").expect("literal");
            let canonical = params.iter().find(|(n, _)| n == "WR0C").expect("canonical");
            assert_eq!(literal.1, alias);
            assert_ne!(canonical.1, alias);
            assert!(sbpl.contains("(param \"WR0\")"));
            assert!(sbpl.contains("(param \"WR0C\")"));
            let _ = std::fs::remove_dir_all(&real);
        }

        #[test]
        fn nonexistent_roots_are_skipped_and_all_missing_denies_all_writes() {
            let missing = std::env::temp_dir().join("mermaid-sbpl-test-definitely-missing");
            let (sbpl, params) = profile(&policy(false, Some(std::slice::from_ref(&missing))));
            assert!(params.is_empty());
            // No surviving root: plain deny (narrowed sandbox, Landlock
            // parity), not an empty require-all of unknown SBPL validity.
            assert!(sbpl.contains("(deny file-write*)\n"));
            assert!(!sbpl.contains("require-all"));
        }

        #[test]
        fn paths_never_reach_the_profile_string() {
            // A directory name full of SBPL metacharacters must not appear in
            // the profile text — it rides only in the -D parameter values.
            let evil = tempdir("evil").join("x) (allow default) (deny");
            std::fs::create_dir_all(&evil).unwrap();
            let (sbpl, params) = profile(&policy(true, Some(std::slice::from_ref(&evil))));
            assert!(!sbpl.contains("allow default) (deny"));
            assert!(
                params.iter().any(|(_, v)| *v == evil),
                "the path must ride a param instead"
            );
            let _ = std::fs::remove_dir_all(evil.parent().unwrap());
        }

        #[test]
        fn read_only_profile_denies_by_default_and_never_allows_writes_broadly() {
            let profile = READ_ONLY_PROFILE;
            assert!(profile.starts_with("(version 1)\n(deny default)\n"));
            // No network rule at all: deny-default covers every socket.
            assert!(!profile.contains("network"));
            // Writes are granted only as data to named devices, never as the
            // `file-write*` family, which would include metadata and create.
            assert!(!profile.contains("file-write*"));
            assert!(!profile.contains("(allow default)"));
            // Signals and process control stay inside the sandbox.
            assert!(profile.contains("(allow signal (target same-sandbox))"));
            assert!(!profile.contains("appleevent"));
        }

        #[test]
        fn read_only_argv_puts_the_profile_before_the_command() {
            let argv: Vec<OsString> = vec!["sh".into(), "-c".into(), "ls".into()];
            let wrapped = wrap_read_only_argv(&argv);
            assert_eq!(wrapped[0], OsString::from(SANDBOX_EXEC));
            assert_eq!(wrapped[1], OsString::from("-p"));
            assert_eq!(wrapped[2], OsString::from(READ_ONLY_PROFILE));
            assert_eq!(wrapped[3], OsString::from("--"));
            assert_eq!(&wrapped[4..], argv.as_slice());
        }

        #[test]
        fn wrap_argv_shape_is_frozen() {
            let dir = tempdir("argv");
            let argv: Vec<OsString> = vec!["sh".into(), "-c".into(), "echo hi".into()];
            let wrapped = wrap_argv(&policy(true, Some(std::slice::from_ref(&dir))), &argv);
            assert_eq!(wrapped[0], OsString::from(SANDBOX_EXEC));
            assert_eq!(wrapped[1], OsString::from("-p"));
            let profile_arg = wrapped[2].to_string_lossy();
            assert!(profile_arg.starts_with("(version 1)\n(allow default)\n"));
            assert_eq!(wrapped[3], OsString::from("-D"));
            let kv = wrapped[4].to_string_lossy();
            assert!(kv.starts_with("WR0="), "param assignment: {kv}");
            // `--` separates sandbox-exec options from the wrapped command.
            let sep = wrapped
                .iter()
                .position(|a| a == "--")
                .expect("-- separator");
            assert_eq!(&wrapped[sep + 1..], argv.as_slice());
            let _ = std::fs::remove_dir_all(&dir);
        }
    }
}

#[cfg(target_os = "linux")]
mod linux {
    use std::collections::BTreeMap;

    use anyhow::Context;
    use seccompiler::{
        BpfProgram, SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter,
        SeccompRule, apply_filter,
    };

    /// Build the "deny internet sockets" BPF program: kill the process on
    /// `socket(AF_INET|AF_INET6, …)`, allow everything else (including
    /// `AF_UNIX`). Comparing the low 32 bits (`Dword`) of the domain argument is
    /// deliberate — it catches a family smuggled in the high bits, which the
    /// kernel would still truncate to `AF_INET`.
    pub(super) fn network_filter() -> anyhow::Result<BpfProgram> {
        let inet = SeccompRule::new(vec![SeccompCondition::new(
            0,
            SeccompCmpArgLen::Dword,
            SeccompCmpOp::Eq,
            libc::AF_INET as u64,
        )?])?;
        let inet6 = SeccompRule::new(vec![SeccompCondition::new(
            0,
            SeccompCmpArgLen::Dword,
            SeccompCmpOp::Eq,
            libc::AF_INET6 as u64,
        )?])?;

        let mut rules: BTreeMap<i64, Vec<SeccompRule>> = BTreeMap::new();
        rules.insert(libc::SYS_socket, vec![inet, inet6]);

        let filter = SeccompFilter::new(
            rules,
            SeccompAction::Allow,       // syscalls with no matching rule: allow
            SeccompAction::KillProcess, // an inet socket: SIGSYS-kill the process
            std::env::consts::ARCH
                .try_into()
                .context("seccomp: unsupported target arch")?,
        )
        .context("seccomp: build network filter")?;

        let program: BpfProgram = filter.try_into().context("seccomp: assemble network BPF")?;
        Ok(program)
    }

    pub fn apply_network_killswitch() -> anyhow::Result<()> {
        let program = network_filter()?;
        apply_filter(&program).context("seccomp: install network filter")?;
        Ok(())
    }

    /// Landlock ABI the write-confinement targets. V3 (kernel 6.2) rounds out
    /// the write set with `Truncate` on top of V2's `Refer` (cross-directory
    /// rename/link). `CompatLevel::BestEffort` degrades gracefully on older
    /// kernels.
    const LANDLOCK_ABI: landlock::ABI = landlock::ABI::V3;

    /// Build + apply the "writes only beneath these directories" Landlock
    /// ruleset. Only write-class access is handled, so reads and execution stay
    /// unrestricted everywhere. Returns whether the kernel actually enforces.
    pub(super) fn apply_fs_confinement(
        allowed_writes: &[std::path::PathBuf],
    ) -> anyhow::Result<bool> {
        use landlock::{
            AccessFs, CompatLevel, Compatible, Ruleset, RulesetAttr, RulesetCreatedAttr,
            RulesetStatus, path_beneath_rules,
        };

        let write_access = AccessFs::from_write(LANDLOCK_ABI);
        // A rule may not grant directory-only rights (`MakeReg`, `RemoveFile`,
        // …) on a non-directory: the kernel answers `EBADFD`. So an allowed
        // path that is a FILE — `/dev/null` and the other discard devices,
        // which a shell legitimately redirects to — gets the file-applicable
        // subset instead. Granting `/dev` as a hierarchy would avoid the split
        // and also hand out `/dev/sda` and `/dev/mem`, which is the whole
        // reason to name devices individually.
        let file_access = write_access & AccessFs::from_file(LANDLOCK_ABI);
        let (files, dirs): (Vec<_>, Vec<_>) = allowed_writes
            .iter()
            .cloned()
            .partition(|p| p.is_file() || p.symlink_metadata().is_ok_and(|m| !m.is_dir()));
        let status = Ruleset::default()
            .set_compatibility(CompatLevel::BestEffort)
            .handle_access(write_access)
            .context("landlock: handle write access")?
            .create()
            .context("landlock: create ruleset")?
            // `path_beneath_rules` silently skips paths that can't be opened,
            // so a missing allowed dir narrows the sandbox instead of erroring.
            .add_rules(path_beneath_rules(&dirs, write_access))
            .context("landlock: add write rules")?
            .add_rules(path_beneath_rules(&files, file_access))
            .context("landlock: add file write rules")?
            .restrict_self()
            .context("landlock: restrict self")?;
        Ok(status.ruleset != RulesetStatus::NotEnforced)
    }

    /// Whether the confinement ruleset assembles (fork-free `self-test` probe;
    /// creates a ruleset fd and drops it without restricting anything).
    pub(super) fn fs_ruleset_builds() -> bool {
        use landlock::{AccessFs, CompatLevel, Compatible, Ruleset, RulesetAttr};
        Ruleset::default()
            .set_compatibility(CompatLevel::BestEffort)
            .handle_access(AccessFs::from_write(LANDLOCK_ABI))
            .and_then(|r| r.create())
            .is_ok()
    }

    /// Paths a read-only command may still open for writing: the discard
    /// devices a shell redirects to and the terminal it runs on. Each gets the
    /// file-level write rights only, so nothing can be created beneath
    /// `/dev/pts`, only the existing terminals written to.
    const READ_ONLY_WRITABLE: &[&str] = &[
        "/dev/null",
        "/dev/zero",
        "/dev/full",
        "/dev/tty",
        "/dev/ptmx",
        "/dev/pts",
    ];

    // Newer than the `libc` constants, and numbered the same on every arch.
    const SYS_FCHMODAT2: i64 = 452;
    const SYS_SETXATTRAT: i64 = 463;
    const SYS_REMOVEXATTRAT: i64 = 466;

    /// `ioctl` requests that change a file's attributes through a read-only
    /// descriptor (`chattr`): `FS_IOC_SETFLAGS`, its 32-bit form, and
    /// `FS_IOC_FSSETXATTR`. Landlock does not see them.
    const ATTR_SETTING_IOCTLS: &[u64] = &[0x4008_6602, 0x4004_6602, 0x401c_5820];

    /// Syscalls a read-only command is refused outright (`EPERM`), because
    /// each changes state without a filesystem write that Landlock would see:
    /// sockets of every family (the internet ones are also killed by
    /// [`network_filter`], which wins when both match), `io_uring` (which can
    /// open sockets without `socket(2)`), System V and POSIX IPC, the kernel
    /// keyring, and file metadata (mode, owner, extended attributes, times).
    fn read_only_denied_syscalls() -> Vec<i64> {
        let mut denied = legacy_metadata_syscalls();
        denied.extend([
            libc::SYS_socket,
            libc::SYS_io_uring_setup,
            libc::SYS_io_uring_enter,
            libc::SYS_io_uring_register,
            libc::SYS_msgget,
            libc::SYS_msgsnd,
            libc::SYS_msgrcv,
            libc::SYS_msgctl,
            libc::SYS_semget,
            libc::SYS_semop,
            libc::SYS_semtimedop,
            libc::SYS_semctl,
            libc::SYS_shmget,
            libc::SYS_shmat,
            libc::SYS_shmctl,
            libc::SYS_mq_open,
            libc::SYS_mq_unlink,
            libc::SYS_mq_timedsend,
            libc::SYS_mq_timedreceive,
            libc::SYS_mq_notify,
            libc::SYS_mq_getsetattr,
            libc::SYS_add_key,
            libc::SYS_request_key,
            libc::SYS_keyctl,
            libc::SYS_fchmod,
            libc::SYS_fchmodat,
            SYS_FCHMODAT2,
            libc::SYS_fchown,
            libc::SYS_fchownat,
            libc::SYS_setxattr,
            libc::SYS_lsetxattr,
            libc::SYS_fsetxattr,
            libc::SYS_removexattr,
            libc::SYS_lremovexattr,
            libc::SYS_fremovexattr,
            SYS_SETXATTRAT,
            SYS_REMOVEXATTRAT,
            libc::SYS_utimensat,
        ]);
        denied
    }

    /// The legacy path-based metadata syscalls, which only the older syscall
    /// tables have; `aarch64` offers the `*at` forms alone.
    fn legacy_metadata_syscalls() -> Vec<i64> {
        #[cfg(target_arch = "x86_64")]
        {
            vec![
                libc::SYS_chmod,
                libc::SYS_chown,
                libc::SYS_lchown,
                libc::SYS_utime,
                libc::SYS_utimes,
                libc::SYS_futimesat,
            ]
        }
        #[cfg(not(target_arch = "x86_64"))]
        {
            Vec::new()
        }
    }

    /// Refuse the x32 ABI outright (`x86_64` only). x32 reaches the same
    /// syscalls with bit 30 set in the number, under the same audit arch, so
    /// the number-keyed filters here would not see them. Hand-assembled
    /// because `seccompiler` matches exact numbers, not ranges: load the
    /// number, and fail anything at or above the x32 bit with `EPERM`.
    #[cfg(target_arch = "x86_64")]
    fn x32_filter() -> BpfProgram {
        use seccompiler::sock_filter;
        const BPF_LD_W_ABS: u16 = 0x20;
        const BPF_JMP_JGE_K: u16 = 0x35;
        const BPF_RET_K: u16 = 0x06;
        const X32_SYSCALL_BIT: u32 = 0x4000_0000;
        let insn = |code, jt, jf, k| sock_filter { code, jt, jf, k };
        vec![
            // `seccomp_data.nr` is at offset 0.
            insn(BPF_LD_W_ABS, 0, 0, 0),
            insn(BPF_JMP_JGE_K, 0, 1, X32_SYSCALL_BIT),
            insn(
                BPF_RET_K,
                0,
                0,
                libc::SECCOMP_RET_ERRNO | libc::EPERM as u32,
            ),
            insn(BPF_RET_K, 0, 0, libc::SECCOMP_RET_ALLOW),
        ]
    }

    /// Build the read-only seccomp program: every syscall in
    /// [`read_only_denied_syscalls`] and the attribute-setting `ioctl`s fail
    /// with `EPERM`; everything else is allowed. An error rather than a kill,
    /// so a tool that probes (a local socket for a name-service cache, say)
    /// falls back instead of dying.
    pub(super) fn read_only_filter() -> anyhow::Result<BpfProgram> {
        let mut rules: BTreeMap<i64, Vec<SeccompRule>> = read_only_denied_syscalls()
            .into_iter()
            // An empty rule list matches the syscall unconditionally.
            .map(|nr| (nr, Vec::new()))
            .collect();
        let ioctl_rules = ATTR_SETTING_IOCTLS
            .iter()
            .map(|&request| {
                SeccompRule::new(vec![SeccompCondition::new(
                    1,
                    SeccompCmpArgLen::Dword,
                    SeccompCmpOp::Eq,
                    request,
                )?])
            })
            .collect::<Result<Vec<_>, _>>()?;
        rules.insert(libc::SYS_ioctl, ioctl_rules);

        let filter = SeccompFilter::new(
            rules,
            SeccompAction::Allow,
            SeccompAction::Errno(libc::EPERM as u32),
            std::env::consts::ARCH
                .try_into()
                .context("seccomp: unsupported target arch")?,
        )
        .context("seccomp: build read-only filter")?;
        let program: BpfProgram = filter
            .try_into()
            .context("seccomp: assemble read-only BPF")?;
        Ok(program)
    }

    /// The Landlock ruleset for read-only containment, as a hard requirement:
    /// every V3 write right is handled, and signals and abstract unix sockets
    /// are scoped to the sandbox (ABI 6). A kernel that cannot enforce all of
    /// it makes this an `Err` rather than a quieter ruleset.
    fn read_only_ruleset() -> anyhow::Result<landlock::RulesetCreated> {
        use landlock::{
            ABI, Access, AccessFs, CompatLevel, Compatible, Ruleset, RulesetAttr, Scope,
        };
        Ruleset::default()
            .set_compatibility(CompatLevel::HardRequirement)
            .handle_access(AccessFs::from_write(LANDLOCK_ABI))
            .context("landlock: handle write access")?
            .scope(Scope::from_all(ABI::V6))
            .context("landlock: scope signals and abstract sockets")?
            .create()
            .context("landlock: create read-only ruleset")
    }

    /// Whether read-only containment can be enforced on this kernel. Builds
    /// the ruleset (an fd, then dropped) and both seccomp programs; installs
    /// nothing.
    pub(super) fn read_only_supported() -> bool {
        read_only_ruleset().is_ok() && network_filter().is_ok() && read_only_filter().is_ok()
    }

    /// Give up every capability, so a command run as root cannot use them
    /// (rebooting, setting the clock, clearing the kernel log, raw I/O).
    /// Ambient and bounding sets first, while `CAP_SETPCAP` may still be
    /// held; then the thread's own sets. Without `CAP_SETPCAP` the bounding
    /// set cannot shrink, and needs not: `no_new_privs`, which Landlock sets
    /// below, already stops an `execve` from gaining anything.
    fn drop_capabilities() -> anyhow::Result<()> {
        use rustix::thread::{CapabilitySet, CapabilitySets, set_capabilities};
        // SAFETY: plain prctl calls with integer arguments.
        unsafe {
            libc::prctl(
                libc::PR_CAP_AMBIENT,
                libc::PR_CAP_AMBIENT_CLEAR_ALL,
                0,
                0,
                0,
            );
            // Capability numbers run to `cap_last_cap`; past it the kernel
            // answers EINVAL, which ends the loop.
            for cap in 0..64 {
                if libc::prctl(libc::PR_CAPBSET_DROP, cap, 0, 0, 0) != 0
                    && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL)
                {
                    break;
                }
            }
        }
        set_capabilities(
            None,
            CapabilitySets {
                effective: CapabilitySet::empty(),
                permitted: CapabilitySet::empty(),
                inheritable: CapabilitySet::empty(),
            },
        )
        .context("capset: drop every capability")?;
        Ok(())
    }

    /// Install read-only containment on the current process: capabilities
    /// dropped, the Landlock ruleset (with `no_new_privs`), then the network
    /// kill-switch and the read-only seccomp filter. Stacked seccomp filters
    /// take the strictest verdict, so an internet socket still dies with the
    /// kill-switch's `SIGSYS` and keeps its precise denial message.
    pub(super) fn apply_read_only() -> anyhow::Result<()> {
        use landlock::{AccessFs, RulesetCreatedAttr, RulesetStatus, path_beneath_rules};

        drop_capabilities()?;

        let file_write = AccessFs::from_write(LANDLOCK_ABI) & AccessFs::from_file(LANDLOCK_ABI);
        let status = read_only_ruleset()?
            // `path_beneath_rules` skips paths that cannot be opened, so a
            // missing device narrows the sandbox instead of erroring.
            .add_rules(path_beneath_rules(READ_ONLY_WRITABLE, file_write))
            .context("landlock: allow device writes")?
            .restrict_self()
            .context("landlock: restrict self")?;
        anyhow::ensure!(
            status.ruleset == RulesetStatus::FullyEnforced,
            "landlock: read-only ruleset not fully enforced ({:?})",
            status.ruleset
        );

        apply_network_killswitch()?;
        let program = read_only_filter()?;
        apply_filter(&program).context("seccomp: install read-only filter")?;
        #[cfg(target_arch = "x86_64")]
        apply_filter(&x32_filter()).context("seccomp: install x32 filter")?;
        Ok(())
    }

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

        /// Fork a child, install `bpf`, attempt `socket(domain, SOCK_STREAM, 0)`,
        /// and return the child's raw wait status. The BPF is built in the
        /// parent so the post-`fork` child only performs near-async-signal-safe
        /// work (the seccomp syscall + `socket` + `_exit`).
        fn child_socket_status(bpf: &BpfProgram, domain: libc::c_int) -> libc::c_int {
            // SAFETY: single-threaded test path; the child only calls
            // `apply_filter`, `socket`/`close`, and `_exit`.
            unsafe {
                let pid = libc::fork();
                assert!(pid >= 0, "fork failed");
                if pid == 0 {
                    if apply_filter(bpf).is_err() {
                        libc::_exit(77);
                    }
                    let fd = libc::socket(domain, libc::SOCK_STREAM, 0);
                    if fd >= 0 {
                        libc::close(fd);
                    }
                    libc::_exit(0);
                }
                let mut status: libc::c_int = 0;
                let waited = libc::waitpid(pid, &mut status, 0);
                assert_eq!(waited, pid, "waitpid failed");
                status
            }
        }

        #[test]
        fn inet_socket_is_killed_with_sigsys() {
            let bpf = network_filter().expect("build filter");
            let status = child_socket_status(&bpf, libc::AF_INET);
            assert!(
                libc::WIFSIGNALED(status),
                "AF_INET socket should be signal-killed, status={status}"
            );
            assert_eq!(
                libc::WTERMSIG(status),
                libc::SIGSYS,
                "AF_INET socket should die with SIGSYS"
            );
        }

        #[test]
        fn unix_socket_is_allowed() {
            let bpf = network_filter().expect("build filter");
            let status = child_socket_status(&bpf, libc::AF_UNIX);
            assert!(
                libc::WIFEXITED(status),
                "AF_UNIX socket should exit cleanly, status={status}"
            );
            assert_eq!(
                libc::WEXITSTATUS(status),
                0,
                "AF_UNIX socket must be allowed under the network kill-switch"
            );
        }

        #[test]
        fn fs_confinement_allows_inside_and_denies_outside_writes() {
            // Two sibling temp dirs; confinement grants writes beneath only one.
            let base = std::env::temp_dir().join(format!(
                "mermaid-landlock-test-{}-{}",
                std::process::id(),
                // Distinguish parallel test binaries reusing a pid.
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            ));
            let allowed = base.join("allowed");
            let outside = base.join("outside");
            std::fs::create_dir_all(&allowed).unwrap();
            std::fs::create_dir_all(&outside).unwrap();

            // Exit codes: 0 = enforced correctly; 42 = kernel can't enforce
            // (skip); 10 = inside write failed; 11 = outside write succeeded;
            // 77 = apply failed. Same fork pattern as the seccomp tests above.
            // SAFETY: the child only runs the confinement setup, two writes,
            // and `_exit`.
            let status = unsafe {
                let pid = libc::fork();
                assert!(pid >= 0, "fork failed");
                if pid == 0 {
                    let code = match apply_fs_confinement(std::slice::from_ref(&allowed)) {
                        Err(_) => 77,
                        Ok(false) => 42,
                        Ok(true) => {
                            let inside_ok = std::fs::write(allowed.join("in.txt"), b"x").is_ok();
                            let outside_ok = std::fs::write(outside.join("out.txt"), b"x").is_ok();
                            match (inside_ok, outside_ok) {
                                (true, false) => 0,
                                (false, _) => 10,
                                (true, true) => 11,
                            }
                        },
                    };
                    libc::_exit(code);
                }
                let mut status: libc::c_int = 0;
                assert_eq!(libc::waitpid(pid, &mut status, 0), pid, "waitpid failed");
                status
            };

            let _ = std::fs::remove_dir_all(&base);

            assert!(
                libc::WIFEXITED(status),
                "child should exit, status={status}"
            );
            let code = libc::WEXITSTATUS(status);
            if code == 42 {
                eprintln!("skipping: kernel does not enforce Landlock");
                return;
            }
            assert_eq!(
                code, 0,
                "confined child: 10 = allowed write failed, 11 = outside write \
                 succeeded, 77 = apply failed"
            );
        }

        /// Fork a child, install read-only containment, run `probe` in it,
        /// and return the child's raw wait status. `probe` answers with an
        /// exit code; 77 means the containment itself failed to apply.
        fn read_only_child_status(probe: impl FnOnce() -> i32) -> libc::c_int {
            // SAFETY: single-threaded test path; the child only installs the
            // containment, runs the probe's few syscalls, and `_exit`s.
            unsafe {
                let pid = libc::fork();
                assert!(pid >= 0, "fork failed");
                if pid == 0 {
                    let code = if apply_read_only().is_ok() {
                        probe()
                    } else {
                        77
                    };
                    libc::_exit(code);
                }
                let mut status: libc::c_int = 0;
                assert_eq!(
                    libc::waitpid(pid, &raw mut status, 0),
                    pid,
                    "waitpid failed"
                );
                status
            }
        }

        fn errno() -> Option<i32> {
            std::io::Error::last_os_error().raw_os_error()
        }

        /// Everything read-only containment promises, one probe each: reads
        /// and discard-device writes work; file writes, metadata changes,
        /// local sockets, and signals to a process outside the sandbox fail.
        #[test]
        fn read_only_containment_allows_reads_and_denies_changes() {
            use std::ffi::CString;
            if !read_only_supported() {
                eprintln!("skipping: kernel cannot enforce read-only containment");
                return;
            }
            let base = std::env::temp_dir().join(format!(
                "mermaid-readonly-test-{}-{}",
                std::process::id(),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            ));
            std::fs::create_dir_all(&base).unwrap();
            let existing = base.join("existing.txt");
            std::fs::write(&existing, b"before").unwrap();
            let existing_c = CString::new(existing.to_str().unwrap()).unwrap();
            let fresh = base.join("fresh.txt");

            let status = read_only_child_status(|| {
                // SAFETY: plain syscalls on owned, NUL-terminated paths.
                unsafe {
                    if std::fs::read(&existing).ok().as_deref() != Some(b"before".as_slice()) {
                        return 10;
                    }
                    if std::fs::OpenOptions::new()
                        .write(true)
                        .open("/dev/null")
                        .is_err()
                    {
                        return 11;
                    }
                    if std::fs::write(&fresh, b"x").is_ok() {
                        return 12;
                    }
                    if std::fs::write(&existing, b"after").is_ok() {
                        return 13;
                    }
                    if libc::chmod(existing_c.as_ptr(), 0o777) == 0 || errno() != Some(libc::EPERM)
                    {
                        return 14;
                    }
                    if libc::utimensat(libc::AT_FDCWD, existing_c.as_ptr(), std::ptr::null(), 0)
                        == 0
                    {
                        return 15;
                    }
                    let fd = libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0);
                    if fd >= 0 || errno() != Some(libc::EPERM) {
                        return 16;
                    }
                    if libc::kill(libc::getppid(), 0) == 0 {
                        return 17;
                    }
                    let caps_dropped = rustix::thread::capabilities(None)
                        .is_ok_and(|c| c.effective.is_empty() && c.permitted.is_empty());
                    if !caps_dropped {
                        return 18;
                    }
                    0
                }
            });
            let unchanged = std::fs::read(&existing).unwrap();
            let _ = std::fs::remove_dir_all(&base);

            assert!(
                libc::WIFEXITED(status),
                "child should exit, status={status}"
            );
            assert_eq!(
                libc::WEXITSTATUS(status),
                0,
                "10 read failed, 11 /dev/null write failed, 12 new file written, \
                 13 existing file written, 14 chmod allowed, 15 utimensat allowed, \
                 16 unix socket allowed, 17 signal left the sandbox, \
                 18 capabilities kept, 77 apply failed"
            );
            assert_eq!(unchanged, b"before");
        }

        /// An internet socket under read-only containment still dies with the
        /// kill-switch's `SIGSYS`: the stricter of the stacked filters wins,
        /// which is what keeps the precise network-denial message.
        #[test]
        fn read_only_containment_kills_internet_sockets() {
            if !read_only_supported() {
                eprintln!("skipping: kernel cannot enforce read-only containment");
                return;
            }
            let status = read_only_child_status(|| {
                // SAFETY: a plain socket syscall.
                let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_STREAM, 0) };
                if fd >= 0 { 1 } else { 2 }
            });
            assert!(
                libc::WIFSIGNALED(status) && libc::WTERMSIG(status) == libc::SIGSYS,
                "AF_INET socket should die with SIGSYS, status={status}"
            );
        }
    }
}