safe-chains 0.243.5

Auto-allow safe bash commands in agentic coding tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use crate::parse::Token;
use crate::verdict::{SafetyLevel, Verdict};
mod credential_args;
pub(super) mod delegate;
mod pre_flags;
use super::policy::{check_owned, flag_given};
use super::types::*;
use super::{CMD_HANDLERS, SUB_HANDLERS};
use pre_flags::skip_pre_flags;

type HandlerMap = std::collections::HashMap<&'static str, super::HandlerFn>;

/// The `per_database` sub that `arg` is a variant of: `arg` is `<sub.name>:<dbname>`.
///
/// The suffix must be ONE plain identifier — the shape of a key in `config/database.yml`. That is
/// what keeps this from degenerating into "ignore anything after a colon": a further `:` names
/// another task, and a suffix with a `/`, a space or a substitution is no database name at all.
fn per_database_variant<'a>(subs: &'a [SubSpec], arg: &str) -> Option<&'a SubSpec> {
    let (base, dbname) = arg.rsplit_once(':')?;
    let plain = !dbname.is_empty() && dbname.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
    // The character test alone is not enough, and failing to say so was a fail-open in the first
    // cut of this: a substitution reaches dispatch already rewritten to `__SAFE_CHAINS_CMDSUB__`,
    // which is alphanumeric-and-underscore and sailed straight through as a "plain identifier".
    // `db:migrate:$(anything)` was admitted as a per-database variant.
    if !plain || crate::cst::check::is_opaque_value(dbname) {
        return None;
    }
    subs.iter().find(|s| s.name_match == NameMatch::WithDatabaseSuffix && s.name == base)
}

fn dispatch_first_arg(
    tokens: &[Token],
    patterns: &[String],
    level: SafetyLevel,
    standalone: &[String],
    valued: &[String],
    loopback_valued: &[String],
) -> Verdict {
    if tokens.len() == 2 && (tokens[1] == "--help" || tokens[1] == "-h") {
        return Verdict::Allowed(SafetyLevel::Inert);
    }
    let Some(arg) = tokens.get(1) else {
        return Verdict::Denied;
    };
    let arg_str = arg.as_str();
    let matches = patterns
        .iter()
        .any(|p| if let Some(prefix) = p.strip_suffix('*') { arg_str.starts_with(prefix) } else { arg_str == p });
    if !matches {
        return Verdict::Denied;
    }
    if super::glob_flags::glob_presents_unlisted_flag(tokens, 2, standalone, valued, loopback_valued) {
        return Verdict::Denied;
    }
    Verdict::Allowed(level)
}

fn dispatch_require_any(
    tokens: &[Token],
    require_any: &[String],
    policy: &OwnedPolicy,
    level: SafetyLevel,
    accept_bare_help: bool,
) -> Verdict {
    if tokens.len() == 2 {
        let t = tokens[1].as_str();
        if t == "--help" || t == "-h" || (accept_bare_help && t == "help") {
            return Verdict::Allowed(SafetyLevel::Inert);
        }
    }
    if flag_given(tokens, policy, require_any) && check_owned(tokens, policy) { Verdict::Allowed(level) } else { Verdict::Denied }
}

/// The first-positional GLOB arm of a `Branching`: which verbs it admits, at what level, the flags
/// it accepts once admitted, and the verbs that instead mark the invocation a credential-read.
struct GlobArm<'a> {
    patterns: &'a [String],
    level: SafetyLevel,
    standalone: &'a [String],
    valued: &'a [String],
    loopback_valued: &'a [String],
    credential: &'a [String],
}

fn dispatch_branching(
    tokens: &[Token],
    subs: &[SubSpec],
    bare_flags: &[String],
    bare_ok: bool,
    pre_flags: (&[String], &[String]),
    toolchain_selector: bool,
    glob: &GlobArm<'_>,
) -> Verdict {
    let (pre_standalone, pre_valued) = pre_flags;
    let start = skip_pre_flags(tokens, pre_standalone, pre_valued, toolchain_selector, 1);
    if start >= tokens.len() {
        return if bare_ok { Verdict::Allowed(SafetyLevel::Inert) } else { Verdict::Denied };
    }
    let arg = tokens[start].as_str();
    let is_bare_flag = bare_flags.iter().any(|f| f == arg) || (bare_flags.is_empty() && matches!(arg, "--help" | "-h"));
    if is_bare_flag {
        let after = skip_pre_flags(tokens, pre_standalone, pre_valued, toolchain_selector, start + 1);
        if after >= tokens.len() {
            return Verdict::Allowed(SafetyLevel::Inert);
        }
        if bare_flags.is_empty() {
            return Verdict::Denied;
        }
    }
    if let Some(sub) = subs.iter().find(|s| s.name == arg) {
        return dispatch_sub(&tokens[start..], sub);
    }
    // A per-database variant: `db:migrate:primary` is `db:migrate` aimed at one of the databases
    // it would otherwise migrate all of. Only subs that OPT IN (`per_database`) match this way,
    // and only for a single trailing plain identifier — see `TomlSub::per_database` for why the
    // set cannot be enumerated and why inheriting the base's classification cannot widen it.
    if let Some(sub) = per_database_variant(subs, arg) {
        return dispatch_sub(&tokens[start..], sub);
    }
    let glob_match = |p: &str| !arg.starts_with('-') && p.strip_suffix('*').map_or(arg == p, |prefix| arg.starts_with(prefix));
    // An argument naming secret material (`kubectl get secret`/`secret/x`, `aws configure get
    // aws_secret_access_key`) is a CREDENTIAL-READ — deny before the allow-glob admits it. The
    // value-dependent complement to `profile=credential-read`.
    if credential_args::names_a_credential(&tokens[start..], glob.credential, &[pre_valued, glob.valued]) {
        return Verdict::Denied;
    }
    if !glob.patterns.is_empty() && glob.patterns.iter().any(|p| glob_match(p)) {
        if super::glob_flags::glob_presents_unlisted_flag(tokens, start + 1, glob.standalone, glob.valued, glob.loopback_valued) {
            return Verdict::Denied;
        }
        return Verdict::Allowed(glob.level);
    }
    Verdict::Denied
}

fn dispatch_wrapper(
    tokens: &[Token],
    standalone: &[String],
    valued: &[String],
    positional_skip: usize,
    separator: Option<&str>,
    bare_ok: bool,
) -> Verdict {
    let mut i = 1;
    while i < tokens.len() {
        let t = &tokens[i];
        if let Some(sep) = separator
            && t == sep
        {
            i += 1;
            break;
        }
        if !t.starts_with('-') {
            break;
        }
        if valued.iter().any(|f| t == f.as_str()) {
            i += 2;
            continue;
        }
        if valued.iter().any(|f| t.as_str().starts_with(&format!("{f}="))) {
            i += 1;
            continue;
        }
        if standalone.iter().any(|f| t == f.as_str()) {
            i += 1;
            continue;
        }
        return Verdict::Denied;
    }
    for _ in 0..positional_skip {
        if i >= tokens.len() {
            return if bare_ok { Verdict::Allowed(SafetyLevel::Inert) } else { Verdict::Denied };
        }
        i += 1;
    }
    if i >= tokens.len() {
        return if bare_ok { Verdict::Allowed(SafetyLevel::Inert) } else { Verdict::Denied };
    }
    let inner = shell_words::join(tokens[i..].iter().map(|t| t.as_str()));
    crate::command_verdict(&inner)
}

fn dispatch_kind(tokens: &[Token], kind: &DispatchKind, handlers: &HandlerMap) -> Verdict {
    match kind {
        DispatchKind::Policy { policy, level, shape } => {
            if misshapen(*shape, tokens, policy) {
                Verdict::Denied
            } else {
                super::policy::check_with_passthrough(tokens, policy, *level)
            }
        }
        DispatchKind::FirstArg { patterns, level, standalone, valued, loopback_valued } => {
            dispatch_first_arg(tokens, patterns, *level, standalone, valued, loopback_valued)
        }
        DispatchKind::RequireAny { require_any, policy, level, accept_bare_help } => {
            dispatch_require_any(tokens, require_any, policy, *level, *accept_bare_help)
        }
        DispatchKind::Branching {
            subs,
            bare_flags,
            bare_ok,
            pre_standalone,
            pre_valued,
            first_arg,
            first_arg_level,
            first_arg_standalone,
            first_arg_valued,
            first_arg_loopback_valued,
            credential_first_arg,
            toolchain_selector,
        } => dispatch_branching(
            tokens,
            subs,
            bare_flags,
            *bare_ok,
            (pre_standalone, pre_valued),
            *toolchain_selector,
            &GlobArm {
                patterns: first_arg,
                level: *first_arg_level,
                standalone: first_arg_standalone,
                valued: first_arg_valued,
                loopback_valued: first_arg_loopback_valued,
                credential: credential_first_arg,
            },
        ),
        DispatchKind::WriteFlagged { policy, base_level, write_flags } => {
            if !check_owned(tokens, policy) {
                return Verdict::Denied;
            }
            write_flagged(tokens, *base_level, write_flags)
        }
        DispatchKind::DelegateAfterSeparator(delegate) => delegate.verdict(tokens),
        DispatchKind::DelegateSkip { skip, shape } => {
            if tokens.len() <= *skip {
                return Verdict::Denied;
            }
            if let Some(shape) = shape
                && !tokens[1..*skip].iter().all(|t| shape.matches(t.as_str()))
            {
                return Verdict::Denied;
            }
            let inner = shell_words::join(tokens[*skip..].iter().map(|t| t.as_str()));
            crate::command_verdict(&inner)
        }
        DispatchKind::Wrapper { standalone, valued, positional_skip, separator, bare_ok } => {
            dispatch_wrapper(tokens, standalone, valued, *positional_skip, separator.as_deref(), *bare_ok)
        }
        DispatchKind::VerbChain(spec) => dispatch_verb_chain(tokens, spec),
        DispatchKind::Executor { policy, level, kind, redirect_flag, shape, passes_argv } => {
            dispatch_executor(tokens, policy, *kind, *level, redirect_flag.as_deref(), *shape, *passes_argv)
        }
        DispatchKind::Custom { handler_name, .. } => handlers.get(handler_name.as_str()).map(|f| f(tokens)).unwrap_or(Verdict::Denied),
    }
}

pub fn dispatch_spec(tokens: &[Token], spec: &CommandSpec) -> Verdict {
    if spec.hooks.refuses(tokens) {
        return Verdict::Denied;
    }
    spec.line_checks
        .judge(tokens, || spec.hooks.classify_exports(tokens, dispatch_kind(tokens, &spec.kind, &CMD_HANDLERS)))
}

/// A sub, dispatched for `registry::try_sub_dispatch` (a handler consulting its TOML subs) and for a branching command.
pub(super) fn dispatch_sub(tokens: &[Token], sub: &SubSpec) -> Verdict {
    super::operands::gated_sub(tokens, sub, || dispatch_kind(tokens, &sub.kind, &SUB_HANDLERS))
}

pub(super) fn check_handler_policy_owned(tokens: &[Token], policy: &OwnedPolicy) -> bool {
    check_owned(tokens, policy)
}

pub(super) fn dispatch_matrix_action(tokens: &[Token], policy: &OwnedPolicy, level: SafetyLevel) -> Verdict {
    if check_owned(tokens, policy) { Verdict::Allowed(level) } else { Verdict::Denied }
}

/// A `verb-chain` grammar (`mlr`): `CMD [main-flags…] verb [args…] then verb …`. The main-flag
/// region is a STRICT allowlist (standalone / valued / variadic) — an unlisted flag denies, so a
/// mutating flag like mlr's `-I`/`--in-place` (omitted) is caught by omission. The region ends at
/// `--` or the first non-flag token, which opens the verb chain: every `then`-segment's first token
/// (the verb NAME) must be on the `verbs` allowlist; verb ARGS are open-ended (a pure verb has no
/// shell/file escape). See `types::VerbChainSpec`.
pub(super) fn dispatch_verb_chain(tokens: &[Token], spec: &VerbChainSpec) -> Verdict {
    if tokens.len() == 1 {
        return Verdict::Denied;
    }
    let has = |set: &[String], s: &str| set.iter().any(|f| f == s);
    let mut i = 1;
    while i < tokens.len() {
        let s = tokens[i].as_str();
        // `--` terminates the main region; the verb chain follows it.
        if s == "--" {
            return verb_chain_tail(&tokens[i + 1..], spec);
        }
        // The first non-flag token opens the verb chain.
        if !tokens[i].starts_with('-') {
            return verb_chain_tail(&tokens[i..], spec);
        }
        if has(&spec.main_standalone, s) {
            i += 1;
        } else if has(&spec.main_variadic, s) {
            // Consume input files up to the `--` terminator (or end); the `--` is left for the
            // loop to treat as the main/verb separator next iteration.
            i += 1;
            while i < tokens.len() && tokens[i].as_str() != "--" {
                i += 1;
            }
        } else if has(&spec.main_valued, s) {
            i += if crate::policy::consumes_next_value(tokens.get(i + 1)) { 2 } else { 1 };
        } else if s.split_once('=').is_some_and(|(f, _)| has(&spec.main_valued, f)) {
            i += 1;
        } else {
            return Verdict::Denied;
        }
    }
    // Only allowlisted main flags, no verb (`mlr --version`, `mlr --csv`): nothing runs.
    Verdict::Allowed(spec.level)
}

/// The verb region: a `then`-chain where every segment's first token must be an allowlisted verb.
fn verb_chain_tail(region: &[Token], spec: &VerbChainSpec) -> Verdict {
    let mut expect_verb = true;
    for t in region {
        if t.as_str() == spec.separator {
            expect_verb = true;
            continue;
        }
        if expect_verb {
            if !spec.verbs.contains(t.as_str()) {
                return Verdict::Denied;
            }
            expect_verb = false;
        }
    }
    // An empty region or a dangling separator leaves `expect_verb` set — no valid verb ran.
    if expect_verb { Verdict::Denied } else { Verdict::Allowed(spec.level) }
}

/// Gate a code-execution command through the execution-origin engine (worktree code allows,
/// foreign denies) instead of a flat level. Shared by executor SUBS (`go run`, `cargo run`)
/// and executor FALLBACKS (interpreters). See docs/design/behavioral-taxonomy-execution-origin.md.
///
/// - `File`: the first positional is the executor path — `bash x.sh`, `go run ./cmd`. Tokens
///   AFTER it are the script's own arguments (data, not validated). With no positional, it's a
///   flag-only invocation (`python3 --version`) validated by `policy` (denies a bare REPL).
/// - `Project`: the current project is the executor — `cargo run`. A `redirect_flag` value
///   (`--manifest-path DIR/Cargo.toml`) moves the executor OUT of the project and is locus-gated
///   like a file executor; without it, the project (worktree) is the executor.
pub(super) fn dispatch_executor(
    tokens: &[Token],
    policy: &OwnedPolicy,
    kind: ExecutorKind,
    level: SafetyLevel,
    redirect_flag: Option<&str>,
    shape: Option<crate::policy::PositionalShape>,
    passes_argv: bool,
) -> Verdict {
    match kind {
        ExecutorKind::File => match super::policy::first_positional_at(tokens, policy).and_then(|(at, first)| {
            // How much of the invocation the command's own grammar governs.
            //
            // This used to check NOTHING once a first positional resolved, so `max_positional`
            // went unenforced and a command that OPENS its extra positionals was handed them:
            // `karma start ./ok.conf.js /etc/evil.conf.js` was admitted, the second path being
            // a second config karma loads and runs. `karma` and `tilt` each grew a `path_gate`
            // to compensate, which worked but left the next such command to inherit the hole.
            //
            // Checking only the PREFIX up to the executor — TODO's first suggestion — does not
            // fix it, which was measured rather than reasoned: the prefix contains exactly one
            // positional by construction, so `max_positional = 1` always passes and the second
            // config is still never counted. That approach is a no-op for the case it targets.
            //
            // So the command DECLARES whether trailing tokens are its own. An interpreter
            // passes them to the script (`python3 ./task.py --flag arg`) and its grammar
            // genuinely cannot describe them, so only the prefix is checked. Everything else is
            // governed in full, which is the enforcing default a new entry gets for free.
            let governed = if passes_argv { &tokens[..=at] } else { tokens };
            check_owned(governed, policy).then_some(first)
        }) {
            // `-` is STDIN, not a file. Every interpreter reads its program from stdin when given
            // it, so the code being run is not in the workspace and is not in the command string
            // either — the classifier cannot see it at all. It was resolving as a bare relative
            // path, which classifies worktree-local, so `curl … | python3 -` auto-approved: remote
            // code execution straight through the allowlist. `/dev/stdin` and `/dev/fd/0` already
            // denied as absolute foreign paths; only the short spelling slipped.
            Some("-") => Verdict::Denied,
            // A declared shape the executor path must satisfy (`go run` → `go-package`):
            // a remote import path is not a worktree executor, so it denies here.
            Some(first) if shape.is_some_and(|s| !s.matches(first)) => Verdict::Denied,
            // Only the locus, NOT `check_owned`. For an interpreter every token after the script
            // is the SCRIPT's argv (`python3 ./task.py --flag arg`), so the command's own flag
            // grammar cannot describe it. The cost is that `max_positional` goes unenforced here
            // — see TODO.md; a command that needs its positionals gated declares a `path_gate`
            // with the `exec` role instead of relying on this.
            Some(first) => crate::engine::resolve::execute_file_verdict(first),
            None if check_owned(tokens, policy) => Verdict::Allowed(level),
            None => Verdict::Denied,
        },
        ExecutorKind::Project => {
            if !check_owned(tokens, policy) {
                return Verdict::Denied;
            }
            match redirect_flag.and_then(|f| flag_value(tokens, f)) {
                Some(redirected) => crate::engine::resolve::execute_file_verdict(redirected),
                None => crate::engine::resolve::execute_project_verdict(),
            }
        }
    }
}

/// The value of valued flag `flag` in `tokens` — the space form (`--manifest-path P`) or the
/// glued `=` form (`--manifest-path=P`). Scans only up to a `--` terminator, so a program
/// argument after `--` can't be mistaken for the flag's value. `None` if the flag is absent.
fn flag_value<'a>(tokens: &'a [Token], flag: &str) -> Option<&'a str> {
    let mut i = 1;
    while i < tokens.len() {
        let t = tokens[i].as_str();
        if t == "--" {
            return None;
        }
        if t == flag {
            return tokens.get(i + 1).map(Token::as_str);
        }
        if let Some(rest) = t.strip_prefix(flag).and_then(|r| r.strip_prefix('=')) {
            return Some(rest);
        }
        i += 1;
    }
    None
}

/// Applies a TOML-declared fallback grammar, for `registry::try_fallback_grammar()`.
pub(super) fn dispatch_fallback(tokens: &[Token], spec: &FallbackSpec) -> Verdict {
    if let Some(kind) = spec.executor {
        return dispatch_executor(
            tokens,
            &spec.policy,
            kind,
            spec.level,
            spec.executor_redirect_flag.as_deref(),
            spec.positional_shape,
            spec.passes_argv,
        );
    }
    if let Some(shape) = spec.positional_shape
        && let Some(first) = super::policy::first_positional(tokens, &spec.policy)
        && !shape.matches(first)
    {
        return Verdict::Denied;
    }
    if !check_owned(tokens, &spec.policy) {
        return Verdict::Denied;
    }
    write_flagged(tokens, spec.level, &spec.write_flags)
}

/// `base`, or `SafeWrite` when any of `write_flags` is present (bare or `--flag=value`).
fn write_flagged(tokens: &[Token], base: SafetyLevel, write_flags: &[String]) -> Verdict {
    let flagged = |t: &Token| write_flags.iter().any(|f| t == f.as_str() || t.as_str().starts_with(&format!("{f}=")));
    Verdict::Allowed(if tokens[1..].iter().any(flagged) { SafetyLevel::SafeWrite } else { base })
}

#[cfg(test)]
mod toolchain_selector_tests {
    use crate::is_safe_command;

    /// The selector is OPT-IN, and must stay that way. Stripping a leading `+token` for every
    /// structured command would silently swallow a first positional on tools that have no such
    /// convention — `+nightly` is a rustup spelling, not a shell one.
    ///
    /// Enumerated over commands that dispatch subs but do NOT declare it: the bare sub allows, and
    /// the same sub behind a `+toolchain` must NOT, because for these tools that token is an
    /// unknown operand rather than a selector.
    #[test]
    fn a_toolchain_selector_is_not_stripped_unless_declared() {
        for (bare, with_selector) in [
            ("git log", "git +nightly log"),
            ("jj log", "jj +nightly log"),
            ("docker compose logs", "docker +nightly compose logs"),
            ("go version", "go +nightly version"),
        ] {
            assert!(is_safe_command(bare), "precondition: `{bare}` should allow");
            assert!(
                !is_safe_command(with_selector),
                "`{with_selector}`: a toolchain selector was stripped for a command that does not \
                 declare `toolchain_selector`, so a leading operand is being silently discarded"
            );
        }
    }

    /// ...and IS stripped where declared, for every spelling a toolchain name takes.
    #[test]
    fn a_declared_toolchain_selector_is_accepted() {
        for line in [
            "cargo +nightly build", "cargo +stable test", "cargo +1.90.0 check", "cargo +nightly-2026-01-01 build",
            "cargo +nightly-x86_64-apple-darwin build",
        ] {
            assert!(is_safe_command(line), "`{line}` should classify as its bare subcommand does");
        }
    }

    /// The selector does not launder the SUBCOMMAND: what `cargo publish` is stays what
    /// `cargo +nightly publish` is. This is the fail-open the strip would cause if it were applied
    /// before, rather than instead of, the sub's own classification.
    #[test]
    fn a_toolchain_selector_does_not_change_its_subcommand() {
        for sub in ["publish", "install ripgrep", "login"] {
            let bare = format!("cargo {sub}");
            let selected = format!("cargo +nightly {sub}");
            assert_eq!(
                is_safe_command(&bare),
                is_safe_command(&selected),
                "`{selected}` disagrees with `{bare}` — the selector changed the verdict",
            );
        }
    }
}