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