Skip to main content

safe_chains/
policy.rs

1use crate::parse::{Token, WordSet};
2
3/// Whether unrecognized flag-shaped tokens are denied or silently accepted
4/// as positional arguments. The default (Strict) makes the allowlist
5/// authoritative — any unrecognized `-X` or `--foo` is denied.
6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
7pub enum UnknownTolerance {
8    /// Deny every unrecognized flag-shaped token. The safe default.
9    #[default]
10    Strict,
11    /// Accept unknown single-dash tokens (`-X`, `-help`, `-mayDie`) as
12    /// positional. Reject unknown double-dash. Use for tools like
13    /// `pdftotext` that have single-dash long flags.
14    Short,
15    /// Accept unknown double-dash tokens (`--foo`, `--foo=value`) as
16    /// positional. Reject unknown single-dash. Dangerous: most modern
17    /// destructive flags are double-dash, so enabling this can silently
18    /// accept mutating options. Reserved for tools with genuinely
19    /// unbounded long-flag surfaces (AWS CLI service flags).
20    Long,
21    /// Accept both single-dash and double-dash unknowns as positional.
22    /// Most permissive; combines the cost of `Short` and `Long`.
23    Both,
24}
25
26impl UnknownTolerance {
27    pub const fn allows_short(self) -> bool {
28        matches!(self, Self::Short | Self::Both)
29    }
30    pub const fn allows_long(self) -> bool {
31        matches!(self, Self::Long | Self::Both)
32    }
33}
34
35/// How the dispatcher treats tokens that look like flags but aren't in the
36/// allowlist. `unknown` controls flag-shaped unknowns; `numeric_dash` opts
37/// into `-NUMBER` shorthand (e.g. `head -20`); `single_dash_words` stops a single-dash token
38/// being read as a cluster of short flags, for tools whose options are whole words (`exiftool -if`
39/// is one option that runs Perl, never `-i -f`). `reads_commands.plus` is for a pager or editor that
40/// runs a `+word` operand as its first command (`less +!id`, `vim '+!id'`): only a line number
41/// (`+42`) or a bare `+` passes. `reads_commands.stdin` is for one that reads keystrokes from a
42/// standard input that is not a terminal (`printf ':!id\n' | vim`): fed anything, it is refused.
43#[derive(Clone, Copy, Debug, Default)]
44pub struct FlagTolerance {
45    pub unknown: UnknownTolerance,
46    pub numeric_dash: bool,
47    pub single_dash_words: bool,
48    pub reads_commands: CommandSources,
49}
50
51/// Where a pager or editor takes commands from besides its options: a `+word` operand, and a
52/// standard input that is not a terminal.
53#[derive(Clone, Copy, Debug, Default)]
54pub struct CommandSources {
55    pub plus: bool,
56    pub stdin: bool,
57}
58
59impl FlagTolerance {
60    /// Strict allowlist: deny every unrecognized flag-shaped token.
61    /// `const`-callable for use in static `FlagPolicy` literals.
62    pub const fn strict() -> Self {
63        Self {
64            unknown: UnknownTolerance::Strict,
65            numeric_dash: false,
66            single_dash_words: false,
67            reads_commands: CommandSources { plus: false, stdin: false },
68        }
69    }
70}
71
72/// Predicate over the first positional token of a fallback grammar.
73/// Lets a TOML-declared fallback say "the first positional must look
74/// like a path" without the handler hardcoding the test.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum PositionalShape {
77    /// Looks like a file path: contains `/`, contains `.`, or is `-`
78    /// (the conventional stdin marker). Rejects flag-shaped tokens.
79    Path,
80    /// A go LOCAL package/file argument: `.`/`..`, a `./`-, `../`-, or
81    /// `/`-anchored path, or a `*.go` file. This is exactly Go's rule for
82    /// "this is a filesystem path, not an import path" — a BARE import path
83    /// (`rsc.io/x@latest`, `example.com/cmd`, `bin/tool`) is resolved via the
84    /// module system and, with `@version`, DOWNLOADS AND RUNS remote code, so
85    /// it must not be treated as a worktree-local executor.
86    GoPackage,
87    /// A rustup toolchain NAME (`stable`, `nightly-2026-10-01`, `1.97.1`), never a path: rustup
88    /// reads a toolchain argument with a path separator as a toolchain directory and runs its
89    /// binaries. The shape `cargo +name` admits.
90    ToolchainName,
91    /// A local folder that cannot be read as a remote address. kustomize clones any target it can
92    /// parse as a git repository (`github.com/org/repo`, `https://…`, `git@host:…`, `gh:org/repo`,
93    /// `host/org/repo.git`) before it looks for a local folder, so a target with a scheme, a
94    /// colon, an `@`, a query, a `//` subpath, a `.git` component, or a host-like first component
95    /// is not a local path.
96    LocalPath,
97}
98
99impl PositionalShape {
100    pub fn matches(self, token: &str) -> bool {
101        match self {
102            Self::Path => looks_like_path(token),
103            Self::GoPackage => is_go_local_package(token),
104            Self::ToolchainName => crate::envvars::is_toolchain_name(token),
105            Self::LocalPath => is_local_path(token),
106        }
107    }
108
109    pub fn from_name(name: &str) -> Option<Self> {
110        match name {
111            "path" => Some(Self::Path),
112            "go-package" => Some(Self::GoPackage),
113            "toolchain-name" => Some(Self::ToolchainName),
114            "local-path" => Some(Self::LocalPath),
115            _ => None,
116        }
117    }
118
119    /// A TOML `positional_shape`, absent or a known name; `owner` names where it was written.
120    pub fn from_toml(name: Option<&str>, owner: &str) -> Result<Option<Self>, String> {
121        name.map(|n| Self::from_name(n).ok_or_else(|| format!("{owner}: unknown positional_shape `{n}`")))
122            .transpose()
123    }
124}
125
126/// Whether `token` names a local folder that no tool could read as a remote address. See
127/// [`PositionalShape::LocalPath`].
128pub fn is_local_path(token: &str) -> bool {
129    if token.is_empty() || token.starts_with('-') || token.contains("//") {
130        return false;
131    }
132    if token.chars().any(|c| matches!(c, ':' | '@' | '?' | '\\')) {
133        return false;
134    }
135    let mut components = token.split('/');
136    let first = components.next().unwrap_or_default();
137    let host_like = !first.starts_with('.') && !first.starts_with('~') && first.contains('.');
138    !host_like && !token.split('/').any(|c| c == "_git" || c.ends_with(".git"))
139}
140
141/// Whether `token` is a go LOCAL package/file (a filesystem path), as opposed to a
142/// module import path. See [`PositionalShape::GoPackage`].
143pub fn is_go_local_package(token: &str) -> bool {
144    token == "." || token == ".." || token.starts_with("./") || token.starts_with("../") || token.starts_with('/') || token.ends_with(".go")
145}
146
147/// Heuristic for "this token looks like a file path." Used by the
148/// `path` `PositionalShape`. Conservative on purpose — a bare word
149/// like `Tiltfile` is a valid filename in cwd but the heuristic
150/// rejects it to avoid swallowing flag-less subcommands. Callers
151/// that want bare-name acceptance should match a sub block instead.
152///
153/// A leading `~` counts, and its absence was a hole rather than part of the conservatism: the
154/// shell expands `~`, `~/x` and `~user` to a home directory, so all four are paths — but a BARE
155/// `~` carries neither `/` nor `.`, so it failed the test and every consumer that pre-filters on
156/// it skipped the operand entirely. `rg x ~` searched `$HOME` and printed matches to the model
157/// while `rg x ~/` denied; `od ~`, `tee ~`, `shred ~` and `awk '{print}' ~` did the same. The
158/// commands whose programs legitimately contain `~` (awk's match operator, an rg pattern) exclude
159/// it by POSITION before reaching here, so recognizing it costs them nothing.
160pub fn looks_like_path(token: &str) -> bool {
161    if token.is_empty() {
162        return false;
163    }
164    if token.starts_with('-') {
165        return token == "-";
166    }
167    token.starts_with('~') || token.contains('/') || token.contains('.')
168}
169
170pub trait FlagSet {
171    fn contains_flag(&self, token: &str) -> bool;
172    fn contains_short(&self, byte: u8) -> bool;
173}
174
175/// Whether `flag`, written without an inline `=value`, takes the next word as its value. An
176/// optional-value flag sits in both sets and takes a value only when glued, as getopt reads it.
177pub(crate) fn takes_next_word<S: FlagSet + ?Sized, V: FlagSet + ?Sized>(standalone: &S, valued: &V, flag: &str) -> bool {
178    valued.contains_flag(flag) && !standalone.contains_flag(flag)
179}
180
181impl FlagSet for WordSet {
182    fn contains_flag(&self, token: &str) -> bool {
183        self.contains(token)
184    }
185    fn contains_short(&self, byte: u8) -> bool {
186        self.contains_short(byte)
187    }
188}
189
190impl FlagSet for [String] {
191    fn contains_flag(&self, token: &str) -> bool {
192        self.iter().any(|f| f.as_str() == token)
193    }
194    fn contains_short(&self, byte: u8) -> bool {
195        self.iter().any(|f| f.len() == 2 && f.as_bytes()[0] == b'-' && f.as_bytes()[1] == byte)
196    }
197}
198
199impl FlagSet for Vec<String> {
200    fn contains_flag(&self, token: &str) -> bool {
201        self.as_slice().contains_flag(token)
202    }
203    fn contains_short(&self, byte: u8) -> bool {
204        self.as_slice().contains_short(byte)
205    }
206}
207
208pub struct FlagPolicy {
209    pub standalone: WordSet,
210    pub valued: WordSet,
211    pub bare: bool,
212    pub max_positional: Option<usize>,
213    pub tolerance: FlagTolerance,
214}
215
216impl FlagPolicy {
217    pub fn describe(&self) -> String {
218        use crate::docs::wordset_items;
219        let mut lines = Vec::new();
220        let standalone = wordset_items(&self.standalone);
221        if !standalone.is_empty() {
222            lines.push(format!("- Allowed standalone flags: {standalone}"));
223        }
224        let valued = wordset_items(&self.valued);
225        if !valued.is_empty() {
226            lines.push(format!("- Allowed valued flags: {valued}"));
227        }
228        if self.bare {
229            lines.push("- Bare invocation allowed".to_string());
230        }
231        if self.tolerance.unknown != UnknownTolerance::Strict {
232            lines.push("- Hyphen-prefixed positional arguments accepted".to_string());
233        }
234        if self.tolerance.numeric_dash {
235            lines.push("- Numeric shorthand accepted (e.g. -20 for -n 20)".to_string());
236        }
237        if lines.is_empty() && !self.bare {
238            return "- Positional arguments only".to_string();
239        }
240        lines.join("\n")
241    }
242}
243
244pub fn check(tokens: &[Token], policy: &FlagPolicy) -> bool {
245    check_flags(tokens, &policy.standalone, &policy.valued, policy.bare, policy.max_positional, policy.tolerance)
246}
247
248pub(crate) fn consumes_next_value(next: Option<&Token>) -> bool {
249    match next {
250        None => false,
251        Some(t) if crate::cst::opaque::is_flag_probe(t.as_str()) => true,
252        Some(t) => {
253            let b = t.as_bytes();
254            // An option-like token (starts with `-` and isn't a negative
255            // number) is never the value of a preceding valued flag. Consuming
256            // it would let an execution-enabling flag ride in as a bogus
257            // "value" — e.g. `node --check --require=evil.js`, where node runs
258            // the `--require` preload even in syntax-check mode. Negative
259            // numbers (`head -n -5`) and a lone `-` (stdin) are real values.
260            !(b.len() > 1 && b[0] == b'-' && !b[1].is_ascii_digit())
261        }
262    }
263}
264
265pub fn check_flags<S: FlagSet + ?Sized, V: FlagSet + ?Sized>(
266    tokens: &[Token],
267    standalone: &S,
268    valued: &V,
269    bare: bool,
270    max_positional: Option<usize>,
271    tolerance: FlagTolerance,
272) -> bool {
273    if tokens.len() == 1 {
274        return bare;
275    }
276    count_positionals(tokens, standalone, valued, tolerance).is_some_and(|n| max_positional.is_none_or(|max| n <= max))
277}
278
279/// The positional operands `check_flags` counts, or `None` where it would refuse a flag.
280pub fn count_positionals<S: FlagSet + ?Sized, V: FlagSet + ?Sized>(
281    tokens: &[Token],
282    standalone: &S,
283    valued: &V,
284    tolerance: FlagTolerance,
285) -> Option<usize> {
286    let mut i = 1;
287    let mut positionals: usize = 0;
288    while i < tokens.len() {
289        let t = &tokens[i];
290
291        if *t == "--" {
292            positionals += tokens.len() - i - 1;
293            break;
294        }
295
296        if tolerance.reads_commands.plus && t.starts_with('+') && !t[1..].bytes().all(|b| b.is_ascii_digit()) {
297            return None;
298        }
299
300        if !t.starts_with('-') || (*t == "-" && !standalone.contains_flag(t)) {
301            positionals += 1;
302            i += 1;
303            continue;
304        }
305
306        if tolerance.numeric_dash && t.len() > 1 && t[1..].bytes().all(|b| b.is_ascii_digit()) {
307            i += 1;
308            continue;
309        }
310
311        if standalone.contains_flag(t) {
312            i += 1;
313            continue;
314        }
315
316        if valued.contains_flag(t) {
317            if consumes_next_value(tokens.get(i + 1)) {
318                i += 2;
319            } else {
320                i += 1;
321            }
322            continue;
323        }
324
325        if let Some(flag) = t.as_str().split_once('=').map(|(f, _)| f) {
326            if valued.contains_flag(flag) {
327                i += 1;
328                continue;
329            }
330            // `--foo=value` forms are governed by the long-flag tolerance.
331            if tolerance.unknown.allows_long() {
332                positionals += 1;
333                i += 1;
334                continue;
335            }
336            return None;
337        }
338
339        if t.starts_with("--") {
340            if tolerance.unknown.allows_long() {
341                positionals += 1;
342                i += 1;
343                continue;
344            }
345            return None;
346        }
347
348        if tolerance.single_dash_words && t.len() > 1 {
349            if tolerance.unknown.allows_short() {
350                positionals += 1;
351                i += 1;
352                continue;
353            }
354            return None;
355        }
356
357        let bytes = t.as_bytes();
358        let mut j = 1;
359        while j < bytes.len() {
360            let b = bytes[j];
361            let is_last = j == bytes.len() - 1;
362            if standalone.contains_short(b) {
363                j += 1;
364                continue;
365            }
366            if valued.contains_short(b) {
367                if is_last && consumes_next_value(tokens.get(i + 1)) {
368                    i += 1;
369                }
370                break;
371            }
372            if tolerance.unknown.allows_short() {
373                positionals += 1;
374                break;
375            }
376            return None;
377        }
378        i += 1;
379    }
380    Some(positionals)
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    #[test]
388    fn local_path_refuses_an_empty_word_a_flag_and_a_double_slash() {
389        for refused in ["", "-x", "a//b"] {
390            assert!(!is_local_path(refused), "{refused:?} is not a local folder");
391        }
392        for local in ["src", "./docs", "a/b"] {
393            assert!(is_local_path(local), "{local} is a local folder");
394        }
395    }
396
397    #[test]
398    fn go_local_package_each_alternative_alone() {
399        for local in [".", "..", "./x", "../x", "/x", "x.go"] {
400            assert!(is_go_local_package(local), "{local} is local");
401        }
402        for module in ["fmt", "github.com/a/b", "a/../b", "~/x", ""] {
403            assert!(!is_go_local_package(module), "{module} is a module path");
404        }
405    }
406
407    static TEST_POLICY: FlagPolicy = FlagPolicy {
408        standalone: WordSet::flags(&[
409            "--color", "--count", "--help", "--recursive", "--version", "-H", "-c", "-i", "-l", "-n", "-o", "-r", "-s", "-v", "-w",
410        ]),
411        valued: WordSet::flags(&["--after-context", "--before-context", "--max-count", "-A", "-B", "-m"]),
412        bare: false,
413        max_positional: None,
414        tolerance: FlagTolerance::strict(),
415    };
416
417    fn toks(words: &[&str]) -> Vec<Token> {
418        words.iter().map(|s| Token::from_test(s)).collect()
419    }
420
421    #[test]
422    fn bare_denied_when_bare_false() {
423        assert!(!check(&toks(&["grep"]), &TEST_POLICY));
424    }
425
426    #[test]
427    fn bare_allowed_when_bare_true() {
428        let policy = FlagPolicy {
429            standalone: WordSet::flags(&[]),
430            valued: WordSet::flags(&[]),
431            bare: true,
432            max_positional: None,
433            tolerance: FlagTolerance::strict(),
434        };
435        assert!(check(&toks(&["uname"]), &policy));
436    }
437
438    #[test]
439    fn a_lone_dash_is_an_operand_and_counts_toward_max_positional() {
440        for max in 0..3usize {
441            let policy = FlagPolicy {
442                standalone: WordSet::flags(&["--version", "-V"]),
443                valued: WordSet::flags(&["-e"]),
444                bare: true,
445                max_positional: Some(max),
446                tolerance: FlagTolerance::strict(),
447            };
448            for dashes in 0..5usize {
449                let mut words = vec!["Rscript", "--version"];
450                words.extend(std::iter::repeat_n("-", dashes));
451                assert_eq!(check(&toks(&words), &policy), dashes <= max, "max {max}, {dashes} dashes");
452                assert_eq!(count_positionals(&toks(&words), &policy.standalone, &policy.valued, policy.tolerance), Some(dashes));
453            }
454        }
455    }
456
457    /// What a flag declared in BOTH lists actually does — measured, because the answer decides
458    /// whether an optional-value flag needs new machinery or only a name.
459    ///
460    /// TODO.md recorded that the two declarations "contradict each other and only one can be
461    /// honoured". That is not what the walk does. `standalone` is consulted first, so the BARE
462    /// spelling matches there and cannot swallow the next token; the `=` branch below it consults
463    /// `valued`, so the GLUED spelling matches too. Both are honoured, for different spellings —
464    /// which is exactly optional-value semantics, and matches getopt, where an optional argument
465    /// must be glued (`--flag=x`, never `--flag x`).
466    ///
467    /// The gap is the SHORT glued form: `-r0` reaches the cluster loop, which walks byte by byte
468    /// and has no notion of "the rest of this token is my value", so it fails on `0`.
469    #[test]
470    fn a_flag_declared_in_both_lists_already_takes_an_optional_value() {
471        static BOTH: FlagPolicy = FlagPolicy {
472            standalone: WordSet::flags(&["--long", "-r"]),
473            valued: WordSet::flags(&["--long", "-r"]),
474            bare: true,
475            max_positional: Some(0),
476            tolerance: FlagTolerance::strict(),
477        };
478        assert!(check(&toks(&["zstd", "--long"]), &BOTH), "bare long form");
479        assert!(check(&toks(&["zstd", "--long=27"]), &BOTH), "glued long form");
480        assert!(check(&toks(&["zstd", "-r"]), &BOTH), "bare short form");
481
482        // The bare form must NOT eat the next token — that swallow is how a path becomes a
483        // positional and slips the flag gate.
484        assert!(!check(&toks(&["zstd", "--long", "somefile"]), &BOTH), "the bare form must not consume the following token as its value");
485
486        // The short glued form is the one shape this does not cover.
487        assert!(!check(&toks(&["7z", "-r0"]), &BOTH), "short-glued is NOT handled today");
488    }
489
490    #[test]
491    fn only_a_flag_that_requires_a_value_takes_the_next_word() {
492        let standalone: Vec<String> = ["--toc", "--both"].map(String::from).to_vec();
493        let valued: Vec<String> = ["--to", "--both"].map(String::from).to_vec();
494        assert!(super::takes_next_word(&standalone, &valued, "--to"));
495        assert!(!super::takes_next_word(&standalone, &valued, "--both"));
496        assert!(!super::takes_next_word(&standalone, &valued, "--toc"));
497        assert!(!super::takes_next_word(&standalone, &valued, "--unknown"));
498    }
499
500    #[test]
501    fn standalone_long_flag() {
502        assert!(check(&toks(&["grep", "--recursive", "pattern", "."]), &TEST_POLICY));
503    }
504
505    #[test]
506    fn standalone_short_flag() {
507        assert!(check(&toks(&["grep", "-r", "pattern", "."]), &TEST_POLICY));
508    }
509
510    #[test]
511    fn valued_long_flag_space() {
512        assert!(check(&toks(&["grep", "--max-count", "5", "pattern"]), &TEST_POLICY));
513    }
514
515    #[test]
516    fn valued_long_flag_eq() {
517        assert!(check(&toks(&["grep", "--max-count=5", "pattern"]), &TEST_POLICY));
518    }
519
520    #[test]
521    fn valued_short_flag_space() {
522        assert!(check(&toks(&["grep", "-m", "5", "pattern"]), &TEST_POLICY));
523    }
524
525    #[test]
526    fn combined_standalone_short() {
527        assert!(check(&toks(&["grep", "-rn", "pattern", "."]), &TEST_POLICY));
528    }
529
530    #[test]
531    fn combined_short_with_valued_last() {
532        assert!(check(&toks(&["grep", "-rnm", "5", "pattern"]), &TEST_POLICY));
533    }
534
535    #[test]
536    fn combined_short_valued_mid_consumes_rest() {
537        assert!(check(&toks(&["grep", "-rmn", "pattern"]), &TEST_POLICY));
538    }
539
540    #[test]
541    fn unknown_long_flag_denied() {
542        assert!(!check(&toks(&["grep", "--exec", "cmd"]), &TEST_POLICY));
543    }
544
545    #[test]
546    fn unknown_short_flag_denied() {
547        assert!(!check(&toks(&["grep", "-z", "pattern"]), &TEST_POLICY));
548    }
549
550    #[test]
551    fn unknown_combined_short_denied() {
552        assert!(!check(&toks(&["grep", "-rz", "pattern"]), &TEST_POLICY));
553    }
554
555    #[test]
556    fn unknown_long_eq_denied() {
557        assert!(!check(&toks(&["grep", "--output=file.txt", "pattern"]), &TEST_POLICY));
558    }
559
560    #[test]
561    fn double_dash_stops_checking() {
562        assert!(check(&toks(&["grep", "--", "--not-a-flag", "file"]), &TEST_POLICY));
563    }
564
565    #[test]
566    fn positional_args_allowed() {
567        assert!(check(&toks(&["grep", "pattern", "file.txt", "other.txt"]), &TEST_POLICY));
568    }
569
570    #[test]
571    fn mixed_flags_and_positional() {
572        assert!(check(&toks(&["grep", "-rn", "--color", "--max-count", "10", "pattern", "."]), &TEST_POLICY,));
573    }
574
575    #[test]
576    fn valued_short_in_explicit_form() {
577        assert!(check(&toks(&["grep", "-A", "3", "-B", "3", "pattern"]), &TEST_POLICY));
578    }
579
580    #[test]
581    fn bare_dash_allowed_as_stdin() {
582        assert!(check(&toks(&["grep", "pattern", "-"]), &TEST_POLICY));
583    }
584
585    #[test]
586    fn valued_flag_at_end_without_value() {
587        assert!(check(&toks(&["grep", "--max-count"]), &TEST_POLICY));
588    }
589
590    #[test]
591    fn single_short_in_wordset_and_byte_array() {
592        assert!(check(&toks(&["grep", "-c", "pattern"]), &TEST_POLICY));
593    }
594
595    static SYNTAX_CHECK_POLICY: FlagPolicy = FlagPolicy {
596        standalone: WordSet::flags(&["--help", "-h"]),
597        valued: WordSet::flags(&["--check", "-c"]),
598        bare: false,
599        max_positional: Some(0),
600        tolerance: FlagTolerance::strict(),
601    };
602
603    #[test]
604    fn valued_flag_consumes_path_value() {
605        assert!(check(&toks(&["node", "--check", "app.js"]), &SYNTAX_CHECK_POLICY));
606        assert!(check(&toks(&["node", "-c", "app.js"]), &SYNTAX_CHECK_POLICY));
607    }
608
609    #[test]
610    fn valued_flag_does_not_swallow_following_long_option() {
611        assert!(!check(&toks(&["node", "--check", "--require=./evil.js"]), &SYNTAX_CHECK_POLICY,));
612    }
613
614    #[test]
615    fn valued_short_does_not_swallow_following_option() {
616        assert!(!check(&toks(&["node", "-c", "-r./evil.js"]), &SYNTAX_CHECK_POLICY));
617    }
618
619    #[test]
620    fn valued_flag_still_consumes_negative_number() {
621        let policy = FlagPolicy {
622            standalone: WordSet::flags(&[]),
623            valued: WordSet::flags(&["-n"]),
624            bare: false,
625            max_positional: Some(1),
626            tolerance: FlagTolerance::strict(),
627        };
628        assert!(check(&toks(&["head", "-n", "-5", "file"]), &policy));
629    }
630
631    static LIMITED_POLICY: FlagPolicy = FlagPolicy {
632        standalone: WordSet::flags(&["--count", "-c", "-d", "-i", "-u"]),
633        valued: WordSet::flags(&["--skip-fields", "-f", "-s"]),
634        bare: true,
635        max_positional: Some(1),
636        tolerance: FlagTolerance::strict(),
637    };
638
639    #[test]
640    fn max_positional_within_limit() {
641        assert!(check(&toks(&["uniq", "input.txt"]), &LIMITED_POLICY));
642    }
643
644    #[test]
645    fn max_positional_exceeded() {
646        assert!(!check(&toks(&["uniq", "input.txt", "output.txt"]), &LIMITED_POLICY));
647    }
648
649    #[test]
650    fn max_positional_with_flags_within_limit() {
651        assert!(check(&toks(&["uniq", "-c", "-f", "3", "input.txt"]), &LIMITED_POLICY));
652    }
653
654    #[test]
655    fn max_positional_with_flags_exceeded() {
656        assert!(!check(&toks(&["uniq", "-c", "input.txt", "output.txt"]), &LIMITED_POLICY));
657    }
658
659    #[test]
660    fn max_positional_after_double_dash() {
661        assert!(!check(&toks(&["uniq", "--", "input.txt", "output.txt"]), &LIMITED_POLICY));
662    }
663
664    #[test]
665    fn max_positional_bare_allowed() {
666        assert!(check(&toks(&["uniq"]), &LIMITED_POLICY));
667    }
668
669    static BOTH_TOLERANCES_POLICY: FlagPolicy = FlagPolicy {
670        standalone: WordSet::flags(&["-E", "-e", "-n"]),
671        valued: WordSet::flags(&[]),
672        bare: true,
673        max_positional: None,
674        tolerance: FlagTolerance {
675            unknown: UnknownTolerance::Both,
676            numeric_dash: false,
677            single_dash_words: false,
678            ..FlagTolerance::strict()
679        },
680    };
681
682    #[test]
683    fn both_tolerances_accept_unknown_long() {
684        assert!(check(&toks(&["echo", "--unknown", "hello"]), &BOTH_TOLERANCES_POLICY));
685    }
686
687    #[test]
688    fn both_tolerances_accept_unknown_short() {
689        assert!(check(&toks(&["echo", "-x", "hello"]), &BOTH_TOLERANCES_POLICY));
690    }
691
692    #[test]
693    fn both_tolerances_accept_triple_dash() {
694        assert!(check(&toks(&["echo", "---"]), &BOTH_TOLERANCES_POLICY));
695    }
696
697    #[test]
698    fn both_tolerances_known_flags_still_work() {
699        assert!(check(&toks(&["echo", "-n", "hello"]), &BOTH_TOLERANCES_POLICY));
700    }
701
702    #[test]
703    fn both_tolerances_combo_known_short() {
704        assert!(check(&toks(&["echo", "-ne", "hello"]), &BOTH_TOLERANCES_POLICY));
705    }
706
707    #[test]
708    fn both_tolerances_combo_unknown_short_byte() {
709        assert!(check(&toks(&["echo", "-nx", "hello"]), &BOTH_TOLERANCES_POLICY));
710    }
711
712    #[test]
713    fn both_tolerances_unknown_eq_form() {
714        assert!(check(&toks(&["echo", "--foo=bar"]), &BOTH_TOLERANCES_POLICY));
715    }
716
717    // Narrow tolerance: short-only
718    // tolerate_unknown_short = true accepts unknown single-dash tokens
719    // (-X, -mayDie, -help) as positional, while leaving double-dash unknowns
720    // strict. This is the safer setting because most modern destructive
721    // flags are double-dash.
722
723    static SHORT_ONLY_POLICY: FlagPolicy = FlagPolicy {
724        standalone: WordSet::flags(&["--help"]),
725        valued: WordSet::flags(&[]),
726        bare: false,
727        max_positional: None,
728        tolerance: FlagTolerance {
729            unknown: UnknownTolerance::Short,
730            numeric_dash: false,
731            single_dash_words: false,
732            ..FlagTolerance::strict()
733        },
734    };
735
736    #[test]
737    fn short_only_accepts_unknown_dash_letter() {
738        assert!(check(&toks(&["sample", "-mayDie"]), &SHORT_ONLY_POLICY));
739    }
740
741    #[test]
742    fn short_only_accepts_single_dash_long_word() {
743        // pdftotext-style: `-help`, `-layout`, `-version` (single dash + word)
744        assert!(check(&toks(&["pdftotext", "-layout"]), &SHORT_ONLY_POLICY));
745    }
746
747    #[test]
748    fn short_only_denies_unknown_double_dash() {
749        // The whole point of the narrow split: --evil-flag must not slip
750        // through when only short-tolerance is on.
751        assert!(!check(&toks(&["sample", "--evil-flag"]), &SHORT_ONLY_POLICY));
752    }
753
754    #[test]
755    fn short_only_denies_unknown_eq_form() {
756        assert!(!check(&toks(&["sample", "--evil=value"]), &SHORT_ONLY_POLICY));
757    }
758
759    #[test]
760    fn short_only_known_long_flag_still_works() {
761        assert!(check(&toks(&["sample", "--help"]), &SHORT_ONLY_POLICY));
762    }
763
764    // Narrow tolerance: long-only
765    // tolerate_unknown_long = true accepts unknown double-dash tokens as
766    // positional. This is the dangerous form; reserved for tools like AWS
767    // CLI whose long-flag surface is genuinely unbounded.
768
769    static LONG_ONLY_POLICY: FlagPolicy = FlagPolicy {
770        standalone: WordSet::flags(&["--help"]),
771        valued: WordSet::flags(&[]),
772        bare: false,
773        max_positional: None,
774        tolerance: FlagTolerance {
775            unknown: UnknownTolerance::Long,
776            numeric_dash: false,
777            single_dash_words: false,
778            ..FlagTolerance::strict()
779        },
780    };
781
782    #[test]
783    fn long_only_accepts_unknown_double_dash() {
784        assert!(check(&toks(&["aws", "--some-aws-flag"]), &LONG_ONLY_POLICY));
785    }
786
787    #[test]
788    fn long_only_accepts_unknown_eq_form() {
789        assert!(check(&toks(&["aws", "--filter=Name=tag,Values=foo"]), &LONG_ONLY_POLICY,));
790    }
791
792    #[test]
793    fn long_only_denies_unknown_short_dash() {
794        assert!(!check(&toks(&["aws", "-x"]), &LONG_ONLY_POLICY));
795    }
796
797    // Both tolerances false: strict
798
799    static STRICT_POLICY: FlagPolicy = FlagPolicy {
800        standalone: WordSet::flags(&["--help"]),
801        valued: WordSet::flags(&[]),
802        bare: false,
803        max_positional: None,
804        tolerance: FlagTolerance::strict(),
805    };
806
807    #[test]
808    fn strict_denies_unknown_short() {
809        assert!(!check(&toks(&["foo", "-evil"]), &STRICT_POLICY));
810    }
811
812    #[test]
813    fn strict_denies_unknown_long() {
814        assert!(!check(&toks(&["foo", "--evil"]), &STRICT_POLICY));
815    }
816
817    #[test]
818    fn strict_known_flag_passes() {
819        assert!(check(&toks(&["foo", "--help"]), &STRICT_POLICY));
820    }
821
822    #[test]
823    fn both_tolerances_with_max_positional() {
824        let policy = FlagPolicy {
825            standalone: WordSet::flags(&["-n"]),
826            valued: WordSet::flags(&[]),
827            bare: true,
828            max_positional: Some(2),
829            tolerance: FlagTolerance {
830                unknown: UnknownTolerance::Both,
831                numeric_dash: false,
832                single_dash_words: false,
833                ..FlagTolerance::strict()
834            },
835        };
836        assert!(check(&toks(&["echo", "--unknown", "hello"]), &policy));
837        assert!(!check(&toks(&["echo", "--a", "--b", "--c"]), &policy));
838    }
839
840    static NUMERIC_DASH_POLICY: FlagPolicy = FlagPolicy {
841        standalone: WordSet::flags(&["--help", "--quiet", "--verbose", "--version", "-V", "-h", "-q", "-v", "-z"]),
842        valued: WordSet::flags(&["--bytes", "--lines", "-c", "-n"]),
843        bare: true,
844        max_positional: None,
845        tolerance: FlagTolerance { numeric_dash: true, ..FlagTolerance::strict() },
846    };
847
848    #[test]
849    fn numeric_dash_single_digit() {
850        assert!(check(&toks(&["head", "-5"]), &NUMERIC_DASH_POLICY));
851    }
852
853    #[test]
854    fn numeric_dash_multi_digit() {
855        assert!(check(&toks(&["head", "-20"]), &NUMERIC_DASH_POLICY));
856    }
857
858    #[test]
859    fn numeric_dash_large_number() {
860        assert!(check(&toks(&["head", "-1000"]), &NUMERIC_DASH_POLICY));
861    }
862
863    #[test]
864    fn numeric_dash_with_file_arg() {
865        assert!(check(&toks(&["head", "-20", "file.txt"]), &NUMERIC_DASH_POLICY));
866    }
867
868    #[test]
869    fn numeric_dash_with_other_flags() {
870        assert!(check(&toks(&["head", "-q", "-20", "file.txt"]), &NUMERIC_DASH_POLICY));
871    }
872
873    #[test]
874    fn numeric_dash_zero() {
875        assert!(check(&toks(&["head", "-0"]), &NUMERIC_DASH_POLICY));
876    }
877
878    #[test]
879    fn numeric_dash_still_rejects_unknown_flags() {
880        assert!(!check(&toks(&["head", "-x"]), &NUMERIC_DASH_POLICY));
881    }
882
883    #[test]
884    fn numeric_dash_rejects_mixed_alpha_num() {
885        assert!(!check(&toks(&["head", "-20x"]), &NUMERIC_DASH_POLICY));
886    }
887
888    #[test]
889    fn numeric_dash_disabled_rejects_multi_digit() {
890        assert!(!check(&toks(&["grep", "-20", "pattern"]), &TEST_POLICY));
891    }
892
893    static WORDS_POLICY: FlagPolicy = FlagPolicy {
894        standalone: WordSet::flags(&["-a", "-f", "-i", "-ifd0"]),
895        valued: WordSet::flags(&["-ext"]),
896        bare: false,
897        max_positional: None,
898        tolerance: FlagTolerance { single_dash_words: true, ..FlagTolerance::strict() },
899    };
900
901    #[test]
902    fn single_dash_words_never_split_a_word_into_letters() {
903        assert!(!check(&toks(&["exiftool", "-if", "system(1)", "a.jpg"]), &WORDS_POLICY));
904        assert!(!check(&toks(&["exiftool", "-fa", "a.jpg"]), &WORDS_POLICY));
905        assert!(check(&toks(&["exiftool", "-fa", "a.jpg"]), &FlagPolicy { tolerance: FlagTolerance::strict(), ..WORDS_POLICY }));
906    }
907
908    #[test]
909    fn single_dash_words_accept_listed_words_values_and_stdin() {
910        assert!(check(&toks(&["exiftool", "-ifd0", "-a", "-ext", "jpg", "a.jpg"]), &WORDS_POLICY));
911        assert!(check(&toks(&["exiftool", "-i", "-f", "-"]), &WORDS_POLICY));
912    }
913
914    #[test]
915    fn single_dash_words_under_short_tolerance_count_unknowns_as_positionals() {
916        let policy = FlagPolicy {
917            max_positional: Some(1),
918            tolerance: FlagTolerance {
919                unknown: UnknownTolerance::Short,
920                single_dash_words: true,
921                numeric_dash: false,
922                ..FlagTolerance::strict()
923            },
924            ..WORDS_POLICY
925        };
926        assert!(check(&toks(&["exiftool", "-if"]), &policy));
927        assert!(!check(&toks(&["exiftool", "-if", "-zz"]), &policy));
928    }
929
930    #[test]
931    fn looks_like_path_accepts_relative() {
932        assert!(looks_like_path("./Tiltfile"));
933        assert!(looks_like_path("path/to/file"));
934    }
935
936    #[test]
937    fn looks_like_path_accepts_dotted() {
938        assert!(looks_like_path("Tiltfile.dev"));
939        assert!(looks_like_path("file.rb"));
940    }
941
942    #[test]
943    fn looks_like_path_accepts_stdin_dash() {
944        assert!(looks_like_path("-"));
945    }
946
947    #[test]
948    fn looks_like_path_rejects_flag() {
949        assert!(!looks_like_path("--help"));
950        assert!(!looks_like_path("-x"));
951    }
952
953    #[test]
954    fn looks_like_path_rejects_bare_word() {
955        assert!(!looks_like_path("Tiltfile"));
956        assert!(!looks_like_path("up"));
957    }
958
959    #[test]
960    fn looks_like_path_rejects_empty() {
961        assert!(!looks_like_path(""));
962    }
963
964    #[test]
965    fn positional_shape_path_matches() {
966        assert!(PositionalShape::Path.matches("./file.rb"));
967        assert!(!PositionalShape::Path.matches("--flag"));
968    }
969
970    #[test]
971    fn positional_shape_from_name() {
972        assert_eq!(PositionalShape::from_name("path"), Some(PositionalShape::Path));
973        assert_eq!(PositionalShape::from_name("nope"), None);
974        assert_eq!(PositionalShape::from_name("local-path"), Some(PositionalShape::LocalPath));
975    }
976
977    proptest::proptest! {
978        /// Every spelling kustomize reads as a git repository is refused as a local folder, and a
979        /// folder spelled with plain words, anchored or not, is accepted.
980        #[test]
981        fn a_repository_address_is_never_a_local_path(
982            host in proptest::string::string_regex("[a-z]{1,8}\\.(com|org|io)").unwrap(),
983            parts in proptest::collection::vec(proptest::string::string_regex("[a-z][a-z0-9_-]{0,7}").unwrap(), 1..4),
984            anchor in proptest::sample::select(vec!["", "./", "../", "~/", "/"]),
985            form in proptest::sample::select(vec![
986                "{h}/{p}", "https://{h}/{p}", "ssh://git@{h}/{p}", "git@{h}:{p}", "gh:{p}",
987                "{h}/{p}?ref=v1", "{h}/{p}//sub", "local/{p}.git", "{p}/_git/x", "file:///{p}",
988            ]),
989        ) {
990            let path = parts.join("/");
991            let remote = form.replace("{h}", &host).replace("{p}", &path);
992            proptest::prop_assert!(!is_local_path(&remote), "{}", remote);
993            let local = format!("{anchor}{path}");
994            proptest::prop_assert!(is_local_path(&local), "{}", local);
995        }
996    }
997
998    #[test]
999    fn a_vec_of_flags_answers_short_lookups_as_its_slice_does() {
1000        let lists: [&[&str]; 4] = [&[], &["-x", "--long", "-y"], &["--x", "-", "-xy"], &["id", "if", "-i"]];
1001        for list in lists {
1002            let flags: Vec<String> = list.iter().map(|s| (*s).to_string()).collect();
1003            for byte in 0..=u8::MAX {
1004                let expected = list.iter().any(|f| f.len() == 2 && f.as_bytes()[0] == b'-' && f.as_bytes()[1] == byte);
1005                assert_eq!(flags.contains_short(byte), expected, "{list:?} byte {byte}");
1006                assert_eq!(flags.as_slice().contains_short(byte), expected, "{list:?} byte {byte}");
1007            }
1008        }
1009    }
1010
1011    #[test]
1012    fn an_opaque_probe_is_consumed_as_a_flag_value_where_other_options_are_not() {
1013        let next = |w: &str| consumes_next_value(Some(&Token::from_test(w)));
1014        assert!(next(crate::cst::opaque::FLAG_PROBE));
1015        assert!(next(crate::cst::opaque::SHORT_PROBE));
1016        assert!(!next("--require=evil.js"));
1017        assert!(!next("-%x"));
1018        assert!(next("-5"));
1019        assert!(next("-"));
1020        assert!(!consumes_next_value(None));
1021    }
1022
1023    fn described(standalone: &'static [&'static str], valued: &'static [&'static str], bare: bool, tolerance: FlagTolerance) -> String {
1024        FlagPolicy { standalone: WordSet::flags(standalone), valued: WordSet::flags(valued), bare, max_positional: None, tolerance }
1025            .describe()
1026    }
1027
1028    #[test]
1029    fn describe_lists_each_flag_group_on_its_own_line() {
1030        assert_eq!(
1031            described(&["--all"], &["--max"], true, FlagTolerance::strict()),
1032            "- Allowed standalone flags: --all\n- Allowed valued flags: --max\n- Bare invocation allowed"
1033        );
1034    }
1035
1036    #[test]
1037    fn describe_names_every_flag_of_a_group() {
1038        let text = described(&["--all", "-a"], &[], false, FlagTolerance::strict());
1039        assert!(text.starts_with("- Allowed standalone flags: "));
1040        assert!(text.contains("--all") && text.contains("-a"));
1041        assert!(!text.contains("valued"));
1042    }
1043
1044    #[test]
1045    fn describe_an_empty_strict_policy_says_positional_only() {
1046        assert_eq!(described(&[], &[], false, FlagTolerance::strict()), "- Positional arguments only");
1047    }
1048
1049    #[test]
1050    fn describe_an_empty_bare_policy_says_bare_only() {
1051        assert_eq!(described(&[], &[], true, FlagTolerance::strict()), "- Bare invocation allowed");
1052    }
1053
1054    #[test]
1055    fn describe_reports_tolerances() {
1056        let lenient =
1057            FlagTolerance { unknown: UnknownTolerance::Short, numeric_dash: true, single_dash_words: false, ..FlagTolerance::strict() };
1058        assert_eq!(
1059            described(&[], &[], false, lenient),
1060            "- Hyphen-prefixed positional arguments accepted\n- Numeric shorthand accepted (e.g. -20 for -n 20)"
1061        );
1062        let numeric_only = FlagTolerance { numeric_dash: true, ..FlagTolerance::strict() };
1063        assert_eq!(described(&[], &[], false, numeric_only), "- Numeric shorthand accepted (e.g. -20 for -n 20)");
1064    }
1065
1066    #[test]
1067    fn describe_of_the_shared_test_policy_names_its_flags() {
1068        let text = TEST_POLICY.describe();
1069        let lines: Vec<&str> = text.lines().collect();
1070        assert_eq!(lines.len(), 2);
1071        assert!(lines[0].starts_with("- Allowed standalone flags: ") && lines[0].contains("--recursive"));
1072        assert!(lines[1].starts_with("- Allowed valued flags: ") && lines[1].contains("--max-count"));
1073    }
1074}