Skip to main content

safe_chains/registry/
dispatch.rs

1use crate::parse::Token;
2use crate::verdict::{SafetyLevel, Verdict};
3mod credential_args;
4pub(super) mod delegate;
5mod pre_flags;
6use super::policy::{check_owned, flag_given};
7use super::types::*;
8use super::{CMD_HANDLERS, SUB_HANDLERS};
9use pre_flags::skip_pre_flags;
10
11type HandlerMap = std::collections::HashMap<&'static str, super::HandlerFn>;
12
13/// The `per_database` sub that `arg` is a variant of: `arg` is `<sub.name>:<dbname>`.
14///
15/// The suffix must be ONE plain identifier — the shape of a key in `config/database.yml`. That is
16/// what keeps this from degenerating into "ignore anything after a colon": a further `:` names
17/// another task, and a suffix with a `/`, a space or a substitution is no database name at all.
18fn per_database_variant<'a>(subs: &'a [SubSpec], arg: &str) -> Option<&'a SubSpec> {
19    let (base, dbname) = arg.rsplit_once(':')?;
20    let plain = !dbname.is_empty() && dbname.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
21    // The character test alone is not enough, and failing to say so was a fail-open in the first
22    // cut of this: a substitution reaches dispatch already rewritten to `__SAFE_CHAINS_CMDSUB__`,
23    // which is alphanumeric-and-underscore and sailed straight through as a "plain identifier".
24    // `db:migrate:$(anything)` was admitted as a per-database variant.
25    if !plain || crate::cst::check::is_opaque_value(dbname) {
26        return None;
27    }
28    subs.iter().find(|s| s.name_match == NameMatch::WithDatabaseSuffix && s.name == base)
29}
30
31fn dispatch_first_arg(
32    tokens: &[Token],
33    patterns: &[String],
34    level: SafetyLevel,
35    standalone: &[String],
36    valued: &[String],
37    loopback_valued: &[String],
38) -> Verdict {
39    if tokens.len() == 2 && (tokens[1] == "--help" || tokens[1] == "-h") {
40        return Verdict::Allowed(SafetyLevel::Inert);
41    }
42    let Some(arg) = tokens.get(1) else {
43        return Verdict::Denied;
44    };
45    let arg_str = arg.as_str();
46    let matches = patterns
47        .iter()
48        .any(|p| if let Some(prefix) = p.strip_suffix('*') { arg_str.starts_with(prefix) } else { arg_str == p });
49    if !matches {
50        return Verdict::Denied;
51    }
52    if super::glob_flags::glob_presents_unlisted_flag(tokens, 2, standalone, valued, loopback_valued) {
53        return Verdict::Denied;
54    }
55    Verdict::Allowed(level)
56}
57
58fn dispatch_require_any(
59    tokens: &[Token],
60    require_any: &[String],
61    policy: &OwnedPolicy,
62    level: SafetyLevel,
63    accept_bare_help: bool,
64) -> Verdict {
65    if tokens.len() == 2 {
66        let t = tokens[1].as_str();
67        if t == "--help" || t == "-h" || (accept_bare_help && t == "help") {
68            return Verdict::Allowed(SafetyLevel::Inert);
69        }
70    }
71    if flag_given(tokens, policy, require_any) && check_owned(tokens, policy) { Verdict::Allowed(level) } else { Verdict::Denied }
72}
73
74/// The first-positional GLOB arm of a `Branching`: which verbs it admits, at what level, the flags
75/// it accepts once admitted, and the verbs that instead mark the invocation a credential-read.
76struct GlobArm<'a> {
77    patterns: &'a [String],
78    level: SafetyLevel,
79    standalone: &'a [String],
80    valued: &'a [String],
81    loopback_valued: &'a [String],
82    credential: &'a [String],
83}
84
85fn dispatch_branching(
86    tokens: &[Token],
87    subs: &[SubSpec],
88    bare_flags: &[String],
89    bare_ok: bool,
90    pre_flags: (&[String], &[String]),
91    toolchain_selector: bool,
92    glob: &GlobArm<'_>,
93) -> Verdict {
94    let (pre_standalone, pre_valued) = pre_flags;
95    let start = skip_pre_flags(tokens, pre_standalone, pre_valued, toolchain_selector, 1);
96    if start >= tokens.len() {
97        return if bare_ok { Verdict::Allowed(SafetyLevel::Inert) } else { Verdict::Denied };
98    }
99    let arg = tokens[start].as_str();
100    let is_bare_flag = bare_flags.iter().any(|f| f == arg) || (bare_flags.is_empty() && matches!(arg, "--help" | "-h"));
101    if is_bare_flag {
102        let after = skip_pre_flags(tokens, pre_standalone, pre_valued, toolchain_selector, start + 1);
103        if after >= tokens.len() {
104            return Verdict::Allowed(SafetyLevel::Inert);
105        }
106        if bare_flags.is_empty() {
107            return Verdict::Denied;
108        }
109    }
110    if let Some(sub) = subs.iter().find(|s| s.name == arg) {
111        return dispatch_sub(&tokens[start..], sub);
112    }
113    // A per-database variant: `db:migrate:primary` is `db:migrate` aimed at one of the databases
114    // it would otherwise migrate all of. Only subs that OPT IN (`per_database`) match this way,
115    // and only for a single trailing plain identifier — see `TomlSub::per_database` for why the
116    // set cannot be enumerated and why inheriting the base's classification cannot widen it.
117    if let Some(sub) = per_database_variant(subs, arg) {
118        return dispatch_sub(&tokens[start..], sub);
119    }
120    let glob_match = |p: &str| !arg.starts_with('-') && p.strip_suffix('*').map_or(arg == p, |prefix| arg.starts_with(prefix));
121    // An argument naming secret material (`kubectl get secret`/`secret/x`, `aws configure get
122    // aws_secret_access_key`) is a CREDENTIAL-READ — deny before the allow-glob admits it. The
123    // value-dependent complement to `profile=credential-read`.
124    if credential_args::names_a_credential(&tokens[start..], glob.credential, &[pre_valued, glob.valued]) {
125        return Verdict::Denied;
126    }
127    if !glob.patterns.is_empty() && glob.patterns.iter().any(|p| glob_match(p)) {
128        if super::glob_flags::glob_presents_unlisted_flag(tokens, start + 1, glob.standalone, glob.valued, glob.loopback_valued) {
129            return Verdict::Denied;
130        }
131        return Verdict::Allowed(glob.level);
132    }
133    Verdict::Denied
134}
135
136fn dispatch_wrapper(
137    tokens: &[Token],
138    standalone: &[String],
139    valued: &[String],
140    positional_skip: usize,
141    separator: Option<&str>,
142    bare_ok: bool,
143) -> Verdict {
144    let mut i = 1;
145    while i < tokens.len() {
146        let t = &tokens[i];
147        if let Some(sep) = separator
148            && t == sep
149        {
150            i += 1;
151            break;
152        }
153        if !t.starts_with('-') {
154            break;
155        }
156        if valued.iter().any(|f| t == f.as_str()) {
157            i += 2;
158            continue;
159        }
160        if valued.iter().any(|f| t.as_str().starts_with(&format!("{f}="))) {
161            i += 1;
162            continue;
163        }
164        if standalone.iter().any(|f| t == f.as_str()) {
165            i += 1;
166            continue;
167        }
168        return Verdict::Denied;
169    }
170    for _ in 0..positional_skip {
171        if i >= tokens.len() {
172            return if bare_ok { Verdict::Allowed(SafetyLevel::Inert) } else { Verdict::Denied };
173        }
174        i += 1;
175    }
176    if i >= tokens.len() {
177        return if bare_ok { Verdict::Allowed(SafetyLevel::Inert) } else { Verdict::Denied };
178    }
179    let inner = shell_words::join(tokens[i..].iter().map(|t| t.as_str()));
180    crate::command_verdict(&inner)
181}
182
183fn dispatch_kind(tokens: &[Token], kind: &DispatchKind, handlers: &HandlerMap) -> Verdict {
184    match kind {
185        DispatchKind::Policy { policy, level, shape } => {
186            if misshapen(*shape, tokens, policy) {
187                Verdict::Denied
188            } else {
189                super::policy::check_with_passthrough(tokens, policy, *level)
190            }
191        }
192        DispatchKind::FirstArg { patterns, level, standalone, valued, loopback_valued } => {
193            dispatch_first_arg(tokens, patterns, *level, standalone, valued, loopback_valued)
194        }
195        DispatchKind::RequireAny { require_any, policy, level, accept_bare_help } => {
196            dispatch_require_any(tokens, require_any, policy, *level, *accept_bare_help)
197        }
198        DispatchKind::Branching {
199            subs,
200            bare_flags,
201            bare_ok,
202            pre_standalone,
203            pre_valued,
204            first_arg,
205            first_arg_level,
206            first_arg_standalone,
207            first_arg_valued,
208            first_arg_loopback_valued,
209            credential_first_arg,
210            toolchain_selector,
211        } => dispatch_branching(
212            tokens,
213            subs,
214            bare_flags,
215            *bare_ok,
216            (pre_standalone, pre_valued),
217            *toolchain_selector,
218            &GlobArm {
219                patterns: first_arg,
220                level: *first_arg_level,
221                standalone: first_arg_standalone,
222                valued: first_arg_valued,
223                loopback_valued: first_arg_loopback_valued,
224                credential: credential_first_arg,
225            },
226        ),
227        DispatchKind::WriteFlagged { policy, base_level, write_flags } => {
228            if !check_owned(tokens, policy) {
229                return Verdict::Denied;
230            }
231            write_flagged(tokens, *base_level, write_flags)
232        }
233        DispatchKind::DelegateAfterSeparator(delegate) => delegate.verdict(tokens),
234        DispatchKind::DelegateSkip { skip, shape } => {
235            if tokens.len() <= *skip {
236                return Verdict::Denied;
237            }
238            if let Some(shape) = shape
239                && !tokens[1..*skip].iter().all(|t| shape.matches(t.as_str()))
240            {
241                return Verdict::Denied;
242            }
243            let inner = shell_words::join(tokens[*skip..].iter().map(|t| t.as_str()));
244            crate::command_verdict(&inner)
245        }
246        DispatchKind::Wrapper { standalone, valued, positional_skip, separator, bare_ok } => {
247            dispatch_wrapper(tokens, standalone, valued, *positional_skip, separator.as_deref(), *bare_ok)
248        }
249        DispatchKind::VerbChain(spec) => dispatch_verb_chain(tokens, spec),
250        DispatchKind::Executor { policy, level, kind, redirect_flag, shape, passes_argv } => {
251            dispatch_executor(tokens, policy, *kind, *level, redirect_flag.as_deref(), *shape, *passes_argv)
252        }
253        DispatchKind::Custom { handler_name, .. } => handlers.get(handler_name.as_str()).map(|f| f(tokens)).unwrap_or(Verdict::Denied),
254    }
255}
256
257pub fn dispatch_spec(tokens: &[Token], spec: &CommandSpec) -> Verdict {
258    if spec.hooks.refuses(tokens) {
259        return Verdict::Denied;
260    }
261    spec.line_checks
262        .judge(tokens, || spec.hooks.classify_exports(tokens, dispatch_kind(tokens, &spec.kind, &CMD_HANDLERS)))
263}
264
265/// A sub, dispatched for `registry::try_sub_dispatch` (a handler consulting its TOML subs) and for a branching command.
266pub(super) fn dispatch_sub(tokens: &[Token], sub: &SubSpec) -> Verdict {
267    super::operands::gated_sub(tokens, sub, || dispatch_kind(tokens, &sub.kind, &SUB_HANDLERS))
268}
269
270pub(super) fn check_handler_policy_owned(tokens: &[Token], policy: &OwnedPolicy) -> bool {
271    check_owned(tokens, policy)
272}
273
274pub(super) fn dispatch_matrix_action(tokens: &[Token], policy: &OwnedPolicy, level: SafetyLevel) -> Verdict {
275    if check_owned(tokens, policy) { Verdict::Allowed(level) } else { Verdict::Denied }
276}
277
278/// A `verb-chain` grammar (`mlr`): `CMD [main-flags…] verb [args…] then verb …`. The main-flag
279/// region is a STRICT allowlist (standalone / valued / variadic) — an unlisted flag denies, so a
280/// mutating flag like mlr's `-I`/`--in-place` (omitted) is caught by omission. The region ends at
281/// `--` or the first non-flag token, which opens the verb chain: every `then`-segment's first token
282/// (the verb NAME) must be on the `verbs` allowlist; verb ARGS are open-ended (a pure verb has no
283/// shell/file escape). See `types::VerbChainSpec`.
284pub(super) fn dispatch_verb_chain(tokens: &[Token], spec: &VerbChainSpec) -> Verdict {
285    if tokens.len() == 1 {
286        return Verdict::Denied;
287    }
288    let has = |set: &[String], s: &str| set.iter().any(|f| f == s);
289    let mut i = 1;
290    while i < tokens.len() {
291        let s = tokens[i].as_str();
292        // `--` terminates the main region; the verb chain follows it.
293        if s == "--" {
294            return verb_chain_tail(&tokens[i + 1..], spec);
295        }
296        // The first non-flag token opens the verb chain.
297        if !tokens[i].starts_with('-') {
298            return verb_chain_tail(&tokens[i..], spec);
299        }
300        if has(&spec.main_standalone, s) {
301            i += 1;
302        } else if has(&spec.main_variadic, s) {
303            // Consume input files up to the `--` terminator (or end); the `--` is left for the
304            // loop to treat as the main/verb separator next iteration.
305            i += 1;
306            while i < tokens.len() && tokens[i].as_str() != "--" {
307                i += 1;
308            }
309        } else if has(&spec.main_valued, s) {
310            i += if crate::policy::consumes_next_value(tokens.get(i + 1)) { 2 } else { 1 };
311        } else if s.split_once('=').is_some_and(|(f, _)| has(&spec.main_valued, f)) {
312            i += 1;
313        } else {
314            return Verdict::Denied;
315        }
316    }
317    // Only allowlisted main flags, no verb (`mlr --version`, `mlr --csv`): nothing runs.
318    Verdict::Allowed(spec.level)
319}
320
321/// The verb region: a `then`-chain where every segment's first token must be an allowlisted verb.
322fn verb_chain_tail(region: &[Token], spec: &VerbChainSpec) -> Verdict {
323    let mut expect_verb = true;
324    for t in region {
325        if t.as_str() == spec.separator {
326            expect_verb = true;
327            continue;
328        }
329        if expect_verb {
330            if !spec.verbs.contains(t.as_str()) {
331                return Verdict::Denied;
332            }
333            expect_verb = false;
334        }
335    }
336    // An empty region or a dangling separator leaves `expect_verb` set — no valid verb ran.
337    if expect_verb { Verdict::Denied } else { Verdict::Allowed(spec.level) }
338}
339
340/// Gate a code-execution command through the execution-origin engine (worktree code allows,
341/// foreign denies) instead of a flat level. Shared by executor SUBS (`go run`, `cargo run`)
342/// and executor FALLBACKS (interpreters). See docs/design/behavioral-taxonomy-execution-origin.md.
343///
344/// - `File`: the first positional is the executor path — `bash x.sh`, `go run ./cmd`. Tokens
345///   AFTER it are the script's own arguments (data, not validated). With no positional, it's a
346///   flag-only invocation (`python3 --version`) validated by `policy` (denies a bare REPL).
347/// - `Project`: the current project is the executor — `cargo run`. A `redirect_flag` value
348///   (`--manifest-path DIR/Cargo.toml`) moves the executor OUT of the project and is locus-gated
349///   like a file executor; without it, the project (worktree) is the executor.
350pub(super) fn dispatch_executor(
351    tokens: &[Token],
352    policy: &OwnedPolicy,
353    kind: ExecutorKind,
354    level: SafetyLevel,
355    redirect_flag: Option<&str>,
356    shape: Option<crate::policy::PositionalShape>,
357    passes_argv: bool,
358) -> Verdict {
359    match kind {
360        ExecutorKind::File => match super::policy::first_positional_at(tokens, policy).and_then(|(at, first)| {
361            // How much of the invocation the command's own grammar governs.
362            //
363            // This used to check NOTHING once a first positional resolved, so `max_positional`
364            // went unenforced and a command that OPENS its extra positionals was handed them:
365            // `karma start ./ok.conf.js /etc/evil.conf.js` was admitted, the second path being
366            // a second config karma loads and runs. `karma` and `tilt` each grew a `path_gate`
367            // to compensate, which worked but left the next such command to inherit the hole.
368            //
369            // Checking only the PREFIX up to the executor — TODO's first suggestion — does not
370            // fix it, which was measured rather than reasoned: the prefix contains exactly one
371            // positional by construction, so `max_positional = 1` always passes and the second
372            // config is still never counted. That approach is a no-op for the case it targets.
373            //
374            // So the command DECLARES whether trailing tokens are its own. An interpreter
375            // passes them to the script (`python3 ./task.py --flag arg`) and its grammar
376            // genuinely cannot describe them, so only the prefix is checked. Everything else is
377            // governed in full, which is the enforcing default a new entry gets for free.
378            let governed = if passes_argv { &tokens[..=at] } else { tokens };
379            check_owned(governed, policy).then_some(first)
380        }) {
381            // `-` is STDIN, not a file. Every interpreter reads its program from stdin when given
382            // it, so the code being run is not in the workspace and is not in the command string
383            // either — the classifier cannot see it at all. It was resolving as a bare relative
384            // path, which classifies worktree-local, so `curl … | python3 -` auto-approved: remote
385            // code execution straight through the allowlist. `/dev/stdin` and `/dev/fd/0` already
386            // denied as absolute foreign paths; only the short spelling slipped.
387            Some("-") => Verdict::Denied,
388            // A declared shape the executor path must satisfy (`go run` → `go-package`):
389            // a remote import path is not a worktree executor, so it denies here.
390            Some(first) if shape.is_some_and(|s| !s.matches(first)) => Verdict::Denied,
391            // Only the locus, NOT `check_owned`. For an interpreter every token after the script
392            // is the SCRIPT's argv (`python3 ./task.py --flag arg`), so the command's own flag
393            // grammar cannot describe it. The cost is that `max_positional` goes unenforced here
394            // — see TODO.md; a command that needs its positionals gated declares a `path_gate`
395            // with the `exec` role instead of relying on this.
396            Some(first) => crate::engine::resolve::execute_file_verdict(first),
397            None if check_owned(tokens, policy) => Verdict::Allowed(level),
398            None => Verdict::Denied,
399        },
400        ExecutorKind::Project => {
401            if !check_owned(tokens, policy) {
402                return Verdict::Denied;
403            }
404            match redirect_flag.and_then(|f| flag_value(tokens, f)) {
405                Some(redirected) => crate::engine::resolve::execute_file_verdict(redirected),
406                None => crate::engine::resolve::execute_project_verdict(),
407            }
408        }
409    }
410}
411
412/// The value of valued flag `flag` in `tokens` — the space form (`--manifest-path P`) or the
413/// glued `=` form (`--manifest-path=P`). Scans only up to a `--` terminator, so a program
414/// argument after `--` can't be mistaken for the flag's value. `None` if the flag is absent.
415fn flag_value<'a>(tokens: &'a [Token], flag: &str) -> Option<&'a str> {
416    let mut i = 1;
417    while i < tokens.len() {
418        let t = tokens[i].as_str();
419        if t == "--" {
420            return None;
421        }
422        if t == flag {
423            return tokens.get(i + 1).map(Token::as_str);
424        }
425        if let Some(rest) = t.strip_prefix(flag).and_then(|r| r.strip_prefix('=')) {
426            return Some(rest);
427        }
428        i += 1;
429    }
430    None
431}
432
433/// Applies a TOML-declared fallback grammar, for `registry::try_fallback_grammar()`.
434pub(super) fn dispatch_fallback(tokens: &[Token], spec: &FallbackSpec) -> Verdict {
435    if let Some(kind) = spec.executor {
436        return dispatch_executor(
437            tokens,
438            &spec.policy,
439            kind,
440            spec.level,
441            spec.executor_redirect_flag.as_deref(),
442            spec.positional_shape,
443            spec.passes_argv,
444        );
445    }
446    if let Some(shape) = spec.positional_shape
447        && let Some(first) = super::policy::first_positional(tokens, &spec.policy)
448        && !shape.matches(first)
449    {
450        return Verdict::Denied;
451    }
452    if !check_owned(tokens, &spec.policy) {
453        return Verdict::Denied;
454    }
455    write_flagged(tokens, spec.level, &spec.write_flags)
456}
457
458/// `base`, or `SafeWrite` when any of `write_flags` is present (bare or `--flag=value`).
459fn write_flagged(tokens: &[Token], base: SafetyLevel, write_flags: &[String]) -> Verdict {
460    let flagged = |t: &Token| write_flags.iter().any(|f| t == f.as_str() || t.as_str().starts_with(&format!("{f}=")));
461    Verdict::Allowed(if tokens[1..].iter().any(flagged) { SafetyLevel::SafeWrite } else { base })
462}
463
464#[cfg(test)]
465mod toolchain_selector_tests {
466    use crate::is_safe_command;
467
468    /// The selector is OPT-IN, and must stay that way. Stripping a leading `+token` for every
469    /// structured command would silently swallow a first positional on tools that have no such
470    /// convention — `+nightly` is a rustup spelling, not a shell one.
471    ///
472    /// Enumerated over commands that dispatch subs but do NOT declare it: the bare sub allows, and
473    /// the same sub behind a `+toolchain` must NOT, because for these tools that token is an
474    /// unknown operand rather than a selector.
475    #[test]
476    fn a_toolchain_selector_is_not_stripped_unless_declared() {
477        for (bare, with_selector) in [
478            ("git log", "git +nightly log"),
479            ("jj log", "jj +nightly log"),
480            ("docker compose logs", "docker +nightly compose logs"),
481            ("go version", "go +nightly version"),
482        ] {
483            assert!(is_safe_command(bare), "precondition: `{bare}` should allow");
484            assert!(
485                !is_safe_command(with_selector),
486                "`{with_selector}`: a toolchain selector was stripped for a command that does not \
487                 declare `toolchain_selector`, so a leading operand is being silently discarded"
488            );
489        }
490    }
491
492    /// ...and IS stripped where declared, for every spelling a toolchain name takes.
493    #[test]
494    fn a_declared_toolchain_selector_is_accepted() {
495        for line in [
496            "cargo +nightly build", "cargo +stable test", "cargo +1.90.0 check", "cargo +nightly-2026-01-01 build",
497            "cargo +nightly-x86_64-apple-darwin build",
498        ] {
499            assert!(is_safe_command(line), "`{line}` should classify as its bare subcommand does");
500        }
501    }
502
503    /// The selector does not launder the SUBCOMMAND: what `cargo publish` is stays what
504    /// `cargo +nightly publish` is. This is the fail-open the strip would cause if it were applied
505    /// before, rather than instead of, the sub's own classification.
506    #[test]
507    fn a_toolchain_selector_does_not_change_its_subcommand() {
508        for sub in ["publish", "install ripgrep", "login"] {
509            let bare = format!("cargo {sub}");
510            let selected = format!("cargo +nightly {sub}");
511            assert_eq!(
512                is_safe_command(&bare),
513                is_safe_command(&selected),
514                "`{selected}` disagrees with `{bare}` — the selector changed the verdict",
515            );
516        }
517    }
518}