Skip to main content

safe_chains/registry/
dispatch.rs

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