Skip to main content

safe_chains/engine/
bridge.rs

1//! Engine bridge (v1.4 §4.5; annex `…-engine` §4). Projects a resolved capability profile
2//! back to a legacy [`Verdict`] so the existing ceiling gate (`main::run_cli`) keeps working
3//! unchanged. The engine is authoritative for every command it can resolve
4//! (`resolve::resolve` → `Some`); the legacy classifier handles the rest. There is no
5//! opt-out — `cst::check::leaf_verdict` calls `engine_verdict(tokens).unwrap_or(legacy)`.
6
7use std::cell::Cell;
8
9use super::authoring::default_levels;
10use super::facet::Profile;
11use super::level::{FacetMismatch, Level};
12use super::resolve;
13use crate::parse::Token;
14use crate::verdict::{SafetyLevel, Verdict};
15
16thread_local! {
17    /// The level a `--level` threshold selected. When set, `project` decides via `Level::admits`
18    /// against THIS level instead of walking the band for the lowest level that admits — which is
19    /// the only way a profile that just one level admits (`git push`, `sudo`) can be approved, and
20    /// the only way a level whose rule the 3-value projection cannot express (`editor`: no
21    /// destroy, no sibling write) can be enforced.
22    ///
23    /// Every named level sets it now. It was upper-band-only while `project` stamped a pass as
24    /// `SafeWrite`, which a lower ceiling then refused; see the note there.
25    ///
26    /// `None` (the default — no `--level` given) keeps the byte-for-byte default-band behavior, so
27    /// `command_verdict` / `is_safe_command` and every existing test are unaffected.
28    static EVAL_LEVEL: Cell<Option<&'static Level>> = const { Cell::new(None) };
29}
30
31/// Evaluate the enclosed classification against `level` (an upper-band level). Restores the
32/// previous context on drop. Mirrors `pathctx::enter`.
33pub fn enter_eval_level(level: &'static Level) -> EvalLevelGuard {
34    EvalLevelGuard(EVAL_LEVEL.with(|c| c.replace(Some(level))))
35}
36
37pub struct EvalLevelGuard(Option<&'static Level>);
38
39impl Drop for EvalLevelGuard {
40    fn drop(&mut self) {
41        EVAL_LEVEL.with(|c| c.set(self.0));
42    }
43}
44
45/// The engine's verdict for a command whose resolver exists, or `None` if it has none
46/// (the caller keeps the legacy verdict).
47pub fn engine_verdict(tokens: &[Token]) -> Option<Verdict> {
48    resolve::resolve(tokens).map(|p| project(&p))
49}
50
51/// [`engine_verdict`], with the path gate the legacy dispatch applies also applied to an engine
52/// approval: a profile describes what a subcommand does, not which file a flag names, so
53/// `git commit -F ~/.ssh/id_rsa` resolves to a worktree commit while it reads the key.
54pub fn gated_engine_verdict(tokens: &[Token]) -> Option<Verdict> {
55    let verdict = engine_verdict(tokens)?;
56    let cmd = crate::registry::canonical_name(tokens.first()?.command_name());
57    Some(if verdict.is_allowed() && crate::pathgate::should_deny(cmd, tokens) { Verdict::Denied } else { verdict })
58}
59
60/// Project a resolved profile to a legacy [`Verdict`]: the **lowest** authored level
61/// that admits it, mapped back to its legacy [`SafetyLevel`]; `Denied` if no
62/// legacy-mapped level admits it (above the auto-approve band → worst-case, §0).
63/// `default_levels()` builds the ascending chain (paranoid ⊂ reader ⊂ editor ⊂
64/// developer), so the first match among the mapped levels is the minimum.
65pub fn project(profile: &Profile) -> Verdict {
66    if profile.capabilities.is_empty() {
67        // Fail-closed (§0): an empty profile means the resolver produced NO capability.
68        // Every level vacuously admits it (`all` of zero capabilities is true), so without
69        // this guard it would project to the lowest level (`paranoid`) — the *most*
70        // permissive, inverting the principle. A genuinely-inert command emits an explicit
71        // observe capability, never an empty profile.
72        return Verdict::Denied;
73    }
74    if let Some(level) = EVAL_LEVEL.with(Cell::get) {
75        // A selected `--level` is authoritative via `admits`: a profile it does not admit is
76        // `Denied`, dominating the chain.
77        if !level.admits(profile) {
78            return Verdict::Denied;
79        }
80        // A pass projects to the band the PROFILE earns — not a fixed `SafeWrite`.
81        //
82        // It was fixed, and correctly so for every level this path originally served: the upper
83        // band and `editor` all carry a `SafeWrite` ceiling, so `run_cli`'s `<= ceiling` gate
84        // accepted the stamp. It silently breaks any level whose ceiling is LOWER. At `reader`
85        // (SafeRead) or `paranoid` (Inert) the gate then refused the very profile the level had
86        // just admitted — `cat ./notes.txt` denied at `--level reader`.
87        //
88        // That is why `level_ceiling` handed an engine level to `editor` and the upper band only:
89        // giving one to reader/paranoid would have denied their whole band. The workaround became
90        // the cause of the `level_monotonic` failure — `editor` classified by `admits` while its
91        // neighbours classified by projection, so two mechanisms sat adjacent in one ordered
92        // ladder with nothing making them agree.
93        //
94        // `unwrap_or(SafeWrite)` keeps the upper band byte-identical: those levels have no legacy
95        // equivalent, so `to_legacy` yields `None` for them and they keep the shared ceiling.
96        return Verdict::Allowed(to_legacy(&level.name).unwrap_or(SafetyLevel::SafeWrite));
97    }
98    for level in default_levels() {
99        // Only the auto-approvable band (paranoid..developer) has a 3-value legacy
100        // equivalent. The levels above it (local-admin, network-admin, yolo) have NO
101        // legacy mapping, so a profile that only THEY admit projects to Denied — never
102        // silently to SafeWrite (the old `_ => SafeWrite` catch-all would have
103        // auto-approved sudo/terraform the moment those levels were added). Selecting
104        // an upper level as a threshold is the separate harness-config change.
105        if let Some(sl) = to_legacy(&level.name)
106            && level.admits(profile)
107        {
108            return Verdict::Allowed(sl);
109        }
110    }
111    Verdict::Denied
112}
113
114/// The most permissive level in the default auto-approve band.
115fn default_band_top_level() -> Option<&'static Level> {
116    default_levels().iter().rfind(|l| to_legacy(&l.name).is_some())
117}
118
119/// The NAME of that level — what a refusal is reported against when the user has set no ceiling of
120/// their own (`developer`, today).
121///
122/// Exposed so `--explain`'s "refused by `X`" and the decision log's `level` field come from one
123/// definition. They were briefly two: the log took `SafetyLevel::to_string()` and recorded the
124/// LEGACY band name (`safe-write`) for the same run `--explain` called `developer`, which is the
125/// kind of disagreement that makes a diagnostic worse than no diagnostic.
126pub fn default_band_top_name() -> &'static str {
127    default_band_top_level().map_or("developer", |l| l.name.as_str())
128}
129
130fn to_legacy(level_name: &str) -> Option<SafetyLevel> {
131    match level_name {
132        "paranoid" => Some(SafetyLevel::Inert),
133        "reader" => Some(SafetyLevel::SafeRead),
134        "editor" | "developer" => Some(SafetyLevel::SafeWrite),
135        _ => None, // local-admin, network-admin, yolo — above the legacy 3-value ceiling
136    }
137}
138
139/// A human-readable account of what a command resolved to and, when the band rejects it, which
140/// facet said no.
141///
142/// The engine was write-only before this: `admits` answered yes/no and nothing reported the axis.
143/// Both a user asking "why was this denied" and an author debugging a resolver were left bisecting
144/// by editing facets and re-running — which is exactly how an incomplete loopback delta got
145/// mistaken for a flawed approach rather than a missing line.
146pub struct ProfileExplanation {
147    /// One entry per capability: its `because` and the facets it sets.
148    pub capabilities: Vec<(String, Vec<(&'static str, &'static str)>)>,
149    /// `(level name, why it refuses)` — absent when the band admits the profile.
150    pub blocked_by: Option<(String, FacetMismatch)>,
151}
152
153/// Resolve `tokens` and explain the result. `None` when no resolver claims the command, which is
154/// itself the answer: the engine never saw it and the legacy classifier decided.
155pub fn explain_profile(tokens: &[Token]) -> Option<ProfileExplanation> {
156    let profile = resolve::resolve(tokens)?;
157    let capabilities = profile.capabilities.iter().map(|c| (c.because.clone(), c.set_facets())).collect();
158
159    // Report against the MOST PERMISSIVE level in the auto-approve band. If the top of the band
160    // refuses a capability, every level below it does too, so its complaint is the binding one —
161    // a lower level's would just be the first of several walls.
162    let blocked_by = default_band_top_level()
163        .and_then(|top| profile.capabilities.iter().find_map(|c| top.nearest_miss(c).map(|m| (top.name.clone(), m))));
164
165    Some(ProfileExplanation { capabilities, blocked_by })
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171    use crate::engine::facet::*;
172
173    fn toks(parts: &[&str]) -> Vec<Token> {
174        parts.iter().map(|p| Token::from_test(p)).collect()
175    }
176
177    #[test]
178    fn project_maps_profiles_to_the_lowest_admitting_level() {
179        // echo — inert
180        let echo = Profile::of(vec![{
181            let mut c = Capability::new(Operation::Observe);
182            c.disclosure.audience = DisclosureAudience::LocalProcess;
183            c
184        }]);
185        assert_eq!(project(&echo), Verdict::Allowed(SafetyLevel::Inert));
186
187        // cat ./notes — read-local
188        let read = Profile::of(vec![{
189            let mut c = Capability::new(Operation::Observe);
190            c.locus.local = LocalLocus::Worktree;
191            c.disclosure.audience = DisclosureAudience::LocalProcess;
192            c
193        }]);
194        assert_eq!(project(&read), Verdict::Allowed(SafetyLevel::SafeRead));
195
196        // cat ~/notes.txt — observe·user·no-secret is inside the reader band now
197        let home = Profile::of(vec![{
198            let mut c = Capability::new(Operation::Observe);
199            c.locus.local = LocalLocus::User;
200            c.disclosure.audience = DisclosureAudience::LocalProcess;
201            c
202        }]);
203        assert_eq!(project(&home), Verdict::Allowed(SafetyLevel::SafeRead));
204
205        // cat ~/.ssh/id_rsa — the SAME rung, refused on the secret claim rather than the locus.
206        // The pair is the point: one facet apart, and it is the facet that names the harm.
207        let secret = Profile::of(vec![{
208            let mut c = Capability::new(Operation::Observe);
209            c.locus.local = LocalLocus::User;
210            c.disclosure.audience = DisclosureAudience::LocalProcess;
211            c.secret.level = SecretLevel::Reads;
212            c
213        }]);
214        assert_eq!(project(&secret), Verdict::Denied);
215
216        // touch build/out — create·worktree·data → write-local → SafeWrite (the
217        // to_legacy `_ => SafeWrite` arm; no resolver emits this yet)
218        let write = Profile::of(vec![{
219            let mut c = Capability::new(Operation::Create);
220            c.locus.local = LocalLocus::Worktree;
221            c.scale = Scale::Bounded;
222            c.reversibility = Reversibility::Recoverable;
223            c.persistence.level = PersistenceLevel::Data;
224            c
225        }]);
226        assert_eq!(project(&write), Verdict::Allowed(SafetyLevel::SafeWrite));
227
228        // an EMPTY profile must fail closed (Denied), NOT project to inert — every level
229        // vacuously admits it, so the guard is what stops "resolved to nothing" = "safe".
230        assert_eq!(project(&Profile::of(vec![])), Verdict::Denied);
231    }
232
233    /// The fail-open this refactor had to avoid: the levels above developer (local-admin,
234    /// network-admin, yolo) have NO legacy `SafetyLevel`, so a profile only they admit must
235    /// project to `Denied` — never to `SafeWrite`. The old `_ => SafeWrite` catch-all in
236    /// `to_legacy` would have auto-approved every one of these.
237    #[test]
238    fn profiles_needing_an_upper_level_project_to_denied_not_safewrite() {
239        // sudo systemctl restart — elevated authority on machine locus (local-admin)
240        let sudo = Profile::of(vec![{
241            let mut c = Capability::new(Operation::Control);
242            c.locus.local = LocalLocus::Machine;
243            c.authority = Authority::Root;
244            c
245        }]);
246        assert_eq!(project(&sudo), Verdict::Denied, "sudo must not auto-approve");
247
248        // terraform apply — remote reach over outbound network (network-admin)
249        let remote = Profile::of(vec![{
250            let mut c = Capability::new(Operation::Mutate);
251            c.locus.remote = RemoteReach::Fixed;
252            c.network.direction = NetDirection::Outbound;
253            c
254        }]);
255        assert_eq!(project(&remote), Verdict::Denied, "remote infra must not auto-approve");
256
257        // terraform destroy — irreversible remote destroy (yolo only)
258        let catastrophe = Profile::of(vec![{
259            let mut c = Capability::new(Operation::Destroy);
260            c.locus.remote = RemoteReach::Fixed;
261            c.reversibility = Reversibility::Irreversible;
262            c
263        }]);
264        assert_eq!(project(&catastrophe), Verdict::Denied, "irreversible destroy must not auto-approve");
265    }
266
267    /// The legacy classifier's leaf verdict for `cmd` — what the engine falls back to for a
268    /// command it can't resolve, and the baseline the never-looser gates compare against.
269    fn legacy(cmd: &str) -> Verdict {
270        crate::handlers::dispatch(&toks(&cmd.split_whitespace().collect::<Vec<_>>()))
271    }
272
273    #[test]
274    fn the_engine_is_authoritative_with_legacy_fallback() {
275        // a resolved command → the engine's (finer) verdict, end to end
276        assert_eq!(
277            crate::command_verdict("cat ./notes.md"),
278            Verdict::Allowed(SafetyLevel::SafeRead),
279            "cat resolves → engine tightens inert to read-local",
280        );
281        // an unresolvable command → the legacy classifier still decides
282        let unresolved = resolve::UNRESOLVED_CMD.join(" ");
283        assert_eq!(crate::command_verdict(&unresolved), legacy(&unresolved), "no resolver → legacy verdict",);
284    }
285
286    #[test]
287    fn engine_verdict_is_none_for_unresearched_commands() {
288        assert!(engine_verdict(&toks(resolve::UNRESOLVED_CMD)).is_none());
289        assert_eq!(engine_verdict(&toks(&["echo", "hi"])), Some(Verdict::Allowed(SafetyLevel::Inert)));
290        assert_eq!(engine_verdict(&toks(&["cat", "./notes.md"])), Some(Verdict::Allowed(SafetyLevel::SafeRead)),);
291        assert_eq!(engine_verdict(&toks(&["cat", "~/.ssh/id_rsa"])), Some(Verdict::Denied));
292    }
293
294    /// The engine may deny what legacy allowed (intended tightening) or classify higher,
295    /// but must **never allow what legacy denied**, nor classify lower.
296    fn not_looser(legacy: Verdict, engine: Verdict) -> bool {
297        match (legacy, engine) {
298            (_, Verdict::Denied) => true,
299            (Verdict::Denied, Verdict::Allowed(_)) => false,
300            (Verdict::Allowed(l), Verdict::Allowed(e)) => e >= l,
301        }
302    }
303
304    /// The rollout safety gate on hand-picked forms — including the ones the wiring and
305    /// the review flushed (unrecognized/dangerous flags, and pattern-less grep, which
306    /// legacy denies as a usage error).
307    #[test]
308    fn the_engine_is_never_looser_than_legacy() {
309        let cases = [
310            "echo hi", "echo", "cat ./notes.md", "cat -n ./notes.md", "cat ~/.ssh/id_rsa", "cat /etc/hosts", "cat a.txt b.txt",
311            "grep foo src/main.rs", "grep -r foo src/", "grep -r foo ~", "grep foo bar.txt",
312            // PCRE (-P/--perl-regexp) is benign — PCRE2 execs no code, just a regex engine
313            "grep -P foo file", "grep -oP foo file", "grep --perl-regexp foo file",
314            // unrecognized / dangerous flags must worst-case
315            "cat --unknownflag ./x", "cat -Z ./x", "grep --wat foo file",
316            // pattern-less grep (C1): legacy denies as a usage error, engine must too
317            "grep", "grep -r", "grep -i", "grep -e foo", "grep -f patterns.txt",
318        ];
319        for cmd in cases {
320            let base = legacy(cmd);
321            let t = toks(&cmd.split_whitespace().collect::<Vec<_>>());
322            let Some(engine) = engine_verdict(&t) else { continue };
323            assert!(not_looser(base, engine), "engine LOOSER than legacy for `{cmd}`: legacy {base}, engine {engine}",);
324        }
325    }
326
327    /// The never-looser invariant above holds over the commands legacy *allowlisted*. The
328    /// `developer` level is the deliberate exception: it admits well-modeled operations the
329    /// hand-built allowlist could only DENY — e.g. deleting your own project files. This
330    /// test pins that divergence as intended, not a regression: it is exactly the kind of
331    /// finer classification the engine exists to make, now that it is authoritative.
332    #[test]
333    fn developer_intentionally_admits_worktree_destroy_that_legacy_denies() {
334        let rm = "rm -rf ./node_modules";
335        assert_eq!(legacy(rm), Verdict::Denied, "legacy allowlist denies rm deletion");
336        assert_eq!(crate::command_verdict(rm), Verdict::Allowed(SafetyLevel::SafeWrite), "engine (developer) admits it — intended");
337        assert!(!not_looser(Verdict::Denied, Verdict::Allowed(SafetyLevel::SafeWrite)), "and it IS looser than legacy, by design");
338    }
339
340    /// sed/tar keep coarse legacy HANDLERS (`coreutils::sed`/`tar`) that `handlers::dispatch`
341    /// consults before the TOML — so `legacy()` for them is that handler, which denies an in-place
342    /// edit. The behavioral engine models `sed -i` on a worktree file correctly (a SafeWrite) and is
343    /// authoritative. Pin the divergence as intended (not a regression) — the same shape as `rm`
344    /// above — because the corpus gate's sed examples deliberately avoid this looser case.
345    #[test]
346    fn engine_intentionally_admits_worktree_in_place_edit_that_legacy_sed_handler_denies() {
347        let sed = "sed -i s/a/b/ ./file.txt";
348        assert_eq!(legacy(sed), Verdict::Denied, "legacy sed handler denies in-place edit");
349        assert_eq!(crate::command_verdict(sed), Verdict::Allowed(SafetyLevel::SafeWrite), "engine admits worktree -i — intended");
350        assert!(
351            !not_looser(Verdict::Denied, Verdict::Allowed(SafetyLevel::SafeWrite)),
352            "and it IS looser than the legacy sed handler, by design"
353        );
354    }
355
356    /// The data-driven corpus gate (the systematic test C1 slipped past): run **every**
357    /// command's real `examples_safe`/`examples_denied` through the engine and assert,
358    /// per resolvable example, the dimensions that hold today —
359    ///   1. **never looser** than legacy (engine ≤ legacy; also subsumes "an
360    ///      examples_denied that resolves stays denied", since legacy denies it),
361    ///   2. **justified** — every resolved capability cites a `because` (§5),
362    ///   3. **total** — resolution and projection never panic.
363    ///
364    /// It grows automatically as commands convert; today it exercises the resolvable
365    /// commands and skips the rest. Only bare single commands are comparable at the leaf
366    /// (chains/redirects/substitutions are the CST's job). The full per-facet completeness
367    /// dimension is the golden-profile check (`resolve::golden_profiles_cover_every_facet`)
368    /// and becomes TOML-derived when commands carry profile data (§7).
369    #[test]
370    fn the_engine_corpus_gate() {
371        let mut exercised = 0usize;
372        for (name, safe, denied) in crate::registry::corpus_examples() {
373            for ex in safe.iter().chain(denied.iter()) {
374                if ex.contains(['|', '>', '<', '&', ';', '$', '`', '(', '\n']) {
375                    continue; // not a bare single command
376                }
377                let t = toks(&ex.split_whitespace().collect::<Vec<_>>());
378                let Some(profile) = crate::engine::resolve::resolve(&t) else { continue };
379                exercised += 1;
380
381                for c in &profile.capabilities {
382                    assert!(!c.because.is_empty(), "unjustified capability for `{ex}` ({name})");
383                }
384
385                // A PROFILED sub's legacy kind is deny-all — a fail-closed placeholder for when the
386                // engine ABSTAINS (a global flag before the sub), NOT a real hand-built verdict. So the
387                // never-looser comparison is meaningless for it: the engine is authoritative and
388                // legitimately admits below the line (`npm ci --ignore-scripts` at developer). Its
389                // landing is pinned by the archetype tests, not here.
390                if crate::registry::sub_archetypes(&t).is_some() {
391                    continue;
392                }
393                // The one deliberate refinement. An informational invocation (`rm --help`) prints
394                // usage and exits, so it is genuinely Inert, while the legacy path classified it at
395                // the command's declared WRITE level. That reads as "looser" to this ratchet
396                // because Inert is admitted by stricter user levels (a `paranoid` plan accepts it),
397                // but it is the engine being more accurate, not more permissive about effects.
398                //
399                // Deliberately narrow: long-form help/version ONLY, and no other token. The risk it
400                // would carry — an informational flag laundering a real operand — is what
401                // `an_informational_flag_is_not_a_write_but_never_launders_an_operand` exists to
402                // rule out, and it is asserted over the whole registry rather than here.
403                if t.len() >= 2 && t[1..].iter().all(|x| matches!(x.as_str(), "--help" | "--version")) {
404                    continue;
405                }
406                let engine = project(&profile);
407                let base = legacy(ex);
408                assert!(not_looser(base, engine), "engine LOOSER than legacy for `{ex}` ({name}): legacy {base}, engine {engine}",);
409            }
410        }
411        // non-vacuity: the gate must actually resolve engine examples, or it is a green
412        // test proving nothing (the trap that hid its own emptiness). Every resolvable
413        // command must contribute at least one example.
414        assert!(exercised >= 5, "corpus gate exercised only {exercised} engine resolutions — vacuous?");
415    }
416
417    /// Per-level threshold wiring end to end: an UPPER-band `--level` classifies via `admits`,
418    /// unlocking profiles that only an upper level admits, while the lower band and the
419    /// allowlist-only fail-closed reflex are untouched.
420    #[test]
421    fn upper_band_levels_admit_via_the_engine_end_to_end() {
422        let net = crate::upper_level_by_name("network-admin").expect("network-admin exists");
423        let yolo = crate::upper_level_by_name("yolo").expect("yolo exists");
424
425        // git push origin — a network-admin op. THE payoff: denied at the default (developer)
426        // band, admitted once the threshold IS an upper level.
427        assert_eq!(crate::command_verdict("git push origin main"), Verdict::Denied, "developer denies push");
428        assert!(crate::command_verdict_at_level("git push origin main", net).is_allowed(), "network-admin admits push");
429        assert!(crate::command_verdict_at_level("git push origin main", yolo).is_allowed(), "yolo admits push");
430
431        // rm -rf / — the one thing even yolo denies (destroy·irreversible·unbounded).
432        assert_eq!(crate::command_verdict_at_level("rm -rf /", yolo), Verdict::Denied, "yolo denies rm -rf /");
433
434        // a plain read passes at every upper level (they extend reader).
435        assert!(crate::command_verdict_at_level("cat ./README.md", net).is_allowed(), "reads pass at network-admin");
436
437        // a legacy-DENIED / unmodeled command stays denied even at yolo — allowlist-only: what
438        // the engine cannot certify, no threshold can approve.
439        assert_eq!(crate::command_verdict_at_level("frobnicate --wombat", yolo), Verdict::Denied, "unmodeled denied at yolo");
440
441        // a chain is admitted only if EVERY segment is (a Denied dominates the combine).
442        assert_eq!(crate::command_verdict_at_level("git push && rm -rf /", yolo), Verdict::Denied, "one bad segment sinks the chain");
443
444        // the upper-band lookup rejects lower-band and unknown names (they keep the 3-value ceiling).
445        assert!(crate::upper_level_by_name("developer").is_none());
446        assert!(crate::upper_level_by_name("reader").is_none());
447        assert!(crate::upper_level_by_name("nonsense").is_none());
448
449        // the lower band is UNCHANGED — no eval-level context, projection still tightens cat to read.
450        assert_eq!(crate::command_verdict("cat ./README.md"), Verdict::Allowed(SafetyLevel::SafeRead), "lower band untouched");
451    }
452
453    // ── properties ────────────────────────────────────────────────────────────
454    //
455    // Generators live in `crate::engine::testgen` (shared with the level/authoring
456    // property tests). No eval-level is set in these tests, so `project` exercises
457    // the default-band walk on every case.
458    use crate::engine::testgen::{arb_capability, arb_profile};
459    use proptest::prelude::*;
460
461    /// How permissive a projected verdict is: `Denied` the least, then down the legacy ladder,
462    /// since an `Allowed(Inert)` is approved under every threshold and a `SafeWrite` only under
463    /// the highest.
464    fn permissiveness(verdict: Verdict) -> u8 {
465        match verdict {
466            Verdict::Denied => 0,
467            Verdict::Allowed(sl) => 3 - sl as u8,
468        }
469    }
470
471    fn observing(local: LocalLocus) -> Capability {
472        let mut c = Capability::new(Operation::Observe);
473        c.locus.local = local;
474        c.disclosure.audience = DisclosureAudience::LocalProcess;
475        c
476    }
477
478    /// Capabilities the band admits, mixed into the generated ones: two generated capabilities
479    /// are almost never admitted together, which left the monotonicity property nearly vacuous.
480    fn mostly_admitted_capability() -> impl Strategy<Value = Capability> {
481        prop_oneof![
482            arb_capability(),
483            Just(observing(LocalLocus::Process)),
484            Just(observing(LocalLocus::Worktree)),
485            Just(observing(LocalLocus::User)),
486        ]
487    }
488
489    #[test]
490    fn reading_the_worktree_after_echoing_is_less_permissive_than_echoing() {
491        let echo = Profile::of(vec![observing(LocalLocus::Process)]);
492        let both = Profile::of(vec![observing(LocalLocus::Process), observing(LocalLocus::Worktree)]);
493        assert_eq!((project(&echo), project(&both)), (Verdict::Allowed(SafetyLevel::Inert), Verdict::Allowed(SafetyLevel::SafeRead)));
494        assert!(permissiveness(project(&both)) < permissiveness(project(&echo)));
495    }
496
497    /// The straightforward reading of `project`'s contract, written independently: the
498    /// empty profile fails closed; otherwise the first level in the ascending chain
499    /// with a legacy mapping that admits the profile decides; nothing → `Denied`.
500    fn reference_project(profile: &Profile) -> Verdict {
501        if profile.capabilities.is_empty() {
502            return Verdict::Denied;
503        }
504        for level in default_levels() {
505            if let Some(sl) = to_legacy(&level.name)
506                && level.admits(profile)
507            {
508                return Verdict::Allowed(sl);
509            }
510        }
511        Verdict::Denied
512    }
513
514    proptest! {
515        /// Differential: `project` agrees with the direct band walk on every profile.
516        #[test]
517        fn projection_matches_a_direct_walk_of_the_band(profile in arb_profile()) {
518            prop_assert_eq!(project(&profile), reference_project(&profile));
519        }
520
521        /// Minimality: an `Allowed(sl)` verdict is EARNED by the first band level
522        /// mapping to `sl` (it admits the profile) and by nothing lower — every
523        /// legacy-mapped level strictly before it refuses the profile. That is what
524        /// "lowest admitting level" (the doc on `project`) means.
525        #[test]
526        fn an_allowed_projection_is_earned_by_that_level_and_refused_by_every_lower_one(profile in arb_profile()) {
527            let Verdict::Allowed(sl) = project(&profile) else {
528                return Ok(()); // a Denied admits no minimality claim
529            };
530            let mapped: Vec<&Level> = default_levels().iter().filter(|l| to_legacy(&l.name).is_some()).collect();
531            let pos = mapped.iter().position(|l| to_legacy(&l.name) == Some(sl) && l.admits(&profile));
532            let pos = pos.expect("the level the verdict names must admit the profile");
533            for lower in &mapped[..pos] {
534                prop_assert!(!lower.admits(&profile), "`{}` projects at a lower level than the verdict claims", lower.name);
535            }
536        }
537
538        /// Monotonicity: a profile passes a level iff EVERY capability is admissible,
539        /// so adding a capability can only shrink the admitting levels — the
540        /// projection can never become MORE permissive by doing more. The empty profile is
541        /// denied by `project` on purpose, so profiles are drawn with at least one capability.
542        #[test]
543        fn adding_a_capability_never_makes_the_projection_more_permissive(
544            capabilities in prop::collection::vec(mostly_admitted_capability(), 1..4),
545            extra in mostly_admitted_capability(),
546        ) {
547            let profile = Profile::of(capabilities);
548            let mut more = profile.clone();
549            more.capabilities.push(extra.clone());
550            prop_assert!(
551                permissiveness(project(&more)) <= permissiveness(project(&profile)),
552                "doing more became more permissive: {profile:?} -> {extra:?}",
553            );
554        }
555    }
556}