Skip to main content

safe_chains/registry/
mod.rs

1mod build;
2pub(crate) mod custom;
3mod cwd_writes;
4pub mod folder_config;
5pub use custom::fuzz_load_config;
6pub(crate) use cwd_writes::cwd_writes;
7mod dispatch;
8mod docs;
9mod flag_sets;
10pub(crate) use flag_sets::{fallback_flag_sets, handler_policy_flag_sets};
11mod glob_flags;
12use glob_flags::glob_presents_unlisted_flag;
13mod passthrough_gate;
14mod policy;
15pub(crate) mod types;
16
17#[cfg(test)]
18use std::cell::RefCell;
19use std::collections::HashMap;
20use std::sync::LazyLock;
21
22use crate::parse::Token;
23use crate::verdict::Verdict;
24
25pub use build::{build_registry, load_toml};
26pub(crate) use custom::user_config_level;
27pub use dispatch::dispatch_spec;
28pub use types::{CommandSpec, OwnedPolicy};
29
30use types::DispatchKind;
31
32type HandlerFn = fn(&[Token]) -> Verdict;
33
34static CMD_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> = LazyLock::new(crate::handlers::custom_cmd_handlers);
35
36static SUB_HANDLERS: LazyLock<HashMap<&'static str, HandlerFn>> = LazyLock::new(crate::handlers::custom_sub_handlers);
37
38static TOML_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(|| include!(concat!(env!("OUT_DIR"), "/toml_includes.rs")));
39
40static CUSTOM_REGISTRY: LazyLock<HashMap<String, CommandSpec>> = LazyLock::new(|| {
41    let mut map = HashMap::new();
42    custom::apply_custom(&mut map);
43    map
44});
45
46pub fn toml_dispatch(tokens: &[Token]) -> Option<Verdict> {
47    let cmd = crate::engine::resolve::invocation_name(&tokens[0]);
48    TOML_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
49}
50
51/// Looks up the command in the runtime custom registry (project-local
52/// `.safe-chains.toml`, then user-level `~/.config/safe-chains.toml`).
53/// A match here wins over the built-in hardcoded handlers, which is how
54/// an override of `gh` takes effect.
55pub fn custom_dispatch(tokens: &[Token]) -> Option<Verdict> {
56    let cmd = crate::engine::resolve::invocation_name(&tokens[0]);
57    #[cfg(test)]
58    if let Some(verdict) = dispatch_test_command(tokens, cmd) {
59        return Some(verdict);
60    }
61    CUSTOM_REGISTRY.get(cmd).map(|spec| dispatch_spec(tokens, spec))
62}
63
64#[cfg(test)]
65thread_local! {
66    static TEST_COMMANDS: RefCell<HashMap<String, CommandSpec>> = RefCell::new(HashMap::new());
67}
68
69#[cfg(test)]
70pub(crate) fn with_test_commands<R>(source: &str, body: impl FnOnce() -> R) -> R {
71    let specs = load_toml(source, "test").unwrap_or_else(|e| panic!("test commands: {e}"));
72    TEST_COMMANDS.with(|slot| {
73        let mut map = slot.borrow_mut();
74        map.clear();
75        for spec in specs {
76            map.insert(spec.name.clone(), spec);
77        }
78    });
79    let _guard = TestCommandGuard;
80    body()
81}
82
83#[cfg(test)]
84struct TestCommandGuard;
85
86#[cfg(test)]
87impl Drop for TestCommandGuard {
88    fn drop(&mut self) {
89        TEST_COMMANDS.with(|slot| slot.borrow_mut().clear());
90    }
91}
92
93#[cfg(test)]
94fn dispatch_test_command(tokens: &[Token], cmd: &str) -> Option<Verdict> {
95    TEST_COMMANDS.with(|slot| {
96        let map = slot.borrow();
97        map.get(cmd).map(|spec| dispatch_spec(tokens, spec))
98    })
99}
100
101/// The canonical command name `cmd` resolves to via the registry's alias map (`gcat` → `cat`,
102/// `glink` → `ln`). Returns `cmd` unchanged when it is already canonical or unknown, so callers
103/// can canonicalize unconditionally. This is what lets the engine's path-gate dispatch reach an
104/// aliased invocation: without it, `gcat /etc/shadow` misses every resolver and falls through to
105/// the (ungated) legacy classifier. Custom registry first (an override may rename), then TOML.
106pub fn canonical_name(cmd: &str) -> &str {
107    CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)).map_or(cmd, |spec| spec.name.as_str())
108}
109
110/// The command's own declared path-argument gate (`[command.path_gate]`), if any — consulted by
111/// `pathgate::should_deny` when a command isn't in `pathgates.toml`, so a path-bearing flag gates
112/// from the command's own definition. `cmd` is already canonicalized by the caller.
113pub(crate) fn command_path_gate(cmd: &str) -> Option<&'static crate::pathgate::RoleSpec> {
114    CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)).and_then(|spec| spec.path_gate.as_ref())
115}
116
117/// The command's declarative facet behavior (`[command.behavior]`), if any — the engine's
118/// non-legacy classification path and the ONLY thing `engine::resolve::resolve` consults (the
119/// hardcoded `RESOLVERS` table is gone; every facet-classified command declares behavior).
120/// `cmd` is already canonicalized by the caller.
121pub(crate) fn command_behavior(cmd: &str) -> Option<&'static crate::registry::types::BehaviorSpec> {
122    CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)).and_then(|spec| spec.behavior.as_ref())
123}
124
125/// What `cmd`'s stdout can name, when that has been researched and declared (`[command.output]`).
126/// `None` — the default for every command — keeps a `$(cmd …)` unpinnable.
127pub(crate) fn command_output_locus(cmd: &str) -> Option<&'static crate::registry::types::OutputSpec> {
128    CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)).and_then(|spec| spec.output.as_ref())
129}
130
131/// What the SUBCOMMAND in `words` prints, when that sub has declared it
132/// (`[command.sub.output]`), plus the arguments left after the sub path.
133///
134/// Separate from `command_output_locus` because for a multi-command tool the claim belongs to the
135/// sub, not the program: `git diff --name-only` prints worktree paths while `git log` prints prose.
136/// Expressing that command-level would mean an `invalidated_by` naming every OTHER subcommand — a
137/// denylist, which fails open the next time git grows one.
138///
139/// Descends nested subs to the deepest declaring node, the same walk `is_eval_safe_invocation`
140/// does, so a claim can sit on `<resource> <action>`. `None` when no sub on the path declares one,
141/// which leaves the caller to fall back to the command-level claim (and then to unpinnable).
142/// `canonical` must be the CANONICALIZED command name (`registry::canonical_name` of the token's
143/// command name), the same key `command_output_locus` is given. Keying on the raw first word
144/// instead silently dropped the claim for a path-spelled or aliased command: `/usr/bin/git diff
145/// --name-only` is a trusted spelling of a trusted tool, and it lost the claim while bare `git` kept
146/// it — one operation, two spellings, two answers.
147pub(crate) fn sub_output_locus<'a>(
148    canonical: &str,
149    args: &'a [String],
150) -> Option<(&'static crate::registry::types::OutputSpec, &'a [String])> {
151    let mut rest = args;
152    let spec = CUSTOM_REGISTRY.get(canonical).or_else(|| TOML_REGISTRY.get(canonical))?;
153    let mut kind = &spec.kind;
154    let mut found: Option<(&'static crate::registry::types::OutputSpec, &'a [String])> = None;
155    loop {
156        let subs = match kind {
157            DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
158            _ => return found,
159        };
160        let Some((arg, tail)) = rest.split_first() else { return found };
161        let Some(sub) = subs.iter().find(|s| s.name == *arg) else {
162            return found;
163        };
164        rest = tail;
165        // Deepest declaration wins. A shallower one is NOT inherited by a child that declares
166        // nothing: the claim is researched per node, and letting `<parent>`'s answer stand in for
167        // an unresearched `<parent> <child>` would be asserting something nobody checked. Reset so
168        // descending past a declaring node into a silent one falls back to unpinnable.
169        found = sub.output.as_ref().map(|o| (o, rest));
170        kind = &sub.kind;
171    }
172}
173
174/// The facet archetypes (`archetypes.toml`) the subcommand `tokens` resolve to — the Phase-1
175/// `profile = …` classification plus a capability for every present escalating `[[command.sub.flag]]`
176/// (`git push` → `[vcs-sync]`; `git push --force` → `[vcs-sync, remote-destroy-irreversible]`). The
177/// engine emits a Capability per name and the level algebra takes the max. Descends `Branching`/
178/// `Custom` subs to the DEEPEST profile-bearing sub (nested `<resource> <action>`). `None` when no
179/// matched sub declares a profile.
180pub(crate) fn sub_archetypes(tokens: &[Token]) -> Option<Vec<&'static str>> {
181    let cmd = canonical_name(tokens.first()?.command_name());
182    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
183    let sub = walk_to_profiled_sub(&tokens[1..], &spec.kind)?;
184    let mut out = vec![sub.profile.as_deref()?];
185    for flag in &sub.flags {
186        if flag_escalates(tokens, flag) {
187            out.push(flag.classifies.as_str());
188        }
189    }
190    // The profile fixes the TIER; it must not also decide what is ADMISSIBLE. Without this the
191    // archetype path bypassed the flag allowlist entirely and any flag rode along on the base
192    // profile — `git rebase --exec 'rm -rf /'` classified as an ordinary rebase. `unclassified` is
193    // the sanctioned fail-closed marker: it resolves to no archetype, so the engine emits a worst
194    // capability and the invocation denies.
195    if presents_unlisted_flag(tokens, sub) {
196        out.push("unclassified");
197    }
198    Some(out)
199}
200
201/// Whether `tokens` carry a flag the profiled `sub` does not declare. Mirrors the legacy flag walk:
202/// `--long` matched whole or as `--long=value`, single-dash tokens split into clustered shorts, `--`
203/// ends the flag region. A sub that declares NO flags at all is treated as "not yet enumerated"
204/// rather than "nothing permitted", so this tightens only where a list exists — the global
205/// enforcement of the empty case is staged separately (see the backfill guard).
206fn presents_unlisted_flag(tokens: &[Token], sub: &types::SubSpec) -> bool {
207    // A flag declared as an escalating `[[command.sub.flag]]` IS declared — it just carries a
208    // capability rather than sitting on the plain allowlist. Omitting it here would deny the very
209    // invocations the escalation exists to classify (`npm ci --ignore-scripts`, whose whole point is
210    // that its PRESENCE is the safe form).
211    let known = |f: &str| {
212        sub.allowed_standalone.iter().any(|a| a == f)
213            || sub.allowed_valued.iter().any(|a| a == f)
214            || sub.flags.iter().any(|d| d.name == f)
215            // An output-path flag is declared too — it names the write destination the engine
216            // path-gates (`supabase db dump -f dump.sql`), so it is admissible by construction.
217            || sub.output_path_flags.iter().any(|a| a == f)
218            || sub.destination_flag.as_deref() == Some(f)
219    };
220    for (idx, t) in tokens.iter().enumerate().skip(1) {
221        let s = t.as_str();
222        if s == "--" {
223            break;
224        }
225        if !s.starts_with('-') || s == "-" || crate::cst::opaque::probe_is_value(tokens, idx, &sub.allowed_valued) {
226            continue;
227        }
228        let head = s.split_once('=').map_or(s, |(f, _)| f);
229        // An endpoint flag is admitted only when it names THIS machine — see the identical rule on
230        // the glob path in `glob_presents_unlisted_flag`.
231        if sub.loopback_valued.iter().any(|a| a == head) {
232            let value = match s.split_once('=') {
233                Some((_, v)) => Some(v),
234                None => tokens.get(idx + 1).map(Token::as_str),
235            };
236            if value.is_some_and(crate::netloc::is_loopback) {
237                continue;
238            }
239            return true;
240        }
241        if known(head) {
242            continue;
243        }
244        // An explicitly declared tolerance keeps the sub open for the shape it names — the
245        // established way to say "this surface is genuinely unbounded" (a cloud API's per-service
246        // options). Declared in the TOML, so it is reviewable, unlike the silent default it replaces.
247        use crate::policy::UnknownTolerance as U;
248        let tolerated = if s.starts_with("--") {
249            matches!(sub.allowed_unknown, U::Long | U::Both)
250        } else {
251            matches!(sub.allowed_unknown, U::Short | U::Both)
252        };
253        if tolerated {
254            continue;
255        }
256        // A single-dash multi-char token may be clustered shorts (`-abc` = `-a -b -c`).
257        if !s.starts_with("--") && s.len() > 2 && s[1..].chars().all(|c| known(&format!("-{c}"))) {
258            continue;
259        }
260        return true;
261    }
262    false
263}
264
265/// The facet archetypes a flat command's PRESENT top-level classifying flags (`[[command.flag]]`)
266/// resolve to — the command-level analog of `sub_archetypes` for a flag-triggered mode (`age -d` →
267/// `[decrypt-read]`, `sops --decrypt` → `[decrypt-read]`). `None` when the command declares none or
268/// none are present, so `engine::resolve` falls through to the command's ordinary resolution (the
269/// bare/encrypt form of a bimodal tool). Uses the same `flag_escalates` predicate as the sub flags.
270pub(crate) fn command_flag_archetypes(tokens: &[Token]) -> Option<Vec<&'static str>> {
271    let cmd = canonical_name(tokens.first()?.command_name());
272    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
273    let present: Vec<&'static str> = spec
274        .archetype_flags
275        .iter()
276        .filter(|f| flag_escalates(tokens, f) || (!f.when_absent && spec.archetype_flags.may_hide_a_flag(tokens)))
277        .map(|f| f.classifies.as_str())
278        .collect();
279    (!present.is_empty()).then_some(present)
280}
281
282/// Whether `flag` escalates given `tokens`. A bare flag (no `value_prefix`) escalates on presence; a
283/// value-matched flag escalates only when its VALUE starts with the prefix — the space form
284/// (`-c core.sshCommand=…`) or the glued form (`--flag=core.sshCommand=…`). Scans the whole line;
285/// an escalator counts wherever it sits.
286fn flag_escalates(tokens: &[Token], flag: &types::FlagProvenance) -> bool {
287    if flag.when_absent {
288        // A SAFETY flag whose ABSENCE is the escalation (`npm ci` without `--ignore-scripts`).
289        // It must be AFFIRMATIVELY set — `--ignore-scripts=false` / `--no-ignore-scripts` re-ENABLE
290        // scripts, so they escalate exactly like the flag being missing (a fail-open otherwise).
291        return !flag_is_affirmatively_set(tokens, &flag.name);
292    }
293    let Some(prefix) = flag.value_prefix.as_deref() else {
294        return flag_present(tokens, &flag.name);
295    };
296    // space form: `NAME VALUE`, VALUE starting with the prefix
297    tokens.windows(2).any(|w| w[0].as_str() == flag.name && w[1].as_str().starts_with(prefix))
298        // glued form: `NAME=VALUE`, VALUE starting with the prefix
299        || tokens.iter().any(|t| {
300            t.as_str()
301                .strip_prefix(flag.name.as_str())
302                .and_then(|r| r.strip_prefix('='))
303                .is_some_and(|v| v.starts_with(prefix))
304        })
305}
306
307/// Whether a boolean flag is AFFIRMATIVELY enabled: bare `--flag`, or `--flag=<truthy>`. A
308/// `--flag=false/0/no/off` or a `--no-flag` DISABLES it (returns false), as does absence. Last
309/// occurrence wins, the CLI convention. Used by the `when_absent` escalator so a re-enabling spelling
310/// can't masquerade as the safety flag being set.
311fn flag_is_affirmatively_set(tokens: &[Token], flag: &str) -> bool {
312    let neg = format!("--no-{}", flag.trim_start_matches('-'));
313    let mut set = false;
314    for t in tokens {
315        let s = t.as_str();
316        if s == flag {
317            set = true;
318        } else if let Some(v) = s.strip_prefix(flag).and_then(|r| r.strip_prefix('=')) {
319            set = !matches!(v.to_ascii_lowercase().as_str(), "false" | "0" | "no" | "off" | "");
320        } else if s == neg {
321            set = false;
322        }
323    }
324    set
325}
326
327fn walk_to_profiled_sub(remaining: &[Token], kind: &'static DispatchKind) -> Option<&'static types::SubSpec> {
328    let subs = match kind {
329        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
330        _ => return None,
331    };
332    let arg = remaining.first()?;
333    let sub = subs.iter().find(|s| s.name == arg.as_str())?;
334    // Deepest profiled match wins: a nested action's profile overrides its resource sub's.
335    walk_to_profiled_sub(&remaining[1..], &sub.kind).or_else(|| sub.profile.is_some().then_some(sub))
336}
337
338/// Like `walk_to_profiled_sub`, but also returns the tokens AFTER the matched sub's name — the
339/// operands the engine still needs to inspect (the destination positional, for `network_destination`).
340fn walk_to_profiled_sub_rest<'a>(remaining: &'a [Token], kind: &'static DispatchKind) -> Option<(&'static types::SubSpec, &'a [Token])> {
341    let subs = match kind {
342        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
343        _ => return None,
344    };
345    let arg = remaining.first()?;
346    let sub = subs.iter().find(|s| s.name == arg.as_str())?;
347    let rest = &remaining[1..];
348    walk_to_profiled_sub_rest(rest, &sub.kind).or_else(|| sub.profile.is_some().then_some((sub, rest)))
349}
350
351/// For a profiled sub declaring `network_destination`, the first positional after it — the send
352/// TARGET (`git push origin` → `origin`; bare `git push` → `None`, the configured default). `None`
353/// (outer) when the resolved sub does not classify a destination. The engine maps the token's
354/// PROVENANCE onto `locus.provenance` (`resolve::destination_provenance`).
355///
356/// "First non-`-` token" is a heuristic: a VALUED flag's value sitting before the target
357/// (`git push -o $VAR origin`) is read as the destination. That only ever misreads CONSERVATIVELY —
358/// a stray value classifies to `literal`/`opaque` (equal-or-stricter than the real `established`
359/// target), never looser — so it can over-deny a rare form but never under-approve.
360pub(crate) fn sub_destination_token(tokens: &[Token]) -> Option<Option<&str>> {
361    let cmd = canonical_name(tokens.first()?.command_name());
362    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
363    let (sub, rest) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind)?;
364    if !sub.network_destination {
365        return None;
366    }
367    // A destination-carrying flag (`git push --repo=<dest>`) OVERRIDES the positional — else a
368    // `--repo=ext::sh` RCE would slip past a benign positional (`origin`). Scanned across the whole
369    // line since the flag may sit anywhere.
370    if let Some(flag) = sub.destination_flag.as_deref()
371        && let Some(v) = flag_value(tokens, flag)
372    {
373        return Some(Some(v));
374    }
375    Some(rest.iter().map(Token::as_str).find(|t| !t.starts_with('-')))
376}
377
378/// A flag's value, but only from the FLAG REGION — tokens after a `--` terminator are positionals,
379/// not flags.
380///
381/// Used where finding a value makes the classification MORE PERMISSIVE, which is where a
382/// disagreement with the tool costs something. `presents_unlisted_flag` already stops at `--`, so
383/// without this the two layers disagreed: `put-item ... -- --endpoint-url http://localhost:8000`
384/// passed admission (the walk never saw the flag) AND localized (the value lookup did), classifying
385/// a call to the real service as a write to this machine.
386///
387/// The restrictive lookups deliberately do NOT use this. For `output_path_flags`, finding a path
388/// ADDS a path-gated write capability, so scanning past `--` errs toward more gating; switching
389/// them here would relax them. Each direction fails closed, which is why the asymmetry stands.
390fn flag_value_in_flag_region<'a>(tokens: &'a [Token], flag: &str) -> Option<&'a str> {
391    let end = tokens.iter().position(|t| t.as_str() == "--").unwrap_or(tokens.len());
392    flag_value(&tokens[..end], flag)
393}
394
395/// A flag's value, glued (`--repo=VALUE`) or space-separated (`--repo VALUE`); `None` if absent.
396/// Scans the WHOLE token list — see `flag_value_in_flag_region` for the `--`-aware variant and why
397/// only the permissive callers use it.
398fn flag_value<'a>(tokens: &'a [Token], flag: &str) -> Option<&'a str> {
399    if let Some(v) = tokens.iter().find_map(|t| t.as_str().strip_prefix(flag).and_then(|r| r.strip_prefix('='))) {
400        return Some(v);
401    }
402    tokens.windows(2).find(|w| w[0].as_str() == flag).map(|w| w[1].as_str())
403}
404
405/// For a profiled `data-export` sub declaring `output_path_flags`, the output-file PATH one of them
406/// carries — or `None` when the export streams to stdout (no output flag present). The engine adds a
407/// path-gated write capability at this path's locus, so a dump to `/etc/cron.d/job` gates on locus
408/// exactly as a redirect there would. `None` (outer) when the resolved sub declares none.
409///
410/// Values are matched in every spelling the flag admits: `--file=X`, `--file X`, `-f X`, `-f=X`, and
411/// the glued short form `-fX` — the last mustn't be a bypass (`-f/etc/cron.d/job` reaching a system
412/// path would otherwise drop the write cap and auto-approve). A bare `-f` with no value is a
413/// malformed invocation the tool itself rejects, so a `None` there is harmless.
414/// Whether this invocation's declared endpoint flag names THIS machine, so `resolve` should clear
415/// the facets the destination determines. `false` covers "no endpoint flag", "points elsewhere",
416/// and "the sub never opted in".
417///
418/// Returning `false` for a non-loopback value is what keeps this independent of the admission
419/// check: even if `presents_unlisted_flag` were bypassed, the remote facets would still be the ones
420/// that classify.
421pub(crate) fn sub_loopback_localizes(tokens: &[Token]) -> bool {
422    let Some(cmd) = tokens.first().map(|t| canonical_name(t.command_name())) else {
423        return false;
424    };
425    let Some(spec) = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)) else {
426        return false;
427    };
428    let Some((sub, _rest)) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind) else {
429        return false;
430    };
431    sub.loopback_effect == types::LoopbackEffect::Localizes
432        && sub
433            .loopback_valued
434            .iter()
435            .filter_map(|f| flag_value_in_flag_region(tokens, f))
436            .any(crate::netloc::is_loopback)
437}
438
439pub(crate) fn sub_output_path_token(tokens: &[Token]) -> Option<&str> {
440    let cmd = canonical_name(tokens.first()?.command_name());
441    let spec = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd))?;
442    let (sub, _rest) = walk_to_profiled_sub_rest(&tokens[1..], &spec.kind)?;
443    sub.output_path_flags.iter().find_map(|f| output_flag_value(tokens, f))
444}
445
446/// `flag_value`, plus the glued short form `-fVALUE` (a two-char `-x` flag with the value fused on).
447/// Kept separate from `flag_value` because a glued short is only unambiguous for the single-letter
448/// output flags this classifies (`-f`, `-r`); the destination-flag path (`--repo`) never needs it.
449fn output_flag_value<'a>(tokens: &'a [Token], flag: &'a str) -> Option<&'a str> {
450    if let Some(v) = flag_value(tokens, flag) {
451        return Some(v);
452    }
453    if flag.len() == 2 && flag.starts_with('-') && !flag.starts_with("--") {
454        return tokens.iter().find_map(|t| t.as_str().strip_prefix(flag).filter(|r| !r.is_empty()));
455    }
456    None
457}
458
459/// Whether `flag` appears anywhere in `tokens` — bare (`--force`), glued (`--flag=v`), or, for a SHORT
460/// single-char flag (`-d`), hidden inside a short CLUSTER (`-da`, `-vd`) for tools that combine short
461/// options. A flag is an escalator wherever it sits, so this scans the whole line. The flag ALLOWLIST
462/// cluster-expands, so this must too — otherwise a cluster admits the command while the classifier
463/// misses the dangerous flag inside it (a classifier/allowlist disagreement; a live bypass for any
464/// clustering tool with a classifying short flag).
465fn flag_present(tokens: &[Token], flag: &str) -> bool {
466    // A `-X` short flag (exactly two chars, leading `-`) can appear in a cluster; `--long` cannot.
467    let short_char = (flag.len() == 2 && flag.as_bytes()[0] == b'-').then(|| flag.as_bytes()[1]);
468    tokens.iter().any(|t| {
469        let s = t.as_str();
470        if s == flag || s.strip_prefix(flag).is_some_and(|rest| rest.starts_with('=')) {
471            return true;
472        }
473        // Short cluster `-<letters>` (single dash, not `--`): scan only the boolean-letter run BEFORE
474        // any `=value`, so a glued value (`-o=decrypted`) can't spuriously match the flag char.
475        matches!(short_char, Some(c)
476            if s.len() > 1 && s.as_bytes()[0] == b'-' && s.as_bytes()[1] != b'-'
477            && s[1..].split('=').next().is_some_and(|run| run.as_bytes().contains(&c)))
478    })
479}
480
481pub fn toml_command_names() -> Vec<&'static str> {
482    TOML_REGISTRY.keys().map(|k| k.as_str()).collect()
483}
484
485/// EVERY declared stdout claim in the registry, command-level and sub-level alike, each paired with
486/// the invocation scope that carries it (`"fd"`, `"git diff"`).
487///
488/// The structural guards over `[command.output]` enumerate this rather than `toml_command_names`,
489/// so a sub-scoped claim is held to the same bar as a command-scoped one. Enumerating only commands
490/// would have let every `[command.sub.output]` ship unprobed — the claim is transitive (it widens
491/// whatever consumes the substitution), so an unguarded one is the worst kind to add.
492#[cfg(test)]
493pub(crate) fn output_claims() -> Vec<(String, &'static crate::registry::types::OutputSpec)> {
494    fn walk(prefix: &str, kind: &'static DispatchKind, out: &mut Vec<(String, &'static crate::registry::types::OutputSpec)>) {
495        let subs = match kind {
496            DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => subs,
497            _ => return,
498        };
499        for sub in subs {
500            let scope = format!("{prefix} {}", sub.name);
501            if let Some(o) = sub.output.as_ref() {
502                out.push((scope.clone(), o));
503            }
504            walk(&scope, &sub.kind, out);
505        }
506    }
507
508    let mut out = Vec::new();
509    for (name, spec) in TOML_REGISTRY.iter() {
510        if let Some(o) = spec.output.as_ref() {
511            out.push((name.clone(), o));
512        }
513        walk(name, &spec.kind, &mut out);
514    }
515    out
516}
517
518/// Every command's canonical name with its declared `examples_safe` / `examples_denied`
519/// — the corpus the engine's never-looser corpus gate runs against.
520#[cfg(test)]
521pub(crate) fn corpus_examples() -> Vec<(&'static str, &'static [String], &'static [String])> {
522    TOML_REGISTRY
523        .iter()
524        .map(|(name, spec)| (name.as_str(), spec.examples_safe.as_slice(), spec.examples_denied.as_slice()))
525        .collect()
526}
527
528/// Look up `cmd_name`'s TOML-declared subs (set via `[[command.sub]]`
529/// blocks alongside `handler = "..."`) and dispatch the one whose name
530/// matches `tokens[1]`. Returns `None` if no sub matched, so the
531/// handler can fall through to its fallback grammar (or deny).
532pub fn try_sub_dispatch(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
533    let spec = handler_spec(cmd_name)?;
534    let DispatchKind::Custom { subs, .. } = &spec.kind else {
535        return None;
536    };
537    let arg = tokens.get(1)?.as_str();
538    let sub = subs.iter().find(|s| s.name == arg)?;
539    Some(dispatch::dispatch_sub_kind(&tokens[1..], &sub.kind))
540}
541
542/// Apply `cmd_name`'s TOML-declared `[command.fallback]` grammar.
543/// Returns `None` if no fallback is declared.
544pub fn try_fallback_grammar(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
545    let spec = handler_spec(cmd_name)?;
546    let DispatchKind::Custom { fallback, .. } = &spec.kind else {
547        return None;
548    };
549    let f = fallback.as_ref()?;
550    Some(dispatch::dispatch_fallback(tokens, f))
551}
552
553/// Dispatch `tokens` against `cmd_name`'s `[[command.matrix]]`
554/// blocks. Looks at `tokens[1]` (parent) and `tokens[2]` (action),
555/// finds the first matrix whose `parents` contains the parent and
556/// whose `actions` map contains the action, then validates
557/// `tokens[2..]` against the named policy (and a guard flag if the
558/// matrix entry declared one). Returns `None` if no matrix matched —
559/// the handler can then fall through to its remaining special cases
560/// or deny.
561pub fn try_matrix_dispatch(cmd_name: &str, tokens: &[Token]) -> Option<Verdict> {
562    let spec = handler_spec(cmd_name)?;
563    let DispatchKind::Custom { matrices, handler_policies, .. } = &spec.kind else {
564        return None;
565    };
566    let parent = tokens.get(1)?.as_str();
567    let action = tokens.get(2)?.as_str();
568    for matrix in matrices {
569        if !matrix.parents.iter().any(|p| p == parent) {
570            continue;
571        }
572        let Some(action_spec) = matrix.actions.get(action) else {
573            continue;
574        };
575        if let Some(long) = action_spec.guard.as_deref()
576            && !crate::parse::has_flag(&tokens[2..], action_spec.guard_short.as_deref(), Some(long))
577        {
578            return Some(Verdict::Denied);
579        }
580        let Some(policy) = handler_policies.get(&action_spec.policy_key) else {
581            return Some(Verdict::Denied);
582        };
583        return Some(dispatch::dispatch_matrix_action(&tokens[2..], policy, matrix.level));
584    }
585    None
586}
587
588/// Validate `tokens` against `cmd_name`'s named flag policy declared
589/// in a `[command.handler_policy.KEY]` block. Returns `false` if no
590/// such policy is declared or the tokens fail it. Used by handlers
591/// whose dispatch logic genuinely can't move to TOML (e.g. gh's
592/// sub × action matrix) but whose per-policy WordSets should live
593/// in TOML rather than as Rust `WordSet` constants.
594pub fn check_handler_policy(cmd_name: &str, key: &str, tokens: &[Token]) -> bool {
595    let Some(spec) = handler_spec(cmd_name) else {
596        return false;
597    };
598    let DispatchKind::Custom { handler_policies, .. } = &spec.kind else {
599        return false;
600    };
601    let Some(policy) = handler_policies.get(key) else {
602        return false;
603    };
604    dispatch::check_handler_policy_owned(tokens, policy)
605}
606
607fn handler_spec(cmd_name: &str) -> Option<&'static CommandSpec> {
608    CUSTOM_REGISTRY.get(cmd_name).or_else(|| TOML_REGISTRY.get(cmd_name))
609}
610
611/// Returns true iff this invocation is tagged eval-safe — meaning its
612/// stdout is documented shell-init code that can safely be substituted
613/// inside `eval "$(...)"`.
614///
615/// The walker descends through `DispatchKind::Branching` AND
616/// `DispatchKind::Custom` matching subs token-by-token (handler-based
617/// commands such as `gh` can have tagged TOML-declared subs even though
618/// the handler does the actual dispatch). The leaf is the deepest matched
619/// node (where no further sub matches). `eval_safe` is checked only at
620/// the leaf — ancestor tags do NOT propagate. After confirming the leaf
621/// is tagged, every `-`-prefixed token in the remaining tail must appear
622/// in `eval_safe_flags`; positionals are unrestricted.
623///
624/// Tagged nodes are vetted manually per-command (see SAMPLE.toml). This
625/// function does not validate that `tokens` is syntactically allowed —
626/// callers must have already passed it through the regular dispatcher.
627pub fn is_eval_safe_invocation(tokens: &[Token]) -> bool {
628    if tokens.is_empty() {
629        return false;
630    }
631    let cmd = crate::engine::resolve::invocation_name(&tokens[0]);
632    let Some(spec) = CUSTOM_REGISTRY.get(cmd).or_else(|| TOML_REGISTRY.get(cmd)) else {
633        return false;
634    };
635    is_eval_safe_for_spec(spec, tokens)
636}
637
638/// Spec-local variant used by tests so they can build a `CommandSpec`
639/// via `load_toml` and exercise the walker without touching the global
640/// `TOML_REGISTRY`.
641pub(crate) fn is_eval_safe_for_spec(spec: &CommandSpec, tokens: &[Token]) -> bool {
642    if tokens.is_empty() {
643        return false;
644    }
645    walk_to_eval_safe_leaf(
646        &tokens[1..],
647        &spec.kind,
648        spec.eval_safe,
649        &spec.eval_safe_flags,
650        &spec.eval_safe_flag_values,
651        &spec.eval_safe_required_flags,
652    )
653}
654
655fn walk_to_eval_safe_leaf(
656    remaining: &[Token],
657    kind: &DispatchKind,
658    eval_safe: bool,
659    eval_safe_flags: &[String],
660    eval_safe_flag_values: &std::collections::HashMap<String, Vec<String>>,
661    eval_safe_required_flags: &[String],
662) -> bool {
663    let subs_opt = match kind {
664        DispatchKind::Branching { subs, .. } | DispatchKind::Custom { subs, .. } => Some(subs),
665        _ => None,
666    };
667    if let Some(subs) = subs_opt
668        && let Some(arg) = remaining.first()
669        && let Some(sub) = subs.iter().find(|s| s.name == arg.as_str())
670    {
671        return walk_to_eval_safe_leaf(
672            &remaining[1..],
673            &sub.kind,
674            sub.eval_safe,
675            &sub.eval_safe_flags,
676            &sub.eval_safe_flag_values,
677            &sub.eval_safe_required_flags,
678        );
679    }
680    if !eval_safe {
681        return false;
682    }
683    let mut i = 0;
684    let mut seen_required = false;
685    while i < remaining.len() {
686        let s = remaining[i].as_str();
687        if !s.starts_with('-') {
688            i += 1;
689            continue;
690        }
691        let (bare, eq_value) = match s.split_once('=') {
692            Some((k, v)) => (k, Some(v)),
693            None => (s, None),
694        };
695        if !eval_safe_flags.iter().any(|f| f == bare) {
696            return false;
697        }
698        if eval_safe_required_flags.iter().any(|f| f == bare) {
699            seen_required = true;
700        }
701        if let Some(allowed) = eval_safe_flag_values.get(bare) {
702            // Valued flag declared in eval_safe_flag_values. The value
703            // arrives either as `--flag=VALUE` (eq_value is Some) or as
704            // the next token (`--flag VALUE`); either way the walker
705            // consumes it because a flag in eval_safe_flag_values is
706            // structurally valued.
707            //
708            // `allowed` empty = explicit-unrestricted: contributor
709            // vetted that any bare-literal value preserves shell-init
710            // output. Non-empty = value must appear in the allowlist.
711            let value: &str = if let Some(v) = eq_value {
712                v
713            } else if let Some(next) = remaining.get(i + 1) {
714                let v = next.as_str();
715                i += 1;
716                v
717            } else {
718                return false;
719            };
720            // Empty value is denied even under the explicit-
721            // unrestricted (`= []`) posture: `--flag=` and an empty
722            // following token never represent a meaningful tool
723            // argument. The bare-literal alphabet check is per-char
724            // and vacuously passes empty strings, so the walker
725            // has to reject explicitly.
726            if value.is_empty() {
727                return false;
728            }
729            if !allowed.is_empty() && !allowed.iter().any(|av| av == value) {
730                return false;
731            }
732        }
733        i += 1;
734    }
735    if !eval_safe_required_flags.is_empty() && !seen_required {
736        return false;
737    }
738    true
739}
740
741pub fn toml_command_docs() -> Vec<crate::docs::CommandDoc> {
742    TOML_REGISTRY
743        .iter()
744        .filter(|(key, spec)| *key == &spec.name)
745        .map(|(_, spec)| spec.to_command_doc())
746        .collect()
747}
748
749#[cfg(test)]
750mod arity_tests;
751#[cfg(test)]
752mod gate_consistency;
753#[cfg(test)]
754mod overlap_tests;
755#[cfg(test)]
756mod tests;