procage 0.4.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
//! Audits of what path rules cannot stop.
//!
//! **Link check (before every spawn, on by default).** A hard link gives a
//! file a second name, and path rules see names: a protected or hidden file
//! with another name in a writable or readable tree can be written or read
//! through it (escape class R-08). The other name may lie anywhere, but the
//! file itself shows it: its link count is above one. So before each spawn
//! procage examines the protected and hidden targets of the policy and the
//! existing files of the secrets, trust-handoff and persistence classes, and
//! with [`LinkAudit::Refuse`] (the default) refuses the spawn when one has
//! more than one name, or a literal target has become a symbolic link.
//! [`LinkAudit::Report`] lists them instead; [`LinkAudit::Off`] skips the
//! check. A subtree named with `CageOptions::with_link_exemption` is not
//! examined for protected files (a store whose files are never rewritten in
//! place, such as `.git/objects`, which a local clone hard-links); hidden
//! files are examined everywhere. Hard links to a protected or hidden file
//! cannot be made during a run: Seatbelt refuses to link a file the child
//! cannot write, Landlock links across directories only between writable
//! trees, and on Linux tier T1 protected and hidden targets are separate
//! mounts.
//!
//! **Handoff audit (after the run, opt-in).** Trust handoff is a program
//! outside the sandbox later running or following what the child wrote (R-07).
//! Where a path rule cannot hold (a file that did not exist at spawn on Linux,
//! a symbolic link the host follows), detection can: with the handoff audit,
//! procage notes the trust-handoff files, symbolic links and repository
//! directories of the writable trees before the run and lists, after it, what
//! was created or changed. The harness decides what to do with them.
//!
//! Both walks stay on the device they start on, never follow a symbolic link
//! and stop at the cage's walk limit; a result past the limit, or with an
//! entry that could not be read, is incomplete, never clean.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};

use procage_policy::linux::may_overlap;

/// What the link check does with a protected file that has another name.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum LinkAudit {
    /// Refuse the spawn (the default).
    #[default]
    Refuse,
    /// Spawn, and list the findings in [`Audit::links`].
    Report,
    /// Do not check.
    Off,
}

/// A protected, hidden or class file with another name.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LinkFinding {
    /// The file, as the policy or the class names it.
    pub path: PathBuf,
    /// Its link count.
    pub links: u64,
    /// The literal target is a symbolic link (not followed).
    pub symbolic: bool,
}

impl fmt::Display for LinkFinding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.symbolic {
            write!(f, "{} is a symbolic link", Escaped(&self.path))
        } else {
            write!(f, "{} has {} names", Escaped(&self.path), self.links)
        }
    }
}

/// What a run changed that an unsandboxed program may later trust.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum HandoffKind {
    /// A trust-handoff file that did not exist before the run.
    Created,
    /// A trust-handoff file the run changed.
    Modified,
    /// A symbolic link created (or retargeted) by the run, with its target
    /// as written (not resolved).
    Link {
        /// The link's target.
        target: PathBuf,
    },
    /// A repository metadata directory (`.git`) created by the run.
    Repository,
}

/// One thing the run left behind.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HandoffFinding {
    /// Where.
    pub path: PathBuf,
    /// What.
    pub kind: HandoffKind,
}

impl fmt::Display for HandoffFinding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let path = Escaped(&self.path);
        match &self.kind {
            HandoffKind::Created => write!(f, "{path} created"),
            HandoffKind::Modified => write!(f, "{path} modified"),
            HandoffKind::Link { target } => write!(f, "{path} -> {}", Escaped(target)),
            HandoffKind::Repository => write!(f, "{path}: repository created"),
        }
    }
}

/// A run's audits.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Audit {
    /// The link check's mode.
    pub mode: LinkAudit,
    /// Link findings (with [`LinkAudit::Report`]; a refused spawn has none).
    pub links: Vec<LinkFinding>,
    /// Whether the link check examined everything.
    pub links_complete: bool,
    /// Entries the link check examined.
    pub links_visited: usize,
    /// The subtrees the link check did not examine for protected files
    /// (see `CageOptions::with_link_exemption`).
    pub links_exempt: Vec<PathBuf>,
    /// What the run left behind, with the handoff audit.
    pub handoff: Option<Vec<HandoffFinding>>,
    /// Whether both handoff walks examined everything, and the run had
    /// ended before the second.
    pub handoff_complete: bool,
    /// Entries the handoff walks examined.
    pub handoff_visited: usize,
}

/// A path with control characters escaped, for messages.
struct Escaped<'a>(&'a Path);

impl fmt::Display for Escaped<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for c in self.0.to_string_lossy().chars() {
            if c.is_control() {
                write!(f, "{}", c.escape_default())?;
            } else {
                write!(f, "{c}")?;
            }
        }
        Ok(())
    }
}

/// Class entries the link check leaves out: large application data
/// (browser profiles) and folders macOS guards with privacy consent (Mail,
/// Messages, Safari, Cookies), which a walk on every spawn would slow down or
/// prompt for. The credential files of the classes are always examined.
const SKIPPED: &[&str] = &[
    ".config/BraveSoftware",
    ".config/chromium",
    ".config/google-chrome",
    ".config/microsoft-edge",
    ".mozilla",
    "Library/Application Support",
    "Library/Cookies",
    "Library/Mail",
    "Library/Messages",
    "Library/Safari",
];

/// The class paths to examine: each entry of `rels` in every home, except
/// [`SKIPPED`], and `system`; only those that exist.
pub(crate) fn class_paths(
    homes: &[PathBuf],
    rels: &[&str],
    system: &[PathBuf],
    hidden: bool,
) -> Vec<(PathBuf, bool)> {
    let mut out: Vec<PathBuf> = homes
        .iter()
        .flat_map(|h| {
            rels.iter()
                .filter(|r| !SKIPPED.iter().any(|s| r.starts_with(s)))
                .map(move |r| h.join(r))
        })
        .chain(system.iter().cloned())
        .filter(|p| std::fs::symlink_metadata(p).is_ok())
        .collect();
    out.sort();
    out.dedup();
    out.into_iter().map(|p| (p, hidden)).collect()
}

/// What the link check examines, built once per cage.
#[derive(Debug, Clone, Default)]
pub(crate) struct Targets {
    /// Literal protect and hide targets, and whether each is hidden.
    literal: Vec<(PathBuf, bool)>,
    /// Protect and hide subpaths: every file below.
    trees: Vec<(PathBuf, bool)>,
    /// The class paths: every file below, except in cache directories.
    classes: Vec<(PathBuf, bool)>,
    /// Protect and hide globs: the fixed prefix to walk and the pattern.
    /// Matching is conservative: a file that may match counts.
    globs: Vec<(PathBuf, String, bool)>,
    /// The caller's uid: a directory another user owns that the caller
    /// cannot search is skipped (see [`walk_skipping`]).
    caller: Option<u32>,
    /// Subtrees not examined for protected files.
    exempt: Vec<PathBuf>,
}

impl Targets {
    /// The targets of `policy` (resolved), plus `class_paths` (the class
    /// files and directories that exist in the homes, and the system ones).
    pub(crate) fn new(
        policy: &procage_policy::Policy,
        class_paths: Vec<(PathBuf, bool)>,
        caller: u32,
    ) -> Targets {
        use procage_policy::{Access, FsTarget};
        use std::os::unix::ffi::OsStrExt;
        let to_path = |b: &[u8]| PathBuf::from(std::ffi::OsStr::from_bytes(b));
        let mut t = Targets {
            classes: class_paths,
            caller: Some(caller),
            ..Targets::default()
        };
        for rule in &policy.fs {
            if !matches!(rule.access, Access::Protect | Access::Hide) {
                continue;
            }
            let hidden = rule.access == Access::Hide;
            match &rule.target {
                FsTarget::Literal(p) => t.literal.push((to_path(p.as_bytes()), hidden)),
                FsTarget::Subpath(p) => t.trees.push((to_path(p.as_bytes()), hidden)),
                FsTarget::Glob(g) => {
                    let source = g.as_str();
                    let prefix: Vec<&str> = source
                        .split('/')
                        .take_while(|c| !c.contains(['*', '?', '[', '{', '\\']))
                        .collect();
                    let prefix = prefix.join("/");
                    let prefix = if prefix.is_empty() {
                        "/".into()
                    } else {
                        prefix
                    };
                    t.globs
                        .push((PathBuf::from(prefix), source.to_string(), hidden));
                }
            }
        }
        t.literal.sort();
        t.literal.dedup();
        t.trees.sort();
        t.trees.dedup();
        t
    }

    /// These targets with `exempt` not examined for protected files.
    pub(crate) fn exempting(mut self, mut exempt: Vec<PathBuf>) -> Targets {
        exempt.sort();
        exempt.dedup();
        self.exempt = exempt;
        self
    }

    /// Whether a protected (not hidden) name at `path` is exempt.
    fn exempt(&self, path: &Path, hidden: bool) -> bool {
        !hidden && self.exempt.iter().any(|e| path.starts_with(e))
    }
}

/// The result of a link check.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct LinkResult {
    pub(crate) findings: Vec<LinkFinding>,
    pub(crate) complete: bool,
    pub(crate) visited: usize,
}

/// Runs the link check over `targets`, examining at most `limit` entries.
/// A file is a finding when it has more names than the check found among the
/// targets: names that all lie inside the protected set (a lock file and its
/// link in the same directory) give nothing away.
pub(crate) fn links(targets: &Targets, limit: usize) -> LinkResult {
    let mut r = LinkResult {
        complete: true,
        ..LinkResult::default()
    };
    let mut seen = Names::new();
    for (path, hidden) in &targets.literal {
        r.visited += 1;
        match std::fs::symlink_metadata(path) {
            Ok(m) if m.file_type().is_symlink() => r.findings.push(LinkFinding {
                path: path.clone(),
                links: m.nlink(),
                symbolic: true,
            }),
            Ok(_) if targets.exempt(path, *hidden) => {}
            Ok(m) => note(&mut seen, path, &m, *hidden),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(_) => r.complete = false,
        }
    }
    let caller = targets.caller;
    // An exempt subtree is neither walked nor counted for protected names.
    for (root, hidden) in &targets.trees {
        if targets.exempt(root, *hidden) {
            continue;
        }
        walk_skipping(
            root,
            limit,
            caller,
            &mut r,
            &mut |path, m, _| note(&mut seen, path, m, *hidden),
            &|dir| targets.exempt(dir, *hidden),
        );
    }
    for (root, hidden) in &targets.classes {
        if targets.exempt(root, *hidden) {
            continue;
        }
        walk_skipping(
            root,
            limit,
            caller,
            &mut r,
            &mut |path, m, _| note(&mut seen, path, m, *hidden),
            &|dir| cache(dir) || targets.exempt(dir, *hidden),
        );
    }
    for (prefix, pattern, hidden) in &targets.globs {
        let skip = |dir: &Path| targets.exempt(dir, *hidden);
        walk_skipping(
            prefix,
            limit,
            caller,
            &mut r,
            &mut |path, m, _| {
                if skip(path) {
                    return;
                }
                match glob_match(pattern, path) {
                    Some(true) => note(&mut seen, path, m, *hidden),
                    // Classes and alternatives are matched conservatively: the
                    // file is examined, but its name never counts as accounted
                    // for, so an over-matched alias cannot hide a finding.
                    None if may_overlap(pattern, path.as_os_str().as_encoded_bytes()) => {
                        note_unaccounted(&mut seen, path, m)
                    }
                    _ => {}
                }
            },
            &skip,
        );
    }
    for (path, links, names) in seen.into_values() {
        // Every name must be among the targets, and a hidden file's names
        // must all be hidden: a second name in a protected (readable) tree
        // would let the child read it.
        let hidden = names.values().any(|h| *h);
        let accounted = names.len() as u64 >= links && (!hidden || names.values().all(|h| *h));
        if !accounted {
            r.findings.push(LinkFinding {
                path,
                links,
                symbolic: false,
            });
        }
    }
    r.findings.sort();
    r.findings.dedup();
    r
}

/// Multi-link files by device and inode: the first name seen, the link
/// count, and every name seen among the targets with whether its target is
/// hidden (a hidden name wins over a protected one for the same path).
type Names = BTreeMap<(u64, u64), (PathBuf, u64, BTreeMap<PathBuf, bool>)>;

/// Whether `path` matches the glob `pattern` (`*` and `?` within a
/// component, `**` across components, `\` escapes); `None` when the
/// pattern uses classes or alternatives (`[…]`, `{…}`), which this does not
/// decide.
fn glob_match(pattern: &str, path: &Path) -> Option<bool> {
    if pattern.contains(['[', '{']) {
        return None;
    }
    fn component(p: &[u8], s: &[u8]) -> bool {
        match (p.first(), s.first()) {
            (None, None) => true,
            (Some(b'*'), _) => component(&p[1..], s) || (!s.is_empty() && component(p, &s[1..])),
            (Some(b'?'), Some(_)) => component(&p[1..], &s[1..]),
            (Some(b'\\'), Some(c)) if p.get(1) == Some(c) => component(&p[2..], &s[1..]),
            (Some(a), Some(b)) if a == b && *a != b'\\' => component(&p[1..], &s[1..]),
            _ => false,
        }
    }
    fn go(p: &[&[u8]], s: &[&[u8]]) -> bool {
        match p.first() {
            None => s.is_empty(),
            Some(&b"**") => go(&p[1..], s) || (!s.is_empty() && go(p, &s[1..])),
            Some(c) => !s.is_empty() && component(c, s[0]) && go(&p[1..], &s[1..]),
        }
    }
    let p: Vec<&[u8]> = pattern
        .as_bytes()
        .split(|b| *b == b'/')
        .filter(|c| !c.is_empty())
        .collect();
    let s: Vec<&[u8]> = path
        .as_os_str()
        .as_encoded_bytes()
        .split(|b| *b == b'/')
        .filter(|c| !c.is_empty())
        .collect();
    Some(go(&p, &s))
}

fn note_unaccounted(seen: &mut Names, path: &Path, m: &std::fs::Metadata) {
    if m.file_type().is_file() && m.nlink() > 1 {
        seen.entry((m.dev(), m.ino()))
            .or_insert_with(|| (path.to_path_buf(), m.nlink(), BTreeMap::new()));
    }
}

fn note(seen: &mut Names, path: &Path, m: &std::fs::Metadata, hidden: bool) {
    if m.file_type().is_file() && m.nlink() > 1 {
        *seen
            .entry((m.dev(), m.ino()))
            .or_insert_with(|| (path.to_path_buf(), m.nlink(), BTreeMap::new()))
            .2
            .entry(path.to_path_buf())
            .or_insert(false) |= hidden;
    }
}

/// Whether a directory inside a class path is a tool's cache (kubectl keeps
/// thousands of entries under `~/.kube/cache`): credentials are not kept in
/// caches, and walking them would slow every spawn.
fn cache(dir: &Path) -> bool {
    dir.file_name()
        .is_some_and(|n| n.to_string_lossy().to_ascii_lowercase().contains("cache"))
}

/// Walks `root` (not following links, not leaving its device), calling
/// `each` for every entry; marks `r` incomplete past `limit` or on an
/// unreadable entry. A missing root is nothing to walk.
///
/// With `caller`, a directory another user owns that the caller cannot
/// search is skipped, not incomplete (such as `/var/spool/cron/crontabs`):
/// the caller cannot have named its entries to link them, and the child,
/// running as the caller, cannot reach them. A directory the caller owns
/// stays incomplete: its mode is the caller's to change.
fn walk(
    root: &Path,
    limit: usize,
    caller: Option<u32>,
    r: &mut LinkResult,
    each: &mut dyn FnMut(&Path, &std::fs::Metadata, &mut LinkResult),
) {
    walk_skipping(root, limit, caller, r, each, &|_| false);
}

/// [`walk`], not descending into directories below `root` that `skip`
/// names.
fn walk_skipping(
    root: &Path,
    limit: usize,
    caller: Option<u32>,
    r: &mut LinkResult,
    each: &mut dyn FnMut(&Path, &std::fs::Metadata, &mut LinkResult),
    skip: &dyn Fn(&Path) -> bool,
) {
    let Ok(meta) = std::fs::symlink_metadata(root) else {
        return;
    };
    let dev = meta.dev();
    let mut stack = vec![(root.to_path_buf(), meta)];
    while let Some((path, meta)) = stack.pop() {
        if r.visited >= limit {
            r.complete = false;
            return;
        }
        r.visited += 1;
        each(&path, &meta, r);
        if !meta.file_type().is_dir() || meta.dev() != dev || (path != root && skip(&path)) {
            continue;
        }
        let Ok(entries) = std::fs::read_dir(&path) else {
            let closed = caller.is_some_and(|uid| {
                meta.uid() != uid
                    && std::fs::symlink_metadata(path.join("."))
                        .is_err_and(|e| e.kind() == std::io::ErrorKind::PermissionDenied)
            });
            if !closed {
                r.complete = false;
            }
            continue;
        };
        for entry in entries {
            let Ok(entry) = entry else {
                r.complete = false;
                continue;
            };
            match std::fs::symlink_metadata(entry.path()) {
                Ok(m) => stack.push((entry.path(), m)),
                Err(_) => r.complete = false,
            }
        }
    }
}

/// The handoff-relevant state of the writable trees at one moment.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Snapshot {
    files: BTreeMap<PathBuf, (u64, u64, i64, i64, i64, i64)>,
    links: BTreeMap<PathBuf, PathBuf>,
    repositories: BTreeSet<PathBuf>,
    complete: bool,
    visited: usize,
}

/// Whether `path` is a trust-handoff path: it is, or lies inside, an entry
/// of `anywhere` (names in any directory, such as `.git/hooks`) or of
/// `home` (absolute).
fn handoff_path(path: &Path, anywhere: &[String], home: &[PathBuf]) -> bool {
    let components: Vec<&std::ffi::OsStr> = path.iter().collect();
    anywhere.iter().any(|name| {
        let want: Vec<&str> = name.split('/').collect();
        components.windows(want.len()).any(|w| {
            w.iter()
                .zip(&want)
                .all(|(got, want)| *got == std::ffi::OsStr::new(want))
        })
    }) || home.iter().any(|h| path.starts_with(h))
}

impl Snapshot {
    /// The handoff files (`anywhere` names under the trees, and the `home`
    /// paths), symbolic links and `.git` directories under `trees`.
    pub(crate) fn take(
        trees: &[PathBuf],
        anywhere: &[String],
        home: &[PathBuf],
        limit: usize,
    ) -> Snapshot {
        let mut s = Snapshot {
            complete: true,
            ..Snapshot::default()
        };
        let mut r = LinkResult {
            complete: true,
            ..LinkResult::default()
        };
        for root in trees.iter().chain(home) {
            walk(root, limit, None, &mut r, &mut |path, m, _| {
                let t = m.file_type();
                if t.is_symlink() {
                    if let Ok(target) = std::fs::read_link(path) {
                        s.links.insert(path.to_path_buf(), target);
                    }
                    return;
                }
                if t.is_dir() && path.file_name().is_some_and(|n| n == ".git") {
                    s.repositories.insert(path.to_path_buf());
                }
                if handoff_path(path, anywhere, home) {
                    s.files.insert(
                        path.to_path_buf(),
                        (
                            m.ino(),
                            m.size(),
                            m.ctime(),
                            m.ctime_nsec(),
                            m.mtime(),
                            m.mtime_nsec(),
                        ),
                    );
                }
            });
        }
        s.complete = r.complete;
        s.visited = r.visited;
        s
    }
}

/// What changed from `before` to `after`, and whether both were complete.
pub(crate) fn handoff(before: &Snapshot, after: &Snapshot) -> (Vec<HandoffFinding>, bool) {
    let mut out = Vec::new();
    for (path, meta) in &after.files {
        match before.files.get(path) {
            None => out.push(HandoffFinding {
                path: path.clone(),
                kind: HandoffKind::Created,
            }),
            Some(old) if old != meta => out.push(HandoffFinding {
                path: path.clone(),
                kind: HandoffKind::Modified,
            }),
            Some(_) => {}
        }
    }
    for (path, target) in &after.links {
        if before.links.get(path) != Some(target) {
            out.push(HandoffFinding {
                path: path.clone(),
                kind: HandoffKind::Link {
                    target: target.clone(),
                },
            });
        }
    }
    for path in after.repositories.difference(&before.repositories) {
        out.push(HandoffFinding {
            path: path.clone(),
            kind: HandoffKind::Repository,
        });
    }
    out.sort();
    out.dedup();
    (out, before.complete && after.complete)
}

/// The link exemptions of a cage, each resolved with `resolve` where it
/// exists; `Err` when one is relative.
pub(crate) fn exemptions(
    paths: &[PathBuf],
    resolve: impl Fn(&Path) -> Option<PathBuf>,
) -> Result<Vec<PathBuf>, &'static str> {
    paths
        .iter()
        .map(|p| {
            if p.is_absolute() {
                Ok(resolve(p).unwrap_or_else(|| p.clone()))
            } else {
                Err("CageOptions::with_link_exemption with a relative path")
            }
        })
        .collect()
}

/// A cage's audits: built once, run for every spawn.
#[derive(Debug)]
pub(crate) struct CageAudit {
    mode: LinkAudit,
    targets: Targets,
    /// With the handoff audit: the writable trees, the handoff names in any
    /// directory, and the handoff paths in the homes.
    handoff: Option<(Vec<PathBuf>, Vec<String>, Vec<PathBuf>)>,
    limit: usize,
}

impl CageAudit {
    pub(crate) fn new(
        mode: LinkAudit,
        targets: Targets,
        handoff: Option<(Vec<PathBuf>, Vec<String>, Vec<PathBuf>)>,
        limit: usize,
    ) -> CageAudit {
        CageAudit {
            mode,
            targets,
            handoff,
            limit,
        }
    }

    /// The link check of one spawn, the last thing before the fork: `Err`
    /// with the findings when the mode refuses them.
    pub(crate) fn before_spawn(self: &std::sync::Arc<Self>) -> Result<RunAudit, Vec<LinkFinding>> {
        let links = match self.mode {
            // Nothing was examined, so nothing is known to be clean.
            LinkAudit::Off => LinkResult::default(),
            _ => links(&self.targets, self.limit),
        };
        if self.mode == LinkAudit::Refuse && !links.findings.is_empty() {
            return Err(links.findings);
        }
        let before = self
            .handoff
            .as_ref()
            .map(|(trees, anywhere, home)| Snapshot::take(trees, anywhere, home, self.limit));
        Ok(RunAudit {
            cage: self.clone(),
            links,
            before,
        })
    }
}

/// One run's audits.
#[derive(Debug)]
pub(crate) struct RunAudit {
    cage: std::sync::Arc<CageAudit>,
    links: LinkResult,
    before: Option<Snapshot>,
}

impl RunAudit {
    /// The audit of the run (the handoff audit walks again now). `ended`:
    /// every process of the run is gone; otherwise the handoff result is
    /// incomplete, since a survivor may still write.
    pub(crate) fn finish(&self, ended: bool) -> Audit {
        let (handoff, handoff_complete, handoff_visited) = match (&self.before, &self.cage.handoff)
        {
            (Some(before), Some((trees, anywhere, home))) => {
                let after = Snapshot::take(trees, anywhere, home, self.cage.limit);
                let (found, complete) = handoff(before, &after);
                (
                    Some(found),
                    complete && ended,
                    before.visited + after.visited,
                )
            }
            _ => (None, true, 0),
        };
        Audit {
            mode: self.cage.mode,
            links: self.links.findings.clone(),
            links_complete: self.links.complete,
            links_visited: self.links.visited,
            links_exempt: self.cage.targets.exempt.clone(),
            handoff,
            handoff_complete,
            handoff_visited,
        }
    }
}

/// The message of a refused spawn.
pub(crate) fn refusal(findings: &[LinkFinding]) -> String {
    let list: Vec<String> = findings.iter().map(ToString::to_string).collect();
    format!(
        "a protected, hidden or class file has another name, which path rules do not cover: {}; \
         remove the extra name, exempt a store whose files are never rewritten with \
         CageOptions::with_link_exemption, or choose LinkAudit::Report or LinkAudit::Off by name",
        list.join(", ")
    )
}

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

    fn scratch(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("procage-audit-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        std::fs::canonicalize(&d).unwrap()
    }

    #[test]
    fn a_second_name_is_found_from_the_protected_side() {
        let d = scratch("links");
        std::fs::create_dir_all(d.join("secret")).unwrap();
        std::fs::write(d.join("secret/key"), "k").unwrap();
        std::fs::write(d.join("secret/alone"), "a").unwrap();
        std::fs::hard_link(d.join("secret/key"), d.join("alias")).unwrap();
        let targets = Targets {
            trees: vec![(d.join("secret"), true)],
            ..Targets::default()
        };
        let r = links(&targets, 100);
        assert!(r.complete);
        assert_eq!(r.findings.len(), 1, "{:?}", r.findings);
        assert_eq!(r.findings[0].path, d.join("secret/key"));
        assert_eq!(r.findings[0].links, 2);
        let r = links(&targets, 1);
        assert!(!r.complete, "past the limit");
        // Both names inside the protected set (a lock file and its link)
        // give nothing away.
        std::fs::hard_link(d.join("secret/alone"), d.join("secret/.lock")).unwrap();
        let r = links(&targets, 100);
        assert_eq!(r.findings.len(), 1, "{:?}", r.findings);
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn an_exempt_store_is_skipped_for_protected_files_only() {
        // A local clone: the objects have a second name in the source
        // repository; the config does too.
        let d = scratch("exempt");
        std::fs::create_dir_all(d.join("ws/.git/objects/ab")).unwrap();
        std::fs::create_dir_all(d.join("src/.git/objects/ab")).unwrap();
        std::fs::write(d.join("src/.git/objects/ab/cd"), "blob").unwrap();
        std::fs::hard_link(
            d.join("src/.git/objects/ab/cd"),
            d.join("ws/.git/objects/ab/cd"),
        )
        .unwrap();
        std::fs::write(d.join("ws/.git/config"), "[core]").unwrap();
        std::fs::hard_link(d.join("ws/.git/config"), d.join("config")).unwrap();
        let protect = Targets {
            trees: vec![(d.join("ws/.git"), false)],
            ..Targets::default()
        };
        let all = links(&protect, 100).findings;
        assert_eq!(all.len(), 2, "{all:?}");
        let exempt = protect.exempting(vec![d.join("ws/.git/objects")]);
        let r = links(&exempt, 100);
        assert!(r.complete);
        assert_eq!(r.findings.len(), 1, "{:?}", r.findings);
        assert_eq!(r.findings[0].path, d.join("ws/.git/config"));
        // An exempt literal target and an exempt tree root are skipped too.
        let root = Targets {
            trees: vec![(d.join("ws/.git/objects"), false)],
            literal: vec![(d.join("ws/.git/objects/ab/cd"), false)],
            ..Targets::default()
        }
        .exempting(vec![d.join("ws/.git/objects")]);
        assert!(links(&root, 100).findings.is_empty());
        // A hidden file is examined inside an exempt subtree.
        let hidden = Targets {
            trees: vec![(d.join("ws/.git"), true)],
            ..Targets::default()
        }
        .exempting(vec![d.join("ws/.git/objects")]);
        assert_eq!(links(&hidden, 100).findings.len(), 2);
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn a_literal_target_that_became_a_link_is_a_finding() {
        let d = scratch("symlink");
        std::fs::write(d.join("real"), "r").unwrap();
        std::os::unix::fs::symlink(d.join("real"), d.join("env")).unwrap();
        let targets = Targets {
            literal: vec![(d.join("env"), true), (d.join("missing"), true)],
            ..Targets::default()
        };
        let r = links(&targets, 100);
        assert_eq!(r.findings.len(), 1);
        assert!(r.findings[0].symbolic);
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn what_a_run_left_behind_is_listed_once() {
        let d = scratch("handoff");
        std::fs::create_dir_all(d.join(".vscode")).unwrap();
        std::fs::write(d.join(".vscode/settings.json"), "{}").unwrap();
        let anywhere = vec![".vscode".to_string(), ".git/hooks".to_string()];
        let before = Snapshot::take(std::slice::from_ref(&d), &anywhere, &[], 1000);
        std::thread::sleep(std::time::Duration::from_millis(20));
        std::fs::write(d.join(".vscode/settings.json"), "{\"x\":1}").unwrap();
        std::fs::write(d.join(".vscode/tasks.json"), "{}").unwrap();
        std::fs::create_dir_all(d.join("sub/.git/hooks")).unwrap();
        std::fs::write(d.join("sub/.git/hooks/pre-commit"), "#!/bin/sh").unwrap();
        std::os::unix::fs::symlink("/etc/passwd", d.join("build")).unwrap();
        std::fs::write(d.join("plain.txt"), "x").unwrap();
        let after = Snapshot::take(std::slice::from_ref(&d), &anywhere, &[], 1000);
        let (found, complete) = handoff(&before, &after);
        assert!(complete);
        let has =
            |p: &str, k: &HandoffKind| found.iter().any(|f| f.path == d.join(p) && &f.kind == k);
        assert!(
            has(".vscode/settings.json", &HandoffKind::Modified),
            "{found:?}"
        );
        assert!(
            has(".vscode/tasks.json", &HandoffKind::Created),
            "{found:?}"
        );
        assert!(
            has("sub/.git/hooks/pre-commit", &HandoffKind::Created),
            "{found:?}"
        );
        assert!(has("sub/.git", &HandoffKind::Repository), "{found:?}");
        assert!(
            has(
                "build",
                &HandoffKind::Link {
                    target: PathBuf::from("/etc/passwd")
                }
            ),
            "{found:?}"
        );
        assert!(
            !found.iter().any(|f| f.path == d.join("plain.txt")),
            "{found:?}"
        );
        let _ = std::fs::remove_dir_all(&d);
    }

    /// A hidden file whose second name lies in a protected (readable) tree is
    /// a finding; both names in hidden trees are not.
    #[test]
    fn a_hidden_file_needs_every_name_hidden() {
        let d = scratch("strict");
        for dir in ["hidden", "protected", "hidden2"] {
            std::fs::create_dir_all(d.join(dir)).unwrap();
        }
        std::fs::write(d.join("hidden/key"), "k").unwrap();
        std::fs::hard_link(d.join("hidden/key"), d.join("protected/key")).unwrap();
        let targets = Targets {
            trees: vec![(d.join("hidden"), true), (d.join("protected"), false)],
            ..Targets::default()
        };
        assert_eq!(links(&targets, 100).findings.len(), 1);
        std::fs::remove_file(d.join("protected/key")).unwrap();
        std::fs::hard_link(d.join("hidden/key"), d.join("hidden2/key")).unwrap();
        let targets = Targets {
            trees: vec![(d.join("hidden"), true), (d.join("hidden2"), true)],
            ..Targets::default()
        };
        assert!(links(&targets, 100).findings.is_empty());
        let _ = std::fs::remove_dir_all(&d);
    }

    /// Walks never follow a link (a loop, or one out of the tree) and mark
    /// an unreadable directory incomplete.
    #[test]
    fn walks_stay_put_and_say_what_they_could_not_read() {
        use std::os::unix::fs::PermissionsExt;
        let d = scratch("walk");
        std::fs::create_dir_all(d.join("t/sub")).unwrap();
        std::os::unix::fs::symlink(d.join("t"), d.join("t/sub/loop")).unwrap();
        std::os::unix::fs::symlink("/", d.join("t/out")).unwrap();
        let targets = Targets {
            trees: vec![(d.join("t"), false)],
            ..Targets::default()
        };
        let r = links(&targets, 1000);
        assert!(r.complete);
        assert!(r.visited < 10, "followed a link: {}", r.visited);
        std::fs::create_dir_all(d.join("t/closed")).unwrap();
        std::fs::set_permissions(d.join("t/closed"), std::fs::Permissions::from_mode(0o0)).unwrap();
        let unreadable = std::fs::read_dir(d.join("t/closed")).is_err();
        let r = links(&targets, 1000);
        let mine = std::fs::metadata(d.join("t")).unwrap().uid();
        let owned = links(
            &Targets {
                caller: Some(mine),
                ..targets.clone()
            },
            1000,
        );
        // Seen from another user, the closed directory is someone else's.
        let foreign = links(
            &Targets {
                caller: Some(mine.wrapping_add(1)),
                ..targets.clone()
            },
            1000,
        );
        std::fs::set_permissions(d.join("t/closed"), std::fs::Permissions::from_mode(0o755))
            .unwrap();
        if unreadable {
            assert!(!r.complete, "an unreadable directory is incomplete");
            assert!(!owned.complete, "the caller can reopen its own directory");
            assert!(
                foreign.complete,
                "another user's closed directory is skipped"
            );
        }
        let _ = std::fs::remove_dir_all(&d);
    }

    /// Refuse fails only on findings: an incomplete check with none lets the
    /// spawn run and says it was incomplete; Off says nothing is known.
    #[test]
    fn incomplete_is_never_clean_and_never_a_refusal() {
        let d = scratch("incomplete");
        std::fs::create_dir_all(d.join("t")).unwrap();
        for i in 0..5 {
            std::fs::write(d.join(format!("t/{i}")), "x").unwrap();
        }
        let targets = Targets {
            trees: vec![(d.join("t"), true)],
            ..Targets::default()
        };
        let cage = std::sync::Arc::new(CageAudit::new(LinkAudit::Refuse, targets.clone(), None, 2));
        let run = cage.before_spawn().expect("no finding, no refusal");
        assert!(!run.finish(true).links_complete);
        let off = std::sync::Arc::new(CageAudit::new(LinkAudit::Off, targets, None, 2));
        assert!(!off.before_spawn().unwrap().finish(true).links_complete);
        let _ = std::fs::remove_dir_all(&d);
    }

    /// A rewrite of the same size with the modification time set back is
    /// still a change: the change time cannot be set back.
    #[test]
    fn a_disguised_rewrite_is_modified() {
        let d = scratch("disguise");
        std::fs::create_dir_all(d.join(".vscode")).unwrap();
        let file = d.join(".vscode/settings.json");
        std::fs::write(&file, "aaaa").unwrap();
        let mtime = std::fs::metadata(&file).unwrap().modified().unwrap();
        let anywhere = vec![".vscode".to_string()];
        let before = Snapshot::take(std::slice::from_ref(&d), &anywhere, &[], 100);
        std::thread::sleep(std::time::Duration::from_millis(20));
        std::fs::write(&file, "bbbb").unwrap();
        std::fs::File::options()
            .write(true)
            .open(&file)
            .unwrap()
            .set_modified(mtime)
            .unwrap();
        let after = Snapshot::take(std::slice::from_ref(&d), &anywhere, &[], 100);
        let (found, _) = handoff(&before, &after);
        assert!(
            found
                .iter()
                .any(|f| f.path == file && f.kind == HandoffKind::Modified),
            "{found:?}"
        );
        let _ = std::fs::remove_dir_all(&d);
    }

    /// The refusal names every file with its link count and the remedies.
    #[test]
    fn the_refusal_names_every_file_and_the_way_out() {
        let found = [
            LinkFinding {
                path: PathBuf::from("/w/.env"),
                links: 2,
                symbolic: false,
            },
            LinkFinding {
                path: PathBuf::from("/home/u/.ssh/id"),
                links: 3,
                symbolic: false,
            },
        ];
        let text = refusal(&found);
        assert!(text.contains("/w/.env has 2 names"), "{text}");
        assert!(text.contains("/home/u/.ssh/id has 3 names"), "{text}");
        assert!(
            text.contains("LinkAudit::Report") && text.contains("LinkAudit::Off"),
            "{text}"
        );
    }

    /// A credential file of a class (hidden) with a name outside, and a file
    /// under a glob target with one, are findings; multi-link files that are
    /// no target are none of the check's business.
    #[test]
    fn class_files_and_globs_are_examined_and_nothing_else() {
        let d = scratch("classes");
        std::fs::create_dir_all(d.join("home/.ssh")).unwrap();
        std::fs::create_dir_all(d.join("ws/conf")).unwrap();
        std::fs::write(d.join("home/.ssh/id"), "k").unwrap();
        std::fs::hard_link(d.join("home/.ssh/id"), d.join("ws/id")).unwrap();
        std::fs::write(d.join("ws/conf/app.toml"), "x").unwrap();
        std::fs::hard_link(d.join("ws/conf/app.toml"), d.join("ws/app-alias")).unwrap();
        std::fs::write(d.join("ws/plain"), "x").unwrap();
        std::fs::hard_link(d.join("ws/plain"), d.join("ws/plain2")).unwrap();
        let classes = class_paths(&[d.join("home")], &[".ssh"], &[], true);
        let pattern = format!("{}/ws/**/*.toml", d.display());
        let targets = Targets {
            classes,
            globs: vec![(d.join("ws"), pattern, false)],
            ..Targets::default()
        };
        assert_eq!(
            glob_match("/a/**/*.toml", Path::new("/a/b/c.toml")),
            Some(true)
        );
        assert_eq!(
            glob_match("/a/**/*.toml", Path::new("/a/c.toml")),
            Some(true)
        );
        assert_eq!(
            glob_match("/a/**/*.toml", Path::new("/a/app-alias")),
            Some(false)
        );
        assert_eq!(glob_match("/a/?.rs", Path::new("/a/x.rs")), Some(true));
        assert_eq!(glob_match("/a/\\*", Path::new("/a/x")), Some(false));
        assert_eq!(glob_match("/a/[ab]", Path::new("/a/a")), None);
        let r = links(&targets, 1000);
        let paths: Vec<&PathBuf> = r.findings.iter().map(|f| &f.path).collect();
        assert!(paths.contains(&&d.join("home/.ssh/id")), "{paths:?}");
        assert!(paths.contains(&&d.join("ws/conf/app.toml")), "{paths:?}");
        assert!(
            !paths
                .iter()
                .any(|p| p.ends_with("plain") || p.ends_with("plain2")),
            "{paths:?}"
        );
        let _ = std::fs::remove_dir_all(&d);
    }

    #[test]
    fn control_characters_are_escaped_in_messages() {
        let f = LinkFinding {
            path: PathBuf::from("/w/a\nb"),
            links: 2,
            symbolic: false,
        };
        assert_eq!(f.to_string(), "/w/a\\nb has 2 names");
    }
}