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 ~/.ssh/id_rsa — above the authored ladder → Denied
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::Denied);
185
186        // touch build/out — create·worktree·data → write-local → SafeWrite (the
187        // to_legacy `_ => SafeWrite` arm; no resolver emits this yet)
188        let write = Profile::of(vec![{
189            let mut c = Capability::new(Operation::Create);
190            c.locus.local = LocalLocus::Worktree;
191            c.scale = Scale::Bounded;
192            c.reversibility = Reversibility::Recoverable;
193            c.persistence.level = PersistenceLevel::Data;
194            c
195        }]);
196        assert_eq!(project(&write), Verdict::Allowed(SafetyLevel::SafeWrite));
197
198        // an EMPTY profile must fail closed (Denied), NOT project to inert — every level
199        // vacuously admits it, so the guard is what stops "resolved to nothing" = "safe".
200        assert_eq!(project(&Profile::of(vec![])), Verdict::Denied);
201    }
202
203    /// The fail-open this refactor had to avoid: the levels above developer (local-admin,
204    /// network-admin, yolo) have NO legacy `SafetyLevel`, so a profile only they admit must
205    /// project to `Denied` — never to `SafeWrite`. The old `_ => SafeWrite` catch-all in
206    /// `to_legacy` would have auto-approved every one of these.
207    #[test]
208    fn profiles_needing_an_upper_level_project_to_denied_not_safewrite() {
209        // sudo systemctl restart — elevated authority on machine locus (local-admin)
210        let sudo = Profile::of(vec![{
211            let mut c = Capability::new(Operation::Control);
212            c.locus.local = LocalLocus::Machine;
213            c.authority = Authority::Root;
214            c
215        }]);
216        assert_eq!(project(&sudo), Verdict::Denied, "sudo must not auto-approve");
217
218        // terraform apply — remote reach over outbound network (network-admin)
219        let remote = Profile::of(vec![{
220            let mut c = Capability::new(Operation::Mutate);
221            c.locus.remote = RemoteReach::Fixed;
222            c.network.direction = NetDirection::Outbound;
223            c
224        }]);
225        assert_eq!(project(&remote), Verdict::Denied, "remote infra must not auto-approve");
226
227        // terraform destroy — irreversible remote destroy (yolo only)
228        let catastrophe = Profile::of(vec![{
229            let mut c = Capability::new(Operation::Destroy);
230            c.locus.remote = RemoteReach::Fixed;
231            c.reversibility = Reversibility::Irreversible;
232            c
233        }]);
234        assert_eq!(project(&catastrophe), Verdict::Denied, "irreversible destroy must not auto-approve");
235    }
236
237    /// The legacy classifier's leaf verdict for `cmd` — what the engine falls back to for a
238    /// command it can't resolve, and the baseline the never-looser gates compare against.
239    fn legacy(cmd: &str) -> Verdict {
240        crate::handlers::dispatch(&toks(&cmd.split_whitespace().collect::<Vec<_>>()))
241    }
242
243    #[test]
244    fn the_engine_is_authoritative_with_legacy_fallback() {
245        // a resolved command → the engine's (finer) verdict, end to end
246        assert_eq!(
247            crate::command_verdict("cat ./notes.md"),
248            Verdict::Allowed(SafetyLevel::SafeRead),
249            "cat resolves → engine tightens inert to read-local",
250        );
251        // an unresolvable command → the legacy classifier still decides
252        let unresolved = resolve::UNRESOLVED_CMD.join(" ");
253        assert_eq!(
254            crate::command_verdict(&unresolved),
255            legacy(&unresolved),
256            "no resolver → legacy verdict",
257        );
258    }
259
260    #[test]
261    fn engine_verdict_is_none_for_unresearched_commands() {
262        assert!(engine_verdict(&toks(resolve::UNRESOLVED_CMD)).is_none());
263        assert_eq!(engine_verdict(&toks(&["echo", "hi"])), Some(Verdict::Allowed(SafetyLevel::Inert)));
264        assert_eq!(
265            engine_verdict(&toks(&["cat", "./notes.md"])),
266            Some(Verdict::Allowed(SafetyLevel::SafeRead)),
267        );
268        assert_eq!(engine_verdict(&toks(&["cat", "~/.ssh/id_rsa"])), Some(Verdict::Denied));
269    }
270
271    /// The engine may deny what legacy allowed (intended tightening) or classify higher,
272    /// but must **never allow what legacy denied**, nor classify lower.
273    fn not_looser(legacy: Verdict, engine: Verdict) -> bool {
274        match (legacy, engine) {
275            (_, Verdict::Denied) => true,
276            (Verdict::Denied, Verdict::Allowed(_)) => false,
277            (Verdict::Allowed(l), Verdict::Allowed(e)) => e >= l,
278        }
279    }
280
281    /// The rollout safety gate on hand-picked forms — including the ones the wiring and
282    /// the review flushed (unrecognized/dangerous flags, and pattern-less grep, which
283    /// legacy denies as a usage error).
284    #[test]
285    fn the_engine_is_never_looser_than_legacy() {
286        let cases = [
287            "echo hi", "echo", "cat ./notes.md", "cat -n ./notes.md", "cat ~/.ssh/id_rsa",
288            "cat /etc/hosts", "cat a.txt b.txt", "grep foo src/main.rs", "grep -r foo src/",
289            "grep -r foo ~", "grep foo bar.txt",
290            // PCRE (-P/--perl-regexp) is benign — PCRE2 execs no code, just a regex engine
291            "grep -P foo file", "grep -oP foo file", "grep --perl-regexp foo file",
292            // unrecognized / dangerous flags must worst-case
293            "cat --unknownflag ./x", "cat -Z ./x", "grep --wat foo file",
294            // pattern-less grep (C1): legacy denies as a usage error, engine must too
295            "grep", "grep -r", "grep -i", "grep -e foo", "grep -f patterns.txt",
296        ];
297        for cmd in cases {
298            let base = legacy(cmd);
299            let t = toks(&cmd.split_whitespace().collect::<Vec<_>>());
300            let Some(engine) = engine_verdict(&t) else { continue };
301            assert!(
302                not_looser(base, engine),
303                "engine LOOSER than legacy for `{cmd}`: legacy {base}, engine {engine}",
304            );
305        }
306    }
307
308    /// The never-looser invariant above holds over the commands legacy *allowlisted*. The
309    /// `developer` level is the deliberate exception: it admits well-modeled operations the
310    /// hand-built allowlist could only DENY — e.g. deleting your own project files. This
311    /// test pins that divergence as intended, not a regression: it is exactly the kind of
312    /// finer classification the engine exists to make, now that it is authoritative.
313    #[test]
314    fn developer_intentionally_admits_worktree_destroy_that_legacy_denies() {
315        let rm = "rm -rf ./node_modules";
316        assert_eq!(legacy(rm), Verdict::Denied, "legacy allowlist denies rm deletion");
317        assert_eq!(crate::command_verdict(rm), Verdict::Allowed(SafetyLevel::SafeWrite), "engine (developer) admits it — intended");
318        assert!(!not_looser(Verdict::Denied, Verdict::Allowed(SafetyLevel::SafeWrite)), "and it IS looser than legacy, by design");
319    }
320
321    /// sed/tar keep coarse legacy HANDLERS (`coreutils::sed`/`tar`) that `handlers::dispatch`
322    /// consults before the TOML — so `legacy()` for them is that handler, which denies an in-place
323    /// edit. The behavioral engine models `sed -i` on a worktree file correctly (a SafeWrite) and is
324    /// authoritative. Pin the divergence as intended (not a regression) — the same shape as `rm`
325    /// above — because the corpus gate's sed examples deliberately avoid this looser case.
326    #[test]
327    fn engine_intentionally_admits_worktree_in_place_edit_that_legacy_sed_handler_denies() {
328        let sed = "sed -i s/a/b/ ./file.txt";
329        assert_eq!(legacy(sed), Verdict::Denied, "legacy sed handler denies in-place edit");
330        assert_eq!(crate::command_verdict(sed), Verdict::Allowed(SafetyLevel::SafeWrite), "engine admits worktree -i — intended");
331        assert!(!not_looser(Verdict::Denied, Verdict::Allowed(SafetyLevel::SafeWrite)), "and it IS looser than the legacy sed handler, by design");
332    }
333
334    /// The data-driven corpus gate (the systematic test C1 slipped past): run **every**
335    /// command's real `examples_safe`/`examples_denied` through the engine and assert,
336    /// per resolvable example, the dimensions that hold today —
337    ///   1. **never looser** than legacy (engine ≤ legacy; also subsumes "an
338    ///      examples_denied that resolves stays denied", since legacy denies it),
339    ///   2. **justified** — every resolved capability cites a `because` (§5),
340    ///   3. **total** — resolution and projection never panic.
341    ///
342    /// It grows automatically as commands convert; today it exercises the resolvable
343    /// commands and skips the rest. Only bare single commands are comparable at the leaf
344    /// (chains/redirects/substitutions are the CST's job). The full per-facet completeness
345    /// dimension is the golden-profile check (`resolve::golden_profiles_cover_every_facet`)
346    /// and becomes TOML-derived when commands carry profile data (§7).
347    #[test]
348    fn the_engine_corpus_gate() {
349        let mut exercised = 0usize;
350        for (name, safe, denied) in crate::registry::corpus_examples() {
351            for ex in safe.iter().chain(denied.iter()) {
352                if ex.contains(['|', '>', '<', '&', ';', '$', '`', '(', '\n']) {
353                    continue; // not a bare single command
354                }
355                let t = toks(&ex.split_whitespace().collect::<Vec<_>>());
356                let Some(profile) = crate::engine::resolve::resolve(&t) else { continue };
357                exercised += 1;
358
359                for c in &profile.capabilities {
360                    assert!(!c.because.is_empty(), "unjustified capability for `{ex}` ({name})");
361                }
362
363                // A PROFILED sub's legacy kind is deny-all — a fail-closed placeholder for when the
364                // engine ABSTAINS (a global flag before the sub), NOT a real hand-built verdict. So the
365                // never-looser comparison is meaningless for it: the engine is authoritative and
366                // legitimately admits below the line (`npm ci --ignore-scripts` at developer). Its
367                // landing is pinned by the archetype tests, not here.
368                if crate::registry::sub_archetypes(&t).is_some() {
369                    continue;
370                }
371                // The one deliberate refinement. An informational invocation (`rm --help`) prints
372                // usage and exits, so it is genuinely Inert, while the legacy path classified it at
373                // the command's declared WRITE level. That reads as "looser" to this ratchet
374                // because Inert is admitted by stricter user levels (a `paranoid` plan accepts it),
375                // but it is the engine being more accurate, not more permissive about effects.
376                //
377                // Deliberately narrow: long-form help/version ONLY, and no other token. The risk it
378                // would carry — an informational flag laundering a real operand — is what
379                // `an_informational_flag_is_not_a_write_but_never_launders_an_operand` exists to
380                // rule out, and it is asserted over the whole registry rather than here.
381                if t.len() >= 2
382                    && t[1..].iter().all(|x| matches!(x.as_str(), "--help" | "--version"))
383                {
384                    continue;
385                }
386                let engine = project(&profile);
387                let base = legacy(ex);
388                assert!(
389                    not_looser(base, engine),
390                    "engine LOOSER than legacy for `{ex}` ({name}): legacy {base}, engine {engine}",
391                );
392            }
393        }
394        // non-vacuity: the gate must actually resolve engine examples, or it is a green
395        // test proving nothing (the trap that hid its own emptiness). Every resolvable
396        // command must contribute at least one example.
397        assert!(exercised >= 5, "corpus gate exercised only {exercised} engine resolutions — vacuous?");
398    }
399
400    /// Per-level threshold wiring end to end: an UPPER-band `--level` classifies via `admits`,
401    /// unlocking profiles that only an upper level admits, while the lower band and the
402    /// allowlist-only fail-closed reflex are untouched.
403    #[test]
404    fn upper_band_levels_admit_via_the_engine_end_to_end() {
405        let net = crate::upper_level_by_name("network-admin").expect("network-admin exists");
406        let yolo = crate::upper_level_by_name("yolo").expect("yolo exists");
407
408        // git push origin — a network-admin op. THE payoff: denied at the default (developer)
409        // band, admitted once the threshold IS an upper level.
410        assert_eq!(crate::command_verdict("git push origin main"), Verdict::Denied, "developer denies push");
411        assert!(crate::command_verdict_at_level("git push origin main", net).is_allowed(), "network-admin admits push");
412        assert!(crate::command_verdict_at_level("git push origin main", yolo).is_allowed(), "yolo admits push");
413
414        // rm -rf / — the one thing even yolo denies (destroy·irreversible·unbounded).
415        assert_eq!(crate::command_verdict_at_level("rm -rf /", yolo), Verdict::Denied, "yolo denies rm -rf /");
416
417        // a plain read passes at every upper level (they extend reader).
418        assert!(crate::command_verdict_at_level("cat ./README.md", net).is_allowed(), "reads pass at network-admin");
419
420        // a legacy-DENIED / unmodeled command stays denied even at yolo — allowlist-only: what
421        // the engine cannot certify, no threshold can approve.
422        assert_eq!(crate::command_verdict_at_level("frobnicate --wombat", yolo), Verdict::Denied, "unmodeled denied at yolo");
423
424        // a chain is admitted only if EVERY segment is (a Denied dominates the combine).
425        assert_eq!(crate::command_verdict_at_level("git push && rm -rf /", yolo), Verdict::Denied, "one bad segment sinks the chain");
426
427        // the upper-band lookup rejects lower-band and unknown names (they keep the 3-value ceiling).
428        assert!(crate::upper_level_by_name("developer").is_none());
429        assert!(crate::upper_level_by_name("reader").is_none());
430        assert!(crate::upper_level_by_name("nonsense").is_none());
431
432        // the lower band is UNCHANGED — no eval-level context, projection still tightens cat to read.
433        assert_eq!(crate::command_verdict("cat ./README.md"), Verdict::Allowed(SafetyLevel::SafeRead), "lower band untouched");
434    }
435}