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
86fn to_legacy(level_name: &str) -> Option<SafetyLevel> {
87    match level_name {
88        "paranoid" => Some(SafetyLevel::Inert),
89        "reader" => Some(SafetyLevel::SafeRead),
90        "editor" | "developer" => Some(SafetyLevel::SafeWrite),
91        _ => None, // local-admin, network-admin, yolo — above the legacy 3-value ceiling
92    }
93}
94
95/// A human-readable account of what a command resolved to and, when the band rejects it, which
96/// facet said no.
97///
98/// The engine was write-only before this: `admits` answered yes/no and nothing reported the axis.
99/// Both a user asking "why was this denied" and an author debugging a resolver were left bisecting
100/// by editing facets and re-running — which is exactly how an incomplete loopback delta got
101/// mistaken for a flawed approach rather than a missing line.
102pub struct ProfileExplanation {
103    /// One entry per capability: its `because` and the facets it sets.
104    pub capabilities: Vec<(String, Vec<(&'static str, &'static str)>)>,
105    /// `(level name, why it refuses)` — absent when the band admits the profile.
106    pub blocked_by: Option<(String, FacetMismatch)>,
107}
108
109/// Resolve `tokens` and explain the result. `None` when no resolver claims the command, which is
110/// itself the answer: the engine never saw it and the legacy classifier decided.
111pub fn explain_profile(tokens: &[Token]) -> Option<ProfileExplanation> {
112    let profile = resolve::resolve(tokens)?;
113    let capabilities = profile
114        .capabilities
115        .iter()
116        .map(|c| (c.because.clone(), c.set_facets()))
117        .collect();
118
119    // Report against the MOST PERMISSIVE level in the auto-approve band. If the top of the band
120    // refuses a capability, every level below it does too, so its complaint is the binding one —
121    // a lower level's would just be the first of several walls.
122    let blocked_by = default_levels()
123        .iter()
124        .rfind(|l| to_legacy(&l.name).is_some())
125        .and_then(|top| {
126            profile
127                .capabilities
128                .iter()
129                .find_map(|c| top.nearest_miss(c).map(|m| (top.name.clone(), m)))
130        });
131
132    Some(ProfileExplanation { capabilities, blocked_by })
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::engine::facet::*;
139
140    fn toks(parts: &[&str]) -> Vec<Token> {
141        parts.iter().map(|p| Token::from_test(p)).collect()
142    }
143
144    #[test]
145    fn project_maps_profiles_to_the_lowest_admitting_level() {
146        // echo — inert
147        let echo = Profile::of(vec![{
148            let mut c = Capability::new(Operation::Observe);
149            c.disclosure.audience = DisclosureAudience::LocalProcess;
150            c
151        }]);
152        assert_eq!(project(&echo), Verdict::Allowed(SafetyLevel::Inert));
153
154        // cat ./notes — read-local
155        let read = Profile::of(vec![{
156            let mut c = Capability::new(Operation::Observe);
157            c.locus.local = LocalLocus::Worktree;
158            c.disclosure.audience = DisclosureAudience::LocalProcess;
159            c
160        }]);
161        assert_eq!(project(&read), Verdict::Allowed(SafetyLevel::SafeRead));
162
163        // cat ~/.ssh/id_rsa — above the authored ladder → Denied
164        let home = Profile::of(vec![{
165            let mut c = Capability::new(Operation::Observe);
166            c.locus.local = LocalLocus::User;
167            c.disclosure.audience = DisclosureAudience::LocalProcess;
168            c
169        }]);
170        assert_eq!(project(&home), Verdict::Denied);
171
172        // touch build/out — create·worktree·data → write-local → SafeWrite (the
173        // to_legacy `_ => SafeWrite` arm; no resolver emits this yet)
174        let write = Profile::of(vec![{
175            let mut c = Capability::new(Operation::Create);
176            c.locus.local = LocalLocus::Worktree;
177            c.scale = Scale::Bounded;
178            c.reversibility = Reversibility::Recoverable;
179            c.persistence.level = PersistenceLevel::Data;
180            c
181        }]);
182        assert_eq!(project(&write), Verdict::Allowed(SafetyLevel::SafeWrite));
183
184        // an EMPTY profile must fail closed (Denied), NOT project to inert — every level
185        // vacuously admits it, so the guard is what stops "resolved to nothing" = "safe".
186        assert_eq!(project(&Profile::of(vec![])), Verdict::Denied);
187    }
188
189    /// The fail-open this refactor had to avoid: the levels above developer (local-admin,
190    /// network-admin, yolo) have NO legacy `SafetyLevel`, so a profile only they admit must
191    /// project to `Denied` — never to `SafeWrite`. The old `_ => SafeWrite` catch-all in
192    /// `to_legacy` would have auto-approved every one of these.
193    #[test]
194    fn profiles_needing_an_upper_level_project_to_denied_not_safewrite() {
195        // sudo systemctl restart — elevated authority on machine locus (local-admin)
196        let sudo = Profile::of(vec![{
197            let mut c = Capability::new(Operation::Control);
198            c.locus.local = LocalLocus::Machine;
199            c.authority = Authority::Root;
200            c
201        }]);
202        assert_eq!(project(&sudo), Verdict::Denied, "sudo must not auto-approve");
203
204        // terraform apply — remote reach over outbound network (network-admin)
205        let remote = Profile::of(vec![{
206            let mut c = Capability::new(Operation::Mutate);
207            c.locus.remote = RemoteReach::Fixed;
208            c.network.direction = NetDirection::Outbound;
209            c
210        }]);
211        assert_eq!(project(&remote), Verdict::Denied, "remote infra must not auto-approve");
212
213        // terraform destroy — irreversible remote destroy (yolo only)
214        let catastrophe = Profile::of(vec![{
215            let mut c = Capability::new(Operation::Destroy);
216            c.locus.remote = RemoteReach::Fixed;
217            c.reversibility = Reversibility::Irreversible;
218            c
219        }]);
220        assert_eq!(project(&catastrophe), Verdict::Denied, "irreversible destroy must not auto-approve");
221    }
222
223    /// The legacy classifier's leaf verdict for `cmd` — what the engine falls back to for a
224    /// command it can't resolve, and the baseline the never-looser gates compare against.
225    fn legacy(cmd: &str) -> Verdict {
226        crate::handlers::dispatch(&toks(&cmd.split_whitespace().collect::<Vec<_>>()))
227    }
228
229    #[test]
230    fn the_engine_is_authoritative_with_legacy_fallback() {
231        // a resolved command → the engine's (finer) verdict, end to end
232        assert_eq!(
233            crate::command_verdict("cat ./notes.md"),
234            Verdict::Allowed(SafetyLevel::SafeRead),
235            "cat resolves → engine tightens inert to read-local",
236        );
237        // an unresolvable command → the legacy classifier still decides
238        let unresolved = resolve::UNRESOLVED_CMD.join(" ");
239        assert_eq!(
240            crate::command_verdict(&unresolved),
241            legacy(&unresolved),
242            "no resolver → legacy verdict",
243        );
244    }
245
246    #[test]
247    fn engine_verdict_is_none_for_unresearched_commands() {
248        assert!(engine_verdict(&toks(resolve::UNRESOLVED_CMD)).is_none());
249        assert_eq!(engine_verdict(&toks(&["echo", "hi"])), Some(Verdict::Allowed(SafetyLevel::Inert)));
250        assert_eq!(
251            engine_verdict(&toks(&["cat", "./notes.md"])),
252            Some(Verdict::Allowed(SafetyLevel::SafeRead)),
253        );
254        assert_eq!(engine_verdict(&toks(&["cat", "~/.ssh/id_rsa"])), Some(Verdict::Denied));
255    }
256
257    /// The engine may deny what legacy allowed (intended tightening) or classify higher,
258    /// but must **never allow what legacy denied**, nor classify lower.
259    fn not_looser(legacy: Verdict, engine: Verdict) -> bool {
260        match (legacy, engine) {
261            (_, Verdict::Denied) => true,
262            (Verdict::Denied, Verdict::Allowed(_)) => false,
263            (Verdict::Allowed(l), Verdict::Allowed(e)) => e >= l,
264        }
265    }
266
267    /// The rollout safety gate on hand-picked forms — including the ones the wiring and
268    /// the review flushed (unrecognized/dangerous flags, and pattern-less grep, which
269    /// legacy denies as a usage error).
270    #[test]
271    fn the_engine_is_never_looser_than_legacy() {
272        let cases = [
273            "echo hi", "echo", "cat ./notes.md", "cat -n ./notes.md", "cat ~/.ssh/id_rsa",
274            "cat /etc/hosts", "cat a.txt b.txt", "grep foo src/main.rs", "grep -r foo src/",
275            "grep -r foo ~", "grep foo bar.txt",
276            // PCRE (-P/--perl-regexp) is benign — PCRE2 execs no code, just a regex engine
277            "grep -P foo file", "grep -oP foo file", "grep --perl-regexp foo file",
278            // unrecognized / dangerous flags must worst-case
279            "cat --unknownflag ./x", "cat -Z ./x", "grep --wat foo file",
280            // pattern-less grep (C1): legacy denies as a usage error, engine must too
281            "grep", "grep -r", "grep -i", "grep -e foo", "grep -f patterns.txt",
282        ];
283        for cmd in cases {
284            let base = legacy(cmd);
285            let t = toks(&cmd.split_whitespace().collect::<Vec<_>>());
286            let Some(engine) = engine_verdict(&t) else { continue };
287            assert!(
288                not_looser(base, engine),
289                "engine LOOSER than legacy for `{cmd}`: legacy {base}, engine {engine}",
290            );
291        }
292    }
293
294    /// The never-looser invariant above holds over the commands legacy *allowlisted*. The
295    /// `developer` level is the deliberate exception: it admits well-modeled operations the
296    /// hand-built allowlist could only DENY — e.g. deleting your own project files. This
297    /// test pins that divergence as intended, not a regression: it is exactly the kind of
298    /// finer classification the engine exists to make, now that it is authoritative.
299    #[test]
300    fn developer_intentionally_admits_worktree_destroy_that_legacy_denies() {
301        let rm = "rm -rf ./node_modules";
302        assert_eq!(legacy(rm), Verdict::Denied, "legacy allowlist denies rm deletion");
303        assert_eq!(crate::command_verdict(rm), Verdict::Allowed(SafetyLevel::SafeWrite), "engine (developer) admits it — intended");
304        assert!(!not_looser(Verdict::Denied, Verdict::Allowed(SafetyLevel::SafeWrite)), "and it IS looser than legacy, by design");
305    }
306
307    /// sed/tar keep coarse legacy HANDLERS (`coreutils::sed`/`tar`) that `handlers::dispatch`
308    /// consults before the TOML — so `legacy()` for them is that handler, which denies an in-place
309    /// edit. The behavioral engine models `sed -i` on a worktree file correctly (a SafeWrite) and is
310    /// authoritative. Pin the divergence as intended (not a regression) — the same shape as `rm`
311    /// above — because the corpus gate's sed examples deliberately avoid this looser case.
312    #[test]
313    fn engine_intentionally_admits_worktree_in_place_edit_that_legacy_sed_handler_denies() {
314        let sed = "sed -i s/a/b/ ./file.txt";
315        assert_eq!(legacy(sed), Verdict::Denied, "legacy sed handler denies in-place edit");
316        assert_eq!(crate::command_verdict(sed), Verdict::Allowed(SafetyLevel::SafeWrite), "engine admits worktree -i — intended");
317        assert!(!not_looser(Verdict::Denied, Verdict::Allowed(SafetyLevel::SafeWrite)), "and it IS looser than the legacy sed handler, by design");
318    }
319
320    /// The data-driven corpus gate (the systematic test C1 slipped past): run **every**
321    /// command's real `examples_safe`/`examples_denied` through the engine and assert,
322    /// per resolvable example, the dimensions that hold today —
323    ///   1. **never looser** than legacy (engine ≤ legacy; also subsumes "an
324    ///      examples_denied that resolves stays denied", since legacy denies it),
325    ///   2. **justified** — every resolved capability cites a `because` (§5),
326    ///   3. **total** — resolution and projection never panic.
327    ///
328    /// It grows automatically as commands convert; today it exercises the resolvable
329    /// commands and skips the rest. Only bare single commands are comparable at the leaf
330    /// (chains/redirects/substitutions are the CST's job). The full per-facet completeness
331    /// dimension is the golden-profile check (`resolve::golden_profiles_cover_every_facet`)
332    /// and becomes TOML-derived when commands carry profile data (§7).
333    #[test]
334    fn the_engine_corpus_gate() {
335        let mut exercised = 0usize;
336        for (name, safe, denied) in crate::registry::corpus_examples() {
337            for ex in safe.iter().chain(denied.iter()) {
338                if ex.contains(['|', '>', '<', '&', ';', '$', '`', '(', '\n']) {
339                    continue; // not a bare single command
340                }
341                let t = toks(&ex.split_whitespace().collect::<Vec<_>>());
342                let Some(profile) = crate::engine::resolve::resolve(&t) else { continue };
343                exercised += 1;
344
345                for c in &profile.capabilities {
346                    assert!(!c.because.is_empty(), "unjustified capability for `{ex}` ({name})");
347                }
348
349                // A PROFILED sub's legacy kind is deny-all — a fail-closed placeholder for when the
350                // engine ABSTAINS (a global flag before the sub), NOT a real hand-built verdict. So the
351                // never-looser comparison is meaningless for it: the engine is authoritative and
352                // legitimately admits below the line (`npm ci --ignore-scripts` at developer). Its
353                // landing is pinned by the archetype tests, not here.
354                if crate::registry::sub_archetypes(&t).is_some() {
355                    continue;
356                }
357                let engine = project(&profile);
358                let base = legacy(ex);
359                assert!(
360                    not_looser(base, engine),
361                    "engine LOOSER than legacy for `{ex}` ({name}): legacy {base}, engine {engine}",
362                );
363            }
364        }
365        // non-vacuity: the gate must actually resolve engine examples, or it is a green
366        // test proving nothing (the trap that hid its own emptiness). Every resolvable
367        // command must contribute at least one example.
368        assert!(exercised >= 5, "corpus gate exercised only {exercised} engine resolutions — vacuous?");
369    }
370
371    /// Per-level threshold wiring end to end: an UPPER-band `--level` classifies via `admits`,
372    /// unlocking profiles that only an upper level admits, while the lower band and the
373    /// allowlist-only fail-closed reflex are untouched.
374    #[test]
375    fn upper_band_levels_admit_via_the_engine_end_to_end() {
376        let net = crate::upper_level_by_name("network-admin").expect("network-admin exists");
377        let yolo = crate::upper_level_by_name("yolo").expect("yolo exists");
378
379        // git push origin — a network-admin op. THE payoff: denied at the default (developer)
380        // band, admitted once the threshold IS an upper level.
381        assert_eq!(crate::command_verdict("git push origin main"), Verdict::Denied, "developer denies push");
382        assert!(crate::command_verdict_at_level("git push origin main", net).is_allowed(), "network-admin admits push");
383        assert!(crate::command_verdict_at_level("git push origin main", yolo).is_allowed(), "yolo admits push");
384
385        // rm -rf / — the one thing even yolo denies (destroy·irreversible·unbounded).
386        assert_eq!(crate::command_verdict_at_level("rm -rf /", yolo), Verdict::Denied, "yolo denies rm -rf /");
387
388        // a plain read passes at every upper level (they extend reader).
389        assert!(crate::command_verdict_at_level("cat ./README.md", net).is_allowed(), "reads pass at network-admin");
390
391        // a legacy-DENIED / unmodeled command stays denied even at yolo — allowlist-only: what
392        // the engine cannot certify, no threshold can approve.
393        assert_eq!(crate::command_verdict_at_level("frobnicate --wombat", yolo), Verdict::Denied, "unmodeled denied at yolo");
394
395        // a chain is admitted only if EVERY segment is (a Denied dominates the combine).
396        assert_eq!(crate::command_verdict_at_level("git push && rm -rf /", yolo), Verdict::Denied, "one bad segment sinks the chain");
397
398        // the upper-band lookup rejects lower-band and unknown names (they keep the 3-value ceiling).
399        assert!(crate::upper_level_by_name("developer").is_none());
400        assert!(crate::upper_level_by_name("reader").is_none());
401        assert!(crate::upper_level_by_name("nonsense").is_none());
402
403        // the lower band is UNCHANGED — no eval-level context, projection still tightens cat to read.
404        assert_eq!(crate::command_verdict("cat ./README.md"), Verdict::Allowed(SafetyLevel::SafeRead), "lower band untouched");
405    }
406}