procage 0.3.1

Process sandboxing for Rust on macOS (Seatbelt, without sandbox-exec) and Linux (Landlock, seccomp, namespaces)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
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
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
//! Spawning a caged child on macOS (Seatbelt).
//!
//! A [`Cage`] is a prepared policy. Preparing it:
//!
//! 1. resolves every path to the spelling the kernel matches (`/tmp/x`
//!    becomes `/private/tmp/x`) and records the rewrite;
//! 2. lowers the policy;
//! 3. compiles the profile once, through libsandbox's private interface,
//!    which is resolved at runtime.
//!
//! Resolution also lets the child read the *metadata* of each symlink a
//! policy path passes through, and of `/etc`, `/tmp` and `/var`. The kernel
//! needs this to look up a path in the spelling the caller uses, so the child
//! can see where those links point, but nothing behind them.
//!
//! [`Cage::spawn`] then forks a child that applies the compiled profile with
//! system calls only, confirms that it is sandboxed, consumes the spawn's
//! grant tokens, and only then executes its target. If any step fails, the
//! target never runs and the error names the step.
//!
//! `tests/spawn_macos.rs` and `tests/escape_macos.rs` check this on a real
//! kernel; the [threat model](crate::threat_model) lists every escape class
//! and its evidence.
//!
//! **Limits:**
//!
//! - there are no pseudo-terminals (`Tty::NewPty`);
//! - the base profiles are curated for macOS 26.6.2;
//!   [`Base::V1`](procage_policy::Base::V1) does not run Xcode's tool shims
//!   (`/usr/bin/git`, `/usr/bin/python3`): use
//!   [`Base::V3`](procage_policy::Base::V3), see `procage_policy::base`;
//! - procage installs no helper program of its own (so R-26 does not apply).
//!
//! With `Tty::Inherit` the child runs in its own process group, so its reads
//! from the shared terminal stop with SIGTTIN, like a background job.

mod canon;
mod child;
mod lifetime;
mod probe;
mod spawn;
mod sys;
mod violations;

use std::collections::HashMap;
use std::fmt;
use std::io;
use std::os::fd::{AsRawFd, BorrowedFd};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex, OnceLock};

use procage_policy::lower::GrantSlot;
use procage_policy::{
    LowerError, LowerOptions, Plan, Policy, Relax, Relaxed, SeatbeltPlan, Target, Tty, lift, lower,
};

pub use crate::unix::TMPDIR_GRANT;
pub use crate::violation::{Coverage, DeniedBy, Violation, Violations};
pub use child::Child;
pub use probe::{ApplyMethod, probe};

use crate::unix::TmpdirGuard;

/// A step of the in-child sequence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Step {
    /// Starting a new session (`setsid`).
    Session,
    /// Setting resource limits.
    Rlimit,
    /// Applying the compiled profile.
    Apply,
    /// Confirming that the process is sandboxed.
    Verify,
    /// Consuming a grant token.
    Consume,
    /// Marking inherited descriptors close-on-exec.
    Fds,
}

impl Step {
    fn from_code(code: u32) -> Option<Step> {
        Some(match code {
            sys::steps::SESSION => Step::Session,
            sys::steps::RLIMIT => Step::Rlimit,
            sys::steps::APPLY => Step::Apply,
            sys::steps::VERIFY => Step::Verify,
            sys::steps::CONSUME => Step::Consume,
            sys::steps::FDS => Step::Fds,
            _ => return None,
        })
    }
}

impl fmt::Display for Step {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Step::Session => "new session",
            Step::Rlimit => "resource limits",
            Step::Apply => "apply profile",
            Step::Verify => "verify sandbox",
            Step::Consume => "consume grant token",
            Step::Fds => "close inherited descriptors",
        })
    }
}

/// Something this macOS release or this procage version cannot do.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unsupported {
    /// A private libsandbox symbol is missing.
    Symbol {
        /// The symbol.
        symbol: &'static str,
        /// `kern.osversion`.
        os_build: String,
    },
    /// The in-child apply method failed its probe on this release.
    ApplyMethod {
        /// `kern.osversion`.
        os_build: String,
        /// What the probe observed.
        detail: String,
    },
    /// A policy setting this backend cannot apply.
    Setting {
        /// The setting.
        setting: &'static str,
    },
    /// The query that finds a run's processes by their sandbox failed its
    /// probe on this release.
    RunMarker {
        /// `kern.osversion`.
        os_build: String,
        /// What the probe observed.
        detail: String,
    },
    /// `EnvPolicy::Passthrough` cannot be used: this standard library does
    /// not show whether `Command::env_clear` was called, so procage cannot
    /// tell whether the caller's environment may be passed.
    EnvClear,
}

impl fmt::Display for Unsupported {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Unsupported::Symbol { symbol, os_build } => {
                write!(
                    f,
                    "libsandbox symbol `{symbol}` is missing on macOS build {os_build}"
                )
            }
            Unsupported::ApplyMethod { os_build, detail } => {
                write!(
                    f,
                    "the in-child apply method failed its probe on macOS build {os_build}: {detail}"
                )
            }
            Unsupported::Setting { setting } => {
                write!(f, "{setting} is not supported in this release")
            }
            Unsupported::EnvClear => write!(
                f,
                "EnvPolicy::Passthrough needs to see whether Command::env_clear was called, \
                 which this Rust standard library does not show; use EnvPolicy::Allowlist"
            ),
            Unsupported::RunMarker { os_build, detail } => {
                write!(
                    f,
                    "the run-marker query failed its probe on macOS build {os_build}: {detail}"
                )
            }
        }
    }
}

/// A problem with a per-spawn grant binding.
#[derive(Debug)]
pub enum GrantError {
    /// The policy declares no grant of this name.
    Undeclared {
        /// The name.
        name: String,
    },
    /// The bound path cannot be resolved (it must exist).
    Missing {
        /// The grant.
        name: String,
        /// The path as bound.
        path: PathBuf,
        /// Why.
        error: io::Error,
    },
    /// The grant name is reserved for procage (`tmpdir`).
    Reserved {
        /// The name.
        name: String,
    },
    /// The policy declares the `tmpdir` grant, which [`Cage::exec`] cannot
    /// provide: no handle would remove the directory.
    TmpdirWithExec,
    /// libsandbox issued no token for the path.
    Issue {
        /// The grant.
        name: String,
        /// The resolved path.
        path: String,
    },
}

impl fmt::Display for GrantError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GrantError::Undeclared { name } => {
                write!(f, "the policy declares no grant named {name:?}")
            }
            GrantError::Missing { name, path, error } => {
                write!(
                    f,
                    "grant {name}: cannot resolve {}: {error}",
                    path.display()
                )
            }
            GrantError::TmpdirWithExec => write!(
                f,
                "the tmpdir grant needs a handle that removes the directory, and Cage::exec \
                 returns none: use Cage::spawn, or bind a directory of your own to another grant"
            ),
            GrantError::Reserved { name } => {
                write!(
                    f,
                    "grant {name} is bound by procage itself (a private temporary directory)"
                )
            }
            GrantError::Issue { name, path } => {
                write!(f, "grant {name}: no extension token issued for {path}")
            }
        }
    }
}

#[cfg(feature = "tokio")]
pub use crate::async_child::AsyncChild;

/// Why no caged child runs.
#[derive(Debug)]
#[non_exhaustive]
pub enum SpawnError {
    /// This release or version cannot do it.
    Unsupported(Unsupported),
    /// The calling process is already sandboxed; a second profile would fail
    /// or be ignored by the kernel.
    AlreadySandboxed,
    /// The policy could not be lowered for macOS.
    Lower(LowerError),
    /// A policy path could not be resolved.
    Path {
        /// The path.
        path: String,
        /// Why.
        error: io::Error,
    },
    /// libsandbox refused the profile.
    Compile {
        /// libsandbox's message.
        message: String,
    },
    /// The profile has more rules than the in-process compile limit.
    LimitExceeded {
        /// The limit.
        limit: usize,
        /// The profile's rule count.
        rules: usize,
    },
    /// A grant binding is wrong.
    Grant(GrantError),
    /// A descriptor handed to the spawn is not open.
    Fd {
        /// The descriptor.
        fd: i32,
    },
    /// The run's private temporary directory could not be created.
    Tmpdir(io::Error),
    /// A step in the child failed; the target did not run.
    Apply {
        /// The step.
        step: Step,
        /// The OS error number.
        errno: i32,
    },
    /// Spawning failed (for example, the target cannot be executed).
    Io(io::Error),
    /// A protected, hidden or class file has another name (a hard link),
    /// which path rules do not cover; see [`LinkAudit`](crate::LinkAudit).
    HardLinks(Vec<crate::LinkFinding>),
    /// A question to [`Cage::explain`] has no answer.
    Explain(procage_policy::explain::ExplainError),
    /// [`Cage::spawn_async`] was called outside a tokio runtime.
    #[cfg(feature = "tokio")]
    NoRuntime,
}

impl fmt::Display for SpawnError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SpawnError::Unsupported(u) => write!(f, "unsupported: {u}"),
            SpawnError::AlreadySandboxed => f.write_str("the calling process is already sandboxed"),
            SpawnError::Lower(e) => write!(f, "{e}"),
            SpawnError::Path { path, error } => write!(f, "cannot resolve {path}: {error}"),
            SpawnError::Compile { message } => {
                write!(f, "libsandbox refused the profile: {message}")
            }
            SpawnError::LimitExceeded { limit, rules } => {
                write!(
                    f,
                    "the profile has {rules} rules, more than the in-process compile limit of {limit}"
                )
            }
            SpawnError::Grant(e) => write!(f, "{e}"),
            SpawnError::Fd { fd } => write!(f, "descriptor {fd} handed to the spawn is not open"),
            SpawnError::Tmpdir(e) => {
                write!(f, "cannot create the private temporary directory: {e}")
            }
            SpawnError::Apply { step, errno } => write!(
                f,
                "the child failed at step `{step}`: {}; the target did not run",
                io::Error::from_raw_os_error(*errno)
            ),
            SpawnError::Io(e) => write!(f, "{e}"),
            SpawnError::HardLinks(found) => f.write_str(&crate::audit::refusal(found)),
            SpawnError::Explain(e) => write!(f, "{e}"),
            #[cfg(feature = "tokio")]
            SpawnError::NoRuntime => {
                f.write_str("spawn_async needs a tokio runtime on the calling thread")
            }
        }
    }
}

impl std::error::Error for SpawnError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            SpawnError::Lower(e) => Some(e),
            SpawnError::Path { error, .. } | SpawnError::Io(error) | SpawnError::Tmpdir(error) => {
                Some(error)
            }
            SpawnError::Grant(GrantError::Missing { error, .. }) => Some(error),
            _ => None,
        }
    }
}

impl From<LowerError> for SpawnError {
    fn from(e: LowerError) -> Self {
        SpawnError::Lower(e)
    }
}

/// A policy path that was rewritten to the spelling the kernel matches.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PathRewrite {
    /// As written in the policy.
    pub from: String,
    /// As resolved.
    pub to: String,
}

/// Options for [`Cage::with_options`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CageOptions {
    /// Options for lowering the policy.
    pub lower: LowerOptions,
    /// The most rules compiled in-process (default 2,000). libsandbox aborts
    /// its caller on very large profiles; larger ones are refused.
    pub compile_limit: usize,
    /// Whether spawns report the operations the sandbox denies (see
    /// [`CageOptions::with_violations`]).
    pub violations: bool,
    /// Whether receipts hold the policy (see
    /// [`CageOptions::with_policy_in_receipt`]).
    pub policy_in_receipt: bool,
    /// What the link check does before each spawn (default: refuse).
    pub link_audit: crate::LinkAudit,
    /// Subtrees the link check does not examine for protected files (see
    /// [`CageOptions::with_link_exemption`]).
    pub link_exempt: Vec<PathBuf>,
    /// Whether runs note what they leave behind (see
    /// [`CageOptions::with_handoff_audit`]).
    pub handoff_audit: bool,
    /// The most entries one audit walk visits (default 200,000).
    pub walk_limit: usize,
    /// The proxy each run of a `Network::Proxy` policy gets (see
    /// [`CageOptions::with_proxy`]).
    #[cfg(feature = "proxy")]
    pub proxy: Option<procage_proxy::Proxy>,
}

impl Default for CageOptions {
    fn default() -> Self {
        Self {
            lower: LowerOptions::default(),
            compile_limit: 2000,
            violations: false,
            policy_in_receipt: false,
            link_audit: crate::LinkAudit::Refuse,
            link_exempt: Vec::new(),
            handoff_audit: false,
            walk_limit: 200_000,
            #[cfg(feature = "proxy")]
            proxy: None,
        }
    }
}

impl CageOptions {
    /// These options with `lower` as the lowering options.
    pub fn with_lower(mut self, lower: LowerOptions) -> Self {
        self.lower = lower;
        self
    }

    /// These options with an in-process compile limit of `limit` rules.
    pub fn with_compile_limit(mut self, limit: usize) -> Self {
        self.compile_limit = limit;
        self
    }

    /// These options with the link check in `mode` (see [`crate::audit`]).
    pub fn with_link_audit(mut self, mode: crate::LinkAudit) -> Self {
        self.link_audit = mode;
        self
    }

    /// These options with `path` exempt from the link check for protected
    /// files: a file at or below it may have another name. Meant for a store
    /// whose files are written once and never rewritten in place, such as a
    /// repository's `.git/objects`, which a local `git clone` hard-links to
    /// the source repository's. A protected file there can then be changed
    /// through a name in a writable tree (git notices a changed object when
    /// it checks one, as `git fsck` does); hidden files are examined
    /// everywhere. The path must be absolute (a relative one fails the cage
    /// with [`Unsupported::Setting`]); [`Audit`](crate::Audit) lists a run's
    /// exemptions.
    pub fn with_link_exemption(mut self, path: impl AsRef<Path>) -> Self {
        self.link_exempt.push(path.as_ref().to_path_buf());
        self
    }

    /// These options with the handoff audit: each run notes the trust-handoff
    /// files, symbolic links and repositories of the writable trees, and
    /// [`Child::audit`] lists what it created or changed (see [`crate::audit`]).
    pub fn with_handoff_audit(mut self) -> Self {
        self.handoff_audit = true;
        self
    }

    /// These options with audit walks of at most `limit` entries.
    pub fn with_walk_limit(mut self, limit: usize) -> Self {
        self.walk_limit = limit;
        self
    }

    /// These options with receipts that hold the policy itself and the
    /// subjects (often paths) of `fit`'s relaxations. Without it a receipt
    /// names the policy by digest only.
    pub fn with_policy_in_receipt(mut self) -> Self {
        self.policy_in_receipt = true;
        self
    }

    /// These options with violation reporting: every spawn's
    /// [`Child::violations`] lists the operations the sandbox denied it, with
    /// the kind of rule that denied each (see [`crate::violation`]).
    ///
    /// The first such spawn in a process starts one helper, `/usr/bin/log
    /// stream`, which ends with the process. Reporting needs an administrator
    /// account; where it cannot start, spawning still works and the record
    /// says why. Without this option nothing changes: no helper, and the
    /// same profile.
    pub fn with_violations(mut self) -> Self {
        self.violations = true;
        self
    }

    /// These options with a proxy of the cage's own (feature `proxy`): each
    /// spawn of a `Network::Proxy` policy gets fresh loopback listeners for
    /// the protocols the policy names, the profile allows outbound
    /// connections to those ports only, and the proxy variables
    /// (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, lower-case too) name them.
    /// The policy's port numbers are not used. Refusals are in
    /// [`Child::violations`] when the cage reports violations; the run's
    /// connections close when the run ends. A policy without
    /// `Network::Proxy` is refused.
    #[cfg(feature = "proxy")]
    pub fn with_proxy(mut self, proxy: procage_proxy::Proxy) -> Self {
        self.proxy = Some(proxy);
        self
    }
}

/// Per-spawn bindings of the policy's grants to existing paths.
#[derive(Debug, Clone, Default)]
pub struct Grants {
    bindings: Vec<(String, PathBuf)>,
}

impl Grants {
    /// No bindings.
    pub fn new() -> Self {
        Self::default()
    }

    /// These bindings plus grant `name` bound to `path`.
    pub fn bind(mut self, name: &str, path: impl AsRef<Path>) -> Self {
        self.bindings
            .push((name.to_string(), path.as_ref().to_path_buf()));
        self
    }
}

type CacheKey = (String, Vec<(String, String)>);

fn cache() -> &'static Mutex<HashMap<CacheKey, Arc<[u8]>>> {
    static CACHE: OnceLock<Mutex<HashMap<CacheKey, Arc<[u8]>>>> = OnceLock::new();
    CACHE.get_or_init(Default::default)
}

/// The bytecode for `plan` with the run-marker parameters `marker`, from the
/// cache or compiled; `true` when it was compiled.
fn compiled(
    lib: &sys::Libsandbox,
    plan: &SeatbeltPlan,
    marker: &[(String, String)],
    overrides: &[(String, String)],
) -> Result<(Arc<[u8]>, bool), SpawnError> {
    let mut params = plan.params.clone();
    params.extend_from_slice(marker);
    for (name, value) in overrides {
        match params.iter_mut().find(|(n, _)| n == name) {
            Some(param) => param.1.clone_from(value),
            None => params.push((name.clone(), value.clone())),
        }
    }
    let key = (plan.profile.clone(), params);
    let cached = cache()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(&key)
        .cloned();
    if let Some(bytecode) = cached {
        return Ok((bytecode, false));
    }
    let bytecode: Arc<[u8]> = lib
        .compile(&plan.profile, &key.1)
        .map_err(|message| SpawnError::Compile {
            message: message.unwrap_or_else(|| "<no error text>".into()),
        })?
        .into();
    cache()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .insert(key, bytecode.clone());
    Ok((bytecode, true))
}

fn libsandbox() -> Result<&'static sys::Libsandbox, SpawnError> {
    sys::Libsandbox::get().map_err(|symbol| {
        SpawnError::Unsupported(Unsupported::Symbol {
            symbol,
            os_build: sys::os_build(),
        })
    })
}

/// Whether the calling process is sandboxed (by procage or anything else).
pub fn is_sandboxed() -> Result<bool, SpawnError> {
    Ok(libsandbox()?.is_sandboxed())
}

/// A prepared policy: resolved, lowered and compiled, reusable for any number
/// of spawns from any thread.
#[derive(Debug, Clone)]
pub struct Cage {
    plan: SeatbeltPlan,
    bytecode: Arc<[u8]>,
    rewrites: Vec<PathRewrite>,
    compiled: bool,
    violations: bool,
    /// What every run's receipt starts from.
    facts: Arc<crate::receipt::CageFacts>,
    /// The audits every spawn runs.
    audit: Arc<crate::audit::CageAudit>,
    /// Answers [`Cage::explain`].
    explainer: Arc<crate::explain::Lazy>,
    /// The cage's own proxy.
    #[cfg(feature = "proxy")]
    proxied: Option<crate::proxied::Proxied>,
}

impl Cage {
    /// Prepares `policy` with default options.
    pub fn new(policy: &Policy) -> Result<Cage, SpawnError> {
        Cage::with_options(policy, &CageOptions::default())
    }

    /// Prepares `policy`, giving up exactly the constructs this host cannot
    /// enforce and `relax` accepts. Returns the cage and what was relaxed,
    /// each with what would lift it (unknown on macOS, where gaps are rare).
    /// Any other gap fails as [`Cage::with_options`] does, with every
    /// remaining gap, and nothing is relaxed that `relax` does not name.
    pub fn fit(
        policy: &Policy,
        options: &CageOptions,
        relax: &Relax,
    ) -> Result<(Cage, Vec<Relaxed>), SpawnError> {
        let mut fitted = policy.clone();
        let mut relaxed = Vec::new();
        // Each round relaxes at least one construct; a few always suffice.
        for _ in 0..4 {
            let gaps = match Cage::with_options(&fitted, options) {
                Ok(cage) => return Ok(cage.relaxed(&fitted, options, relaxed)),
                Err(SpawnError::Lower(LowerError::Gaps(gaps))) => gaps,
                Err(e) => return Err(e),
            };
            let done = relax
                .apply(&mut fitted, &gaps)
                .map_err(|rest| SpawnError::Lower(LowerError::Gaps(rest)))?;
            relaxed.extend(done.into_iter().map(|(gap, relaxation)| Relaxed {
                lift: lift(policy, &gap, &options.lower, 0),
                gap,
                relaxation,
            }));
        }
        Cage::with_options(&fitted, options).map(|cage| cage.relaxed(&fitted, options, relaxed))
    }

    /// This cage with its receipts listing `relaxed`.
    fn relaxed(
        mut self,
        fitted: &Policy,
        options: &CageOptions,
        relaxed: Vec<Relaxed>,
    ) -> (Cage, Vec<Relaxed>) {
        self.facts = Arc::new(facts(fitted, options, &self.plan, &relaxed));
        (self, relaxed)
    }

    /// Prepares `policy`. Fails with [`SpawnError::AlreadySandboxed`] in a
    /// process that is itself sandboxed.
    pub fn with_options(policy: &Policy, options: &CageOptions) -> Result<Cage, SpawnError> {
        if policy.tty == Tty::NewPty {
            return Err(SpawnError::Unsupported(Unsupported::Setting {
                setting: "Tty::NewPty",
            }));
        }
        let lib = libsandbox()?;
        // A sandboxed process cannot cage a child (the kernel refuses or
        // ignores a second profile); say so before anything else fails.
        if lib.is_sandboxed() {
            return Err(SpawnError::AlreadySandboxed);
        }
        #[cfg(feature = "proxy")]
        let proxied = match &options.proxy {
            None => None,
            Some(proxy) => Some(crate::proxied::Proxied::new(proxy, &policy.net).ok_or(
                SpawnError::Unsupported(Unsupported::Setting {
                    setting: "CageOptions::with_proxy without Network::Proxy",
                }),
            )?),
        };
        let (resolved, rewrites) = canon::resolve_policy(policy)?;
        let violations = options.violations || options.lower.violations;
        let mut lower_options = options.lower.clone();
        if violations {
            lower_options = lower_options.with_violations();
        }
        let Plan::Seatbelt(plan) = lower(&resolved, Target::MacOs, &lower_options)? else {
            unreachable!("lowering for macOS yields a Seatbelt plan");
        };
        if plan.rule_count > options.compile_limit {
            return Err(SpawnError::LimitExceeded {
                limit: options.compile_limit,
                rules: plan.rule_count,
            });
        }
        // A forking or reporting policy is compiled for the first run-marker
        // slot, the one sequential runs use.
        let marker = if plan.run_marker || violations {
            lifetime::first_params().to_vec()
        } else {
            Vec::new()
        };
        let (bytecode, compiled) = compiled(lib, &plan, &marker, &[])?;
        let facts = Arc::new(facts(policy, options, &plan, &[]));
        let audit = Arc::new(cage_audit(&resolved, options)?);
        let explainer = Arc::new(crate::explain::Lazy::new(
            resolved,
            Target::MacOs,
            lower_options,
        ));
        Ok(Cage {
            plan,
            bytecode,
            rewrites,
            compiled,
            violations,
            facts,
            audit,
            explainer,
            #[cfg(feature = "proxy")]
            proxied,
        })
    }

    /// Why a child of this cage, spawned with `grants`, may or may not
    /// perform `op` on `path` as the file is now: the deciding rule and what
    /// would change it (see [`procage_policy::explain`]).
    ///
    /// Symbolic links in `path` and the grants' paths are resolved, and the
    /// file's mode is read (set-user-ID files are denied). The grant of the
    /// private temporary directory is left out: its path exists only during
    /// a run.
    ///
    /// The answer names the policy's rules: show it to the user, do not
    /// relay it into the cage unfiltered.
    pub fn explain(
        &self,
        op: procage_policy::explain::Op,
        path: impl AsRef<Path>,
        grants: &Grants,
    ) -> Result<procage_policy::explain::Answer, SpawnError> {
        let path = path.as_ref();
        let question = crate::explain::question(op, path).map_err(|error| SpawnError::Path {
            path: path.display().to_string(),
            error,
        })?;
        let mut bound = Vec::new();
        for (name, p) in &grants.bindings {
            if self.grant_slot(name).is_none() {
                return Err(SpawnError::Grant(GrantError::Undeclared {
                    name: name.clone(),
                }));
            }
            let real = canon::resolve_existing(p).map_err(|error| {
                SpawnError::Grant(GrantError::Missing {
                    name: name.clone(),
                    path: p.clone(),
                    error,
                })
            })?;
            let real: &std::ffi::OsStr = std::os::unix::ffi::OsStrExt::from_bytes(real.as_bytes());
            bound.push((name.clone(), PathBuf::from(real)));
        }
        let context = crate::explain::context(bound, &[]).map_err(SpawnError::Io)?;
        self.explainer
            .get()?
            .explain(&question, &context)
            .map_err(SpawnError::Explain)
    }

    /// The lowered plan (profile text, parameters, grant slots, hygiene).
    pub fn plan(&self) -> &SeatbeltPlan {
        &self.plan
    }

    /// The path rewrites made while preparing.
    pub fn rewrites(&self) -> &[PathRewrite] {
        &self.rewrites
    }

    /// Whether preparing this cage compiled the profile (`false`: the
    /// in-memory cache already held it).
    pub fn compiled(&self) -> bool {
        self.compiled
    }

    fn grant_slot(&self, name: &str) -> Option<&GrantSlot> {
        self.plan.grants.iter().find(|g| g.name.as_str() == name)
    }

    /// Spawns `command` in this cage, with `grants` bound for this spawn.
    ///
    /// The command's program must be executable under the policy. Fails
    /// without forking when the caller is already sandboxed, when the
    /// apply method failed its probe, or when a grant binding is wrong. The
    /// child receives only standard input, output and error.
    ///
    /// The child's environment comes from the policy's
    /// [`EnvPolicy`](procage_policy::EnvPolicy) and the variables set or
    /// removed on `command`, which win (see [`crate::hygiene`]). After
    /// `Command::env_clear`, no variable of the caller is passed under any
    /// policy: the child gets exactly the variables set on `command`. Fails
    /// with [`Unsupported::EnvClear`] before forking when a passthrough
    /// policy is used and the standard library does not show whether
    /// `env_clear` was called.
    pub fn spawn(&self, command: &mut Command, grants: &Grants) -> Result<Child, SpawnError> {
        self.spawn_with_fds(command, grants, &[])
    }

    /// Like [`Cage::spawn`], and also hands `fds` to the child: they stay
    /// open across the exec, at the same numbers. Every other descriptor
    /// numbered 3 or higher is closed in the child.
    pub fn spawn_with_fds(
        &self,
        command: &mut Command,
        grants: &Grants,
        fds: &[BorrowedFd<'_>],
    ) -> Result<Child, SpawnError> {
        let launch = self.launch(command, grants, fds)?;
        match command.spawn() {
            Ok(inner) => Ok(self.adopt(launch, crate::unix::Proc::Std(inner))),
            Err(e) => Err(launch.abandon(e)),
        }
    }

    /// Everything a spawn does before the fork: the checks, the child
    /// sequence installed on `command`, the link check and the record.
    pub(crate) fn launch(
        &self,
        command: &mut Command,
        grants: &Grants,
        fds: &[BorrowedFd<'_>],
    ) -> Result<Launch, SpawnError> {
        let session = if self.plan.hygiene.tty == Tty::Inherit {
            sys::Session::Group
        } else {
            sys::Session::New
        };
        #[cfg(feature = "proxy")]
        let (listeners, overrides) = self.proxy_listeners(command)?;
        #[cfg(not(feature = "proxy"))]
        let overrides = Vec::new();
        let prepared = self.prepare(command, grants, fds, session, &overrides)?;
        // The link check is the last step before the fork.
        let run_audit = self.audit.before_spawn().map_err(SpawnError::HardLinks)?;
        // The record is registered before the fork, so no early denial is
        // missed.
        let report = match &prepared.run {
            Some(run) if self.violations => Some(violations::register(run.marker())),
            _ => None,
        };
        let names = grants.bindings.iter().map(|(n, _)| n.clone()).collect();
        Ok(Launch {
            prepared,
            run_audit,
            report,
            names,
            #[cfg(feature = "proxy")]
            listeners,
        })
    }

    /// The run's proxy listeners, the profile parameters for their ports,
    /// and the proxy variables set on `command`.
    #[cfg(feature = "proxy")]
    #[allow(clippy::type_complexity)]
    fn proxy_listeners(
        &self,
        command: &mut Command,
    ) -> Result<
        (
            Vec<(procage_proxy::Protocol, std::net::TcpListener)>,
            Vec<(String, String)>,
        ),
        SpawnError,
    > {
        let Some(proxied) = &self.proxied else {
            return Ok((Vec::new(), Vec::new()));
        };
        let listeners = proxied.bind().map_err(SpawnError::Io)?;
        let mut addrs = Vec::new();
        let mut overrides = Vec::new();
        for (protocol, listener) in &listeners {
            let addr = listener.local_addr().map_err(SpawnError::Io)?;
            let param = match protocol {
                procage_proxy::Protocol::Http => procage_policy::PROXY_HTTP_PARAM,
                procage_proxy::Protocol::Socks5 => procage_policy::PROXY_SOCKS_PARAM,
            };
            overrides.push((param.to_string(), format!("localhost:{}", addr.port())));
            addrs.push((*protocol, addr));
        }
        crate::proxied::set_env(command, &addrs);
        Ok((listeners, overrides))
    }

    /// The handle of the process `launch` was spawned as.
    pub(crate) fn adopt(&self, launch: Launch, inner: crate::unix::Proc) -> Child {
        let Launch {
            prepared,
            run_audit,
            report,
            mut names,
            #[cfg(feature = "proxy")]
            listeners,
        } = launch;
        let tmpdir = prepared.tmpdir.disarm();
        if tmpdir.is_some() {
            names.push(TMPDIR_GRANT.into());
        }
        #[cfg(feature = "proxy")]
        let proxy_run = self
            .proxied
            .as_ref()
            .and_then(|p| p.serve(listeners, report.clone()));
        #[cfg_attr(not(feature = "proxy"), allow(unused_mut))]
        let mut child = Child::new(
            inner,
            prepared.dropped,
            tmpdir,
            prepared.run,
            child::Reporting {
                forking: self.plan.run_marker,
                record: report,
            },
            crate::receipt::RunFacts::new(self.facts.clone(), names),
            run_audit,
        );
        #[cfg(feature = "proxy")]
        child.set_proxy(proxy_run);
        child
    }

    /// Turns the calling process into `command`, running in this cage: like
    /// std's [`CommandExt::exec`](std::os::unix::process::CommandExt::exec),
    /// it does not fork and returns only on failure.
    ///
    /// This is the entry point for a helper program that other code starts
    /// and owns (an MCP client, a terminal, `tokio::process::Command` with
    /// `kill_on_drop`): after `exec`, the helper's pid, standard streams,
    /// process group and exit status are the command's, so whatever kills
    /// or waits for the helper does so for the command. The confinement is
    /// the one [`Cage::spawn`] gives, except that the session and process
    /// group stay the caller's, and there is no [`Child`] handle:
    ///
    /// - the code that started the helper owns the lifetime. Start the
    ///   helper in its own process group and kill the group to end it;
    /// - descendants that stay in the process group die with that kill.
    ///   A descendant that starts its own session (which the macOS sandbox
    ///   cannot prevent) is not reached: when that matters, use
    ///   [`Cage::spawn`], whose handle finds such descendants.
    ///
    /// Everything that can be checked is checked before the process changes,
    /// and a failure leaves it as it was: a caller that is already
    /// sandboxed, the probe, grant bindings, the `tmpdir` grant (refused:
    /// nothing would remove the directory), the environment (see
    /// [`Cage::spawn`]) and a program that cannot be found. A failure after
    /// that ([`SpawnError::Apply`], or [`SpawnError::Io`] from `execvp`)
    /// leaves the process partly confined: the caller should exit.
    ///
    /// ```no_run
    /// # fn main() {
    /// use std::process::Command;
    /// use procage::native::{Cage, Grants};
    /// use procage::policy::{Base, Policy};
    ///
    /// let mut policy = Policy::default();
    /// policy.base = Base::V1;
    /// let cage = Cage::new(&policy).unwrap_or_else(|e| panic!("{e}"));
    /// let err = cage.exec(&mut Command::new("/bin/date"), &Grants::new());
    /// eprintln!("helper: {err}");
    /// std::process::exit(126);
    /// # }
    /// ```
    pub fn exec(&self, command: &mut Command, grants: &Grants) -> SpawnError {
        self.exec_with_fds(command, grants, &[])
    }

    /// Like [`Cage::exec`], and also keeps `fds` open across the exec, at the
    /// same numbers. Every other descriptor numbered 3 or higher is closed.
    pub fn exec_with_fds(
        &self,
        command: &mut Command,
        grants: &Grants,
        fds: &[BorrowedFd<'_>],
    ) -> SpawnError {
        use std::os::unix::process::CommandExt;
        if self.grant_slot(TMPDIR_GRANT).is_some() {
            return SpawnError::Grant(GrantError::TmpdirWithExec);
        }
        #[cfg(feature = "proxy")]
        if self.proxied.is_some() {
            // No handle would hold the run's proxy.
            return SpawnError::Unsupported(Unsupported::Setting {
                setting: "Cage::exec with CageOptions::with_proxy",
            });
        }
        match self.prepare(command, grants, fds, sys::Session::Keep, &[]) {
            // On success `exec` does not return; the run marker (forking
            // policies) is never searched: there is no handle.
            Ok(_prepared) => match self.audit.before_spawn() {
                Ok(_) => spawn::decode(command.exec()),
                Err(found) => SpawnError::HardLinks(found),
            },
            Err(e) => e,
        }
    }

    /// Everything before the fork (or the exec), without changing the
    /// calling process: checks, grant tokens, the environment, the run
    /// marker and the child sequence installed on `command`.
    fn prepare(
        &self,
        command: &mut Command,
        grants: &Grants,
        fds: &[BorrowedFd<'_>],
        session: sys::Session,
        overrides: &[(String, String)],
    ) -> Result<Prepared, SpawnError> {
        let lib = libsandbox()?;
        if lib.is_sandboxed() {
            return Err(SpawnError::AlreadySandboxed);
        }
        probe()?;
        let keep = kept_fds(fds.iter().map(AsRawFd::as_raw_fd))?;
        if grants.bindings.iter().any(|(name, _)| name == TMPDIR_GRANT) {
            return Err(SpawnError::Grant(GrantError::Reserved {
                name: TMPDIR_GRANT.into(),
            }));
        }
        let tmpdir = match self.grant_slot(TMPDIR_GRANT) {
            Some(_) => Some(crate::unix::private_tmpdir().map_err(SpawnError::Tmpdir)?),
            None => None,
        };
        let removal = TmpdirGuard(tmpdir.clone());
        let mut grants = grants.clone();
        if let Some(dir) = &tmpdir {
            grants = grants.bind(TMPDIR_GRANT, dir);
            if !command.get_envs().any(|(k, _)| k == "TMPDIR") {
                command.env("TMPDIR", dir);
            }
        }
        let tokens = spawn::tokens(lib, self, &grants)?;
        let dropped = crate::unix::environment(command, &self.plan.hygiene.env)
            .map_err(|_| SpawnError::Unsupported(Unsupported::EnvClear))?;
        if session == sys::Session::Keep {
            crate::unix::find_program(command).map_err(SpawnError::Io)?;
        }
        let (run, bytecode) = self.run_and_bytecode(lib, overrides)?;
        sys::ChildPlan {
            ops: lib.child_ops(),
            bytecode,
            tokens,
            limits: crate::unix::limits(&self.plan.hygiene.limits),
            session,
            keep,
            fd_buffer: sys::fd_buffer(),
        }
        .install(command);
        Ok(Prepared {
            dropped,
            tmpdir: removal,
            run,
        })
    }

    /// The run marker for a spawn of a forking policy, and the bytecode bound
    /// to it (compiled before the fork when the slot is not the first).
    fn run_and_bytecode(
        &self,
        lib: &sys::Libsandbox,
        overrides: &[(String, String)],
    ) -> Result<(Option<lifetime::Run>, Arc<[u8]>), SpawnError> {
        if !self.plan.run_marker && !self.violations {
            if overrides.is_empty() {
                return Ok((None, self.bytecode.clone()));
            }
            return Ok((None, compiled(lib, &self.plan, &[], overrides)?.0));
        }
        if self.plan.run_marker {
            lifetime::probe(lib)?;
        }
        let run = lifetime::Run::take();
        if run.is_first() && overrides.is_empty() {
            return Ok((Some(run), self.bytecode.clone()));
        }
        match compiled(lib, &self.plan, &run.params(), overrides) {
            Ok((bytecode, _)) => Ok((Some(run), bytecode)),
            Err(e) => {
                run.free();
                Err(e)
            }
        }
    }
}

/// A spawn up to the fork ([`Cage::launch`]).
pub(crate) struct Launch {
    prepared: Prepared,
    run_audit: crate::audit::RunAudit,
    report: Option<violations::Sink>,
    names: Vec<String>,
    #[cfg(feature = "proxy")]
    listeners: Vec<(procage_proxy::Protocol, std::net::TcpListener)>,
}

impl Launch {
    /// The spawn failed: no process is left behind, but the run's slot is
    /// retired (dropped) rather than freed, to stay on the safe side.
    pub(crate) fn abandon(self, e: std::io::Error) -> SpawnError {
        if let Some(run) = &self.prepared.run {
            violations::unregister(run.marker());
        }
        spawn::decode(e)
    }
}

/// What [`Cage::prepare`] made for one spawn.
struct Prepared {
    dropped: Vec<String>,
    tmpdir: TmpdirGuard,
    run: Option<lifetime::Run>,
}

/// The descriptors to hand over: those above the standard three, each of
/// which must be open.
fn kept_fds(fds: impl IntoIterator<Item = i32>) -> Result<Vec<i32>, SpawnError> {
    let keep: Vec<i32> = fds.into_iter().filter(|&fd| fd > 2).collect();
    match keep.iter().find(|&&fd| !sys::fd_is_open(fd)) {
        Some(&fd) => Err(SpawnError::Fd { fd }),
        None => Ok(keep),
    }
}

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

    #[test]
    fn a_descriptor_that_is_not_open_is_refused() {
        // `BorrowedFd` guarantees an open descriptor in safe code; the check
        // guards against one closed by another thread.
        let closed = 1_000_000;
        assert!(matches!(kept_fds([closed]), Err(SpawnError::Fd { fd }) if fd == closed));
        assert_eq!(kept_fds([0, 1, 2]).unwrap(), Vec::<i32>::new());
        let file = std::fs::File::open("/").unwrap();
        let fd = file.as_raw_fd();
        assert_eq!(kept_fds([fd]).unwrap(), vec![fd]);
    }
}

/// Probes for procage's own tests; not part of the API.
#[doc(hidden)]
pub mod testing {
    use super::{SpawnError, Unsupported, sys};

    /// Resolves `symbol` like the symbol table does.
    pub fn resolve_symbol(symbol: &'static str) -> Result<(), SpawnError> {
        if sys::has_symbol(symbol) {
            Ok(())
        } else {
            Err(SpawnError::Unsupported(Unsupported::Symbol {
                symbol,
                os_build: sys::os_build(),
            }))
        }
    }

    /// Ends the violation monitor's helper, as if it had died.
    pub fn stop_violation_monitor() {
        super::violations::stop();
    }

    /// The processes `child`'s run marker finds now (none without a marker).
    pub fn run_members(child: &super::Child) -> std::io::Result<Vec<u32>> {
        let Some(run) = child.run() else {
            return Ok(Vec::new());
        };
        let lib = super::libsandbox().map_err(std::io::Error::other)?;
        let pids = super::lifetime::members(lib, run)?;
        Ok(pids.into_iter().map(i32::cast_unsigned).collect())
    }

    /// The run-marker slot of `child`.
    pub fn run_slot(child: &super::Child) -> Option<u32> {
        child.run().map(super::lifetime::Run::slot)
    }

    /// Whether the calling process leads its own session.
    pub fn is_session_leader() -> bool {
        sys::is_session_leader()
    }

    /// Whether the calling process leads its own process group.
    pub fn is_group_leader() -> bool {
        sys::is_group_leader()
    }

    /// Contends for dyld's locks until `stop` is set.
    pub fn dyld_churn(stop: &std::sync::atomic::AtomicBool) {
        sys::dyld_churn(stop);
    }

    /// Clears close-on-exec on `fd`.
    pub fn clear_cloexec(fd: i32) -> bool {
        sys::clear_cloexec(fd).is_ok()
    }

    /// Whether `fd` is open in the calling process.
    pub fn fd_is_open(fd: i32) -> bool {
        sys::fd_is_open(fd)
    }

    /// Whether process `pid` exists.
    pub fn alive(pid: u32) -> bool {
        libc::pid_t::try_from(pid).is_ok_and(sys::alive)
    }

    /// Spawns `/bin/sleep 30`, in a new session when `setsid`.
    pub fn spawn_sleeper(setsid: bool) -> std::io::Result<u32> {
        sys::spawn_sleeper(setsid)
    }

    /// The soft limits for open files and core size.
    pub fn nofile_and_core() -> Option<(u64, u64)> {
        Some((
            sys::getrlimit(libc::RLIMIT_NOFILE)?.0,
            sys::getrlimit(libc::RLIMIT_CORE)?.0,
        ))
    }

    /// Looks up the Mach service `name`; the `kern_return_t` (0: found).
    pub fn mach_lookup(name: &str) -> i32 {
        std::ffi::CString::new(name).map_or(libc::EINVAL, |c| sys::mach_lookup(&c))
    }

    /// `fcntl(fd, cmd, 0)`; the errno, or 0 on success.
    pub fn fcntl_errno(fd: i32, cmd: i32) -> i32 {
        sys::fcntl_errno(fd, cmd)
    }

    /// Reads another process's arguments and environment
    /// (`KERN_PROCARGS2`); the errno, or 0.
    pub fn procargs_errno(pid: u32) -> i32 {
        libc::pid_t::try_from(pid).map_or(libc::EINVAL, sys::procargs_errno)
    }

    /// Reads another process's arguments through the older `KERN_PROCARGS`
    /// query; the errno, or 0.
    pub fn procargs1_errno(pid: u32) -> i32 {
        libc::pid_t::try_from(pid).map_or(libc::EINVAL, sys::procargs1_errno)
    }

    /// Reads a process's information (`proc_pidinfo`); the errno, or 0.
    pub fn pidinfo_errno(pid: u32) -> i32 {
        libc::pid_t::try_from(pid).map_or(libc::EINVAL, sys::pidinfo_errno)
    }

    /// `kill(pid, sig)`; the errno, or 0.
    pub fn kill_errno(pid: u32, sig: i32) -> i32 {
        libc::pid_t::try_from(pid).map_or(libc::EINVAL, |p| sys::kill_errno(p, sig))
    }

    /// A new pseudo-terminal: the controller and the path of the device.
    pub fn open_pty() -> std::io::Result<(std::os::fd::OwnedFd, std::path::PathBuf)> {
        sys::open_pty()
    }

    /// Makes the terminal `fd` the caller's controlling terminal
    /// (`TIOCSCTTY`); the errno, or 0.
    pub fn make_controlling(fd: i32) -> i32 {
        sys::ioctl_errno(fd, libc::TIOCSCTTY.into())
    }

    /// Pushes `byte` into the input of terminal `fd` (`TIOCSTI`); the
    /// errno, or 0.
    pub fn tiocsti_errno(fd: i32, byte: u8) -> i32 {
        sys::tiocsti_errno(fd, byte)
    }
}

/// What the receipts of a cage made for `policy` start from.
fn facts(
    policy: &Policy,
    options: &CageOptions,
    plan: &SeatbeltPlan,
    relaxed: &[Relaxed],
) -> crate::receipt::CageFacts {
    crate::receipt::CageFacts::new(
        policy,
        options.policy_in_receipt,
        crate::ReceiptBackend::MacOs {
            apply: "path-a".into(),
            os_release: sys::os_release(),
            os_build: sys::os_build(),
        },
        crate::receipt::approximations(&plan.degradations),
        relaxed,
    )
}

/// The audits of a cage for `policy` (resolved): the link check's targets,
/// with the class paths of every home under `/Users`, and the handoff
/// audit's trees.
fn cage_audit(
    policy: &Policy,
    options: &CageOptions,
) -> Result<crate::audit::CageAudit, SpawnError> {
    use procage_policy::{HardDenyClass, presets};
    use std::os::unix::ffi::OsStrExt;
    let homes: Vec<PathBuf> = std::fs::read_dir("/Users")
        .map(|e| {
            e.flatten()
                .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
                .map(|e| e.path())
                .collect()
        })
        .unwrap_or_default();
    let mut class_paths = Vec::new();
    if !policy.waive.contains(&HardDenyClass::Secrets) {
        class_paths.extend(crate::audit::class_paths(
            &homes,
            presets::SECRETS_HOME,
            &[],
            true,
        ));
    }
    if !policy.waive.contains(&HardDenyClass::TrustHandoff) {
        class_paths.extend(crate::audit::class_paths(
            &homes,
            presets::HANDOFF_HOME,
            &[],
            false,
        ));
    }
    if !policy.waive.contains(&HardDenyClass::Persistence) {
        let system: Vec<PathBuf> = presets::PERSISTENCE_SYSTEM
            .iter()
            .map(PathBuf::from)
            .collect();
        class_paths.extend(crate::audit::class_paths(
            &homes,
            presets::PERSISTENCE_HOME,
            &system,
            false,
        ));
    }
    let exempt = crate::audit::exemptions(&options.link_exempt, |p| {
        canon::resolve_existing(p)
            .ok()
            .map(|a| PathBuf::from(std::ffi::OsStr::from_bytes(a.as_bytes())))
    })
    .map_err(|setting| SpawnError::Unsupported(Unsupported::Setting { setting }))?;
    let targets = crate::audit::Targets::new(policy, class_paths, sys::uid()).exempting(exempt);
    let handoff = options.handoff_audit.then(|| {
        let trees = policy
            .fs
            .iter()
            .filter(|r| r.access == procage_policy::Access::Write)
            .filter_map(|r| match &r.target {
                procage_policy::FsTarget::Subpath(p) => {
                    Some(PathBuf::from(std::ffi::OsStr::from_bytes(p.as_bytes())))
                }
                _ => None,
            })
            .collect();
        let home = homes
            .iter()
            .flat_map(|h| presets::HANDOFF_HOME.iter().map(move |r| h.join(r)))
            .collect();
        (
            trees,
            presets::HANDOFF_ANYWHERE
                .iter()
                .map(|n| n.to_string())
                .collect(),
            home,
        )
    });
    Ok(crate::audit::CageAudit::new(
        options.link_audit,
        targets,
        handoff,
        options.walk_limit,
    ))
}