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