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