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