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