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