Skip to main content

safe_chains/registry/
policy.rs

1use crate::parse::Token;
2use crate::policy::{FlagSet, FlagTolerance, UnknownTolerance, check_flags, consumes_next_value, count_positionals};
3use crate::verdict::{SafetyLevel, Verdict};
4
5use super::types::{PassthroughSpec, TomlLevel, TomlPassthrough};
6
7#[derive(Debug, Clone)]
8pub struct OwnedPolicy {
9    pub standalone: Vec<String>,
10    pub valued: Vec<String>,
11    pub bare: bool,
12    pub max_positional: Option<usize>,
13    pub min_positional: Option<usize>,
14    pub tolerance: FlagTolerance,
15    pub passthrough: Option<Box<PassthroughSpec>>,
16}
17
18impl OwnedPolicy {
19    pub(super) fn allow_all() -> Self {
20        OwnedPolicy {
21            standalone: Vec::new(),
22            valued: Vec::new(),
23            bare: true,
24            max_positional: None,
25            min_positional: None,
26            tolerance: FlagTolerance { unknown: UnknownTolerance::Both, numeric_dash: false, single_dash_words: false },
27            passthrough: None,
28        }
29    }
30
31    pub(super) fn deny_all() -> Self {
32        OwnedPolicy {
33            standalone: Vec::new(),
34            valued: Vec::new(),
35            bare: false,
36            max_positional: Some(0),
37            min_positional: None,
38            tolerance: FlagTolerance::default(),
39            passthrough: None,
40        }
41    }
42}
43
44pub(super) fn build_passthrough(toml: TomlPassthrough) -> Box<PassthroughSpec> {
45    let policy = super::build::build_policy(
46        toml.standalone, toml.valued, toml.optional_valued, toml.bare, toml.max_positional, toml.tolerate_unknown_short,
47        toml.tolerate_unknown_long, toml.numeric_dash,
48    );
49    let mut require_any = toml.require_any;
50    if let Some(guard) = toml.guard {
51        require_any.push(guard);
52    }
53    if let Some(short) = toml.guard_short {
54        require_any.push(short);
55    }
56    let level: SafetyLevel = toml.level.unwrap_or(TomlLevel::Inert).into();
57    Box::new(PassthroughSpec { policy, require_any, level })
58}
59
60fn has_unvalued_flag(tokens: &[Token], policy: &OwnedPolicy) -> bool {
61    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
62    for (i, token) in tokens.iter().enumerate().skip(1) {
63        let t = token.as_str();
64        if !t.starts_with('-') {
65            continue;
66        }
67        if valued.contains_flag(t) {
68            if !consumes_next_value(tokens.get(i + 1)) {
69                return true;
70            }
71            continue;
72        }
73        if !policy.tolerance.single_dash_words {
74            let bytes = t.as_bytes();
75            for (j, &b) in bytes.iter().enumerate().skip(1) {
76                if standalone.contains_short(b) {
77                    continue;
78                }
79                if valued.contains_short(b) {
80                    if j + 1 == bytes.len() && !consumes_next_value(tokens.get(i + 1)) {
81                        return true;
82                    }
83                    break;
84                }
85                break;
86            }
87        }
88    }
89    false
90}
91
92pub(super) fn check_with_passthrough(tokens: &[Token], policy: &OwnedPolicy, base_level: SafetyLevel) -> Verdict {
93    if let Some(pass) = &policy.passthrough
94        && let Some(rel) = tokens[1..].iter().position(|t| t == "--")
95    {
96        let sep = rel + 1;
97        let prefix = &tokens[..sep];
98        let tail = &tokens[sep..];
99        if !check_owned(prefix, policy)
100            || has_unvalued_flag(prefix, policy)
101            || tail[1..].iter().any(|t| t == "--")
102            || !check_owned(tail, &pass.policy)
103            || has_unvalued_flag(tail, &pass.policy)
104        {
105            return Verdict::Denied;
106        }
107        let guarded = pass.require_any.is_empty()
108            || flag_given(tail, &pass.policy, &pass.require_any)
109            || flag_given(prefix, policy, &pass.require_any);
110        return if guarded { Verdict::Allowed(pass.level) } else { Verdict::Denied };
111    }
112    if check_owned(tokens, policy) {
113        if let Some(pass) = &policy.passthrough {
114            if has_unvalued_flag(tokens, policy) {
115                return Verdict::Denied;
116            }
117            if flag_given(tokens, policy, &pass.require_any) {
118                return Verdict::Allowed(pass.level);
119            }
120        }
121        Verdict::Allowed(base_level)
122    } else {
123        Verdict::Denied
124    }
125}
126
127pub(super) fn check_owned(tokens: &[Token], policy: &OwnedPolicy) -> bool {
128    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
129    check_flags(tokens, standalone, valued, policy.bare, policy.max_positional, policy.tolerance)
130        && policy
131            .min_positional
132            .is_none_or(|min| count_positionals(tokens, standalone, valued, policy.tolerance).is_some_and(|n| n >= min))
133}
134
135/// Whether one of `wanted` is given AS A FLAG: not as the value of the flag before it, not glued
136/// into a short cluster after a flag that takes the rest as its value (`-rm` is `-r m`), and not
137/// after `--`.
138///
139/// A required flag that only appears to be present is how a guarded sub runs its unguarded form:
140/// `jj describe -rm` names revision `m` and opens the editor.
141pub(super) fn flag_given(tokens: &[Token], policy: &OwnedPolicy, wanted: &[String]) -> bool {
142    let (standalone, valued) = (policy.standalone.as_slice(), policy.valued.as_slice());
143    let wants = |flag: &str| wanted.iter().any(|w| w == flag);
144    let mut i = 1;
145    while i < tokens.len() {
146        let t = tokens[i].as_str();
147        if t == "--" {
148            return false;
149        }
150        i += 1;
151        if wants(t) {
152            return true;
153        }
154        if !t.starts_with('-') || t == "-" {
155            continue;
156        }
157        if t.starts_with("--") {
158            let name = t.split_once('=').map_or(t, |(name, _)| name);
159            if wants(name) {
160                return true;
161            }
162            if !t.contains('=') && valued.contains_flag(name) && consumes_next_value(tokens.get(i)) {
163                i += 1;
164            }
165            continue;
166        }
167        if policy.tolerance.single_dash_words || valued.contains_flag(t) {
168            if valued.contains_flag(t) && consumes_next_value(tokens.get(i)) {
169                i += 1;
170            }
171            continue;
172        }
173        let bytes = t.as_bytes();
174        for (j, &b) in bytes.iter().enumerate().skip(1) {
175            if wanted.iter().any(|w| w.as_bytes() == [b'-', b]) {
176                return true;
177            }
178            if valued.contains_short(b) {
179                if j == bytes.len() - 1 && consumes_next_value(tokens.get(i)) {
180                    i += 1;
181                }
182                break;
183            }
184            if !standalone.contains_short(b) {
185                break;
186            }
187        }
188    }
189    false
190}
191
192/// Returns the first non-flag token after `tokens[0]`, treating the
193/// policy's `valued` flags as consuming the next argument and its
194/// `standalone` flags as zero-arg. `--` ends flag scanning. `-` is a
195/// positional (the conventional stdin marker). Used by fallback
196/// grammars that want to apply a `PositionalShape` predicate to the
197/// first positional without re-implementing flag walking.
198pub(super) fn min_positional_fits(parent: &str, toml: &super::types::TomlSub, policy_free: bool) -> Result<(), String> {
199    let Some(min) = toml.min_positional else { return Ok(()) };
200    if policy_free || !toml.sub.is_empty() || !toml.first_arg.is_empty() || !toml.credential_first_arg.is_empty() {
201        return Err(format!("command '{parent}' sub `{}`: min_positional needs a flag policy to count operands against", toml.name));
202    }
203    match toml.max_positional {
204        Some(max) if min > max => Err(format!("command '{parent}' sub `{}`: min_positional {min} exceeds max_positional {max}", toml.name)),
205        _ => Ok(()),
206    }
207}
208
209pub(super) fn first_positional<'a>(tokens: &'a [Token], policy: &OwnedPolicy) -> Option<&'a str> {
210    first_positional_at(tokens, policy).map(|(_, s)| s)
211}
212
213/// [`first_positional`], plus WHERE it was found.
214///
215/// The index is what lets a caller split an invocation at the executor: everything up to and
216/// including that token is the command's own grammar and can be checked against its flag policy,
217/// while everything after it is the SCRIPT's argv and cannot. `dispatch_executor` needs exactly
218/// that split — see the comment there.
219///
220/// Expressed as one walk with `first_positional` delegating to it, rather than two functions that
221/// scan independently: the value and its index must never disagree about which token is the
222/// executor, and two copies of this loop is how they would.
223pub(super) fn first_positional_at<'a>(tokens: &'a [Token], policy: &OwnedPolicy) -> Option<(usize, &'a str)> {
224    let standalone = policy.standalone.as_slice();
225    let valued = policy.valued.as_slice();
226    let mut i = 1;
227    while i < tokens.len() {
228        let t = &tokens[i];
229        let s = t.as_str();
230        if s == "--" {
231            return tokens.get(i + 1).map(|t| (i + 1, t.as_str()));
232        }
233        if s == "-" || !s.starts_with('-') {
234            return Some((i, s));
235        }
236        if standalone.contains_flag(s) {
237            i += 1;
238            continue;
239        }
240        if valued.contains_flag(s) {
241            i += 2;
242            continue;
243        }
244        if let Some((flag, _)) = s.split_once('=')
245            && valued.contains_flag(flag)
246        {
247            i += 1;
248            continue;
249        }
250        // Unknown flag: bail out — it's the policy validator's job to
251        // accept or reject. Either way, we've reached the end of the
252        // recognized flag run without finding a positional.
253        return None;
254    }
255    None
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use crate::parse::Token;
262    use crate::policy::FlagTolerance;
263
264    fn toks(words: &[&str]) -> Vec<Token> {
265        words.iter().map(|s| Token::from_test(s)).collect()
266    }
267
268    fn policy(standalone: &[&str], valued: &[&str], max_positional: Option<usize>) -> OwnedPolicy {
269        OwnedPolicy {
270            standalone: standalone.iter().map(|s| s.to_string()).collect(),
271            valued: valued.iter().map(|s| s.to_string()).collect(),
272            bare: true,
273            max_positional,
274            min_positional: None,
275            tolerance: FlagTolerance::strict(),
276            passthrough: None,
277        }
278    }
279
280    #[test]
281    fn first_positional_finds_bare_arg() {
282        let p = policy(&[], &[], None);
283        let tokens = toks(&["cmd", "arg"]);
284        assert_eq!(first_positional(&tokens, &p), Some("arg"));
285    }
286
287    #[test]
288    fn first_positional_skips_standalone_flags() {
289        let p = policy(&["--verbose"], &[], None);
290        let tokens = toks(&["cmd", "--verbose", "file"]);
291        assert_eq!(first_positional(&tokens, &p), Some("file"));
292    }
293
294    #[test]
295    fn first_positional_skips_valued_flag_value() {
296        let p = policy(&[], &["--type"], None);
297        let tokens = toks(&["cmd", "--type", "erb", "file.erb"]);
298        assert_eq!(first_positional(&tokens, &p), Some("file.erb"));
299    }
300
301    #[test]
302    fn first_positional_skips_valued_flag_eq_form() {
303        let p = policy(&[], &["--type"], None);
304        let tokens = toks(&["cmd", "--type=erb", "file.erb"]);
305        assert_eq!(first_positional(&tokens, &p), Some("file.erb"));
306    }
307
308    #[test]
309    fn first_positional_treats_double_dash_as_terminator() {
310        let p = policy(&["--verbose"], &[], None);
311        let tokens = toks(&["cmd", "--", "--verbose"]);
312        // After --, the very next token (even if flag-shaped) is positional.
313        assert_eq!(first_positional(&tokens, &p), Some("--verbose"));
314    }
315
316    #[test]
317    fn first_positional_treats_lone_dash_as_positional() {
318        let p = policy(&[], &[], None);
319        let tokens = toks(&["cmd", "-"]);
320        assert_eq!(first_positional(&tokens, &p), Some("-"));
321    }
322
323    #[test]
324    fn first_positional_returns_none_for_no_args() {
325        let p = policy(&[], &[], None);
326        let tokens = toks(&["cmd"]);
327        assert_eq!(first_positional(&tokens, &p), None);
328    }
329
330    #[test]
331    fn first_positional_returns_none_for_only_flags() {
332        let p = policy(&["--help"], &[], None);
333        let tokens = toks(&["cmd", "--help"]);
334        assert_eq!(first_positional(&tokens, &p), None);
335    }
336
337    #[test]
338    fn first_positional_returns_none_on_unknown_flag() {
339        // Bails out at the unknown flag rather than guessing — the policy
340        // validator is responsible for rejecting or accepting it.
341        let p = policy(&[], &[], None);
342        let tokens = toks(&["cmd", "--unknown", "file"]);
343        assert_eq!(first_positional(&tokens, &p), None);
344    }
345
346    /// Property tests for `first_positional` / `first_positional_at` / `check_owned`.
347    ///
348    /// Each property pins an invariant of the function pair rather than an example. They share
349    /// the in-module `policy`/`toks` builders and run under `proptest` so the synthesized tokens
350    /// stay inside the alphabet those builders already understand.
351    mod prop {
352        use super::*;
353        use proptest::prelude::*;
354
355        /// A flag-shaped tail token (regex covers `-`, `--`, and `--name=value` shapes).
356        const FLAG_RE: &str = "--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?";
357        /// A never-flag-shaped token (no leading `-`, otherwise printable).
358        const NON_FLAG_RE: &str = "[a-zA-Z][a-zA-Z0-9._]{0,7}";
359
360        fn toks_owned(words: &[String]) -> Vec<Token> {
361            words.iter().cloned().map(Token::from_raw).collect()
362        }
363
364        /// Reference implementation of `first_positional_at` for the case where BOTH flag lists
365        /// are empty. In that mode the documented behavior reduces to: walk forward, return
366        /// `(i + 1, next)` after a bare `--`, return `(i, s)` for `-` or any non-`-`-starting
367        /// token, and return `None` on any other flag-shaped token. Used as the oracle.
368        fn oracle_first_positional_at(tokens: &[Token]) -> Option<(usize, &str)> {
369            // Skips index 0 and returns the same answer the documented walk would on an empty
370            // grammar: look at one token, then stop. Encoded as `if let` rather than a loop
371            // because every branch decides the result on the first token and a loop would loop
372            // at most once.
373            let (offset, t) = tokens.iter().enumerate().nth(1)?;
374            let s = t.as_str();
375            if s == "--" {
376                let i = offset + 1;
377                return tokens.get(i).map(|t| (i, t.as_str()));
378            }
379            if s == "-" || !s.starts_with('-') {
380                return Some((offset, s));
381            }
382            None
383        }
384
385        proptest! {
386            /// Consistency / roundtrip: `first_positional` delegates to `first_positional_at`,
387            /// so the string it returns must equal the string half of the indexed pair for
388            /// EVERY (tokens, policy) pair. A regression that splits the two walks apart —
389            /// the very thing the docstring warns against — fails here.
390            #[test]
391            fn first_positional_and_first_positional_at_agree_on_the_returned_string(
392                tail in proptest::collection::vec("(-|--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})", 0..8),
393                standalone in proptest::collection::vec(FLAG_RE, 0..4),
394                valued in proptest::collection::vec(FLAG_RE, 0..4),
395            ) {
396                let mut words = vec!["cmd".to_string()];
397                words.extend(tail);
398                let tokens = toks_owned(&words);
399                let p = policy(
400                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
401                    &valued.iter().map(String::as_str).collect::<Vec<_>>(),
402                    None,
403                );
404                let expected = first_positional_at(&tokens, &p).map(|(_, s)| s.to_string());
405                let actual = first_positional(&tokens, &p).map(|s| s.to_string());
406                proptest::prop_assert_eq!(actual, expected);
407            }
408
409            /// Index honesty: the index returned by `first_positional_at` must really point
410            /// at the token whose text it pairs with. The walk stores `(i, s)` as one
411            /// expression so they cannot disagree by construction, and this property pins
412            /// that coupling against any future change that recomputes one half from a
413            /// different loop variable.
414            #[test]
415            fn first_positional_at_index_points_at_the_returned_token(
416                standalone in proptest::collection::vec(FLAG_RE, 0..3),
417                valued in proptest::collection::vec(FLAG_RE, 0..3),
418                tail in proptest::collection::vec(
419                    "(--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})",
420                    1..6,
421                ),
422            ) {
423                let mut words = vec!["cmd".to_string()];
424                words.extend(tail);
425                let tokens = toks_owned(&words);
426                let p = policy(
427                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
428                    &valued.iter().map(String::as_str).collect::<Vec<_>>(),
429                    None,
430                );
431                if let Some((i, s)) = first_positional_at(&tokens, &p) {
432                    proptest::prop_assert!(i < tokens.len(), "index {} past tokens.len()={}", i, tokens.len());
433                    proptest::prop_assert_eq!(tokens[i].as_str(), s);
434                }
435            }
436
437            /// Oracle / differential: with both `standalone` and `valued` empty the walk
438            /// collapses to a four-line scan. This property states that the contracted
439            /// implementation equals the inlined reference for EVERY generated shape, so
440            /// a refactor that introduced extra logic for the empty-grammar case would be
441            /// caught — the empty case is the one that has to match the docstring.
442            #[test]
443            fn first_positional_with_empty_grammars_matches_a_simple_scan(
444                tail in proptest::collection::vec(
445                    "(-|--|--?[a-zA-Z][a-zA-Z0-9._-]{0,7}(=[a-zA-Z0-9._-]{1,8})?|[a-zA-Z][a-zA-Z0-9._]{0,7})",
446                    0..6,
447                ),
448            ) {
449                let mut words = vec!["cmd".to_string()];
450                words.extend(tail);
451                let tokens = toks_owned(&words);
452                let p = policy(&[], &[], None);
453                let oracle = oracle_first_positional_at(&tokens).map(|(i, s)| (i, s.to_string()));
454                let actual = first_positional_at(&tokens, &p).map(|(i, s)| (i, s.to_string()));
455                proptest::prop_assert_eq!(actual, oracle);
456            }
457
458            /// Monotonicity: prepending a token that the policy declares as a STANDALONE flag
459            /// does not change the first positional found later. The walk consumes a standalone
460            /// in exactly one step (`i += 1`), so the rest of the scan is identical; the
461            /// property locks that "additive, not destructive" behavior in. The prepended flag
462            /// is taken from the SAME generated standalone list so we are asserting on real
463            /// acceptance, not on unknown-flag bailouts.
464            #[test]
465            fn prepending_a_known_standalone_flag_does_not_change_the_first_positional(
466                standalone in proptest::collection::vec(FLAG_RE, 1..4),
467                tail in proptest::collection::vec(NON_FLAG_RE, 0..5),
468            ) {
469                let prefix_token = standalone[0].clone();
470                let mut base = vec!["cmd".to_string()];
471                base.extend(tail.clone());
472                let base_tokens = toks_owned(&base);
473                let p = policy(
474                    &standalone.iter().map(String::as_str).collect::<Vec<_>>(),
475                    &[],
476                    None,
477                );
478                let before = first_positional(&base_tokens, &p).map(|s| s.to_string());
479
480                let mut prefixed = vec!["cmd".to_string(), prefix_token];
481                prefixed.extend(tail);
482                let prefixed_tokens = toks_owned(&prefixed);
483                let after = first_positional(&prefixed_tokens, &p).map(|s| s.to_string());
484
485                proptest::prop_assert_eq!(after, before);
486            }
487        }
488    }
489}
490
491#[cfg(test)]
492mod flag_given_tests {
493    use super::*;
494    use proptest::prelude::*;
495
496    fn jj_like(min_positional: Option<usize>) -> OwnedPolicy {
497        OwnedPolicy {
498            standalone: vec!["--quiet".into(), "-a".into(), "-k".into()],
499            valued: vec!["--message".into(), "--revision".into(), "-m".into(), "-r".into()],
500            bare: true,
501            max_positional: None,
502            min_positional,
503            tolerance: FlagTolerance::strict(),
504            passthrough: None,
505        }
506    }
507
508    fn toks(words: &[&str]) -> Vec<Token> {
509        std::iter::once("cmd").chain(words.iter().copied()).map(Token::from_test).collect()
510    }
511
512    fn given(words: &[&str]) -> bool {
513        flag_given(&toks(words), &jj_like(None), &["--message".to_string(), "-m".to_string()])
514    }
515
516    #[test]
517    fn a_flag_is_given_in_each_of_its_spellings() {
518        for words in [&["-m", "x"][..], &["-mx"], &["--message", "x"], &["--message=x"], &["-km", "x"], &["-r", "@", "-m", "x"]] {
519            assert!(given(words), "{words:?}");
520        }
521    }
522
523    #[test]
524    fn a_flag_that_only_looks_given_is_not() {
525        for words in [&[][..], &["-rm"], &["-r", "m"], &["--", "-m", "x"], &["--revision=-m"], &["--revision", "m"], &["m"]] {
526            assert!(!given(words), "{words:?}");
527        }
528    }
529
530    #[test]
531    fn a_required_word_matches_whole() {
532        let mut words = jj_like(None);
533        words.tolerance.single_dash_words = true;
534        let want = |w: &str| vec![w.to_string()];
535        assert!(flag_given(&toks(&["-statistics"]), &words, &want("-statistics")));
536        assert!(!flag_given(&toks(&["-statsonly"]), &words, &want("-s")));
537        assert!(flag_given(&toks(&["-", "bash"]), &jj_like(None), &want("-")));
538        assert!(!flag_given(&toks(&["--", "-"]), &jj_like(None), &want("-")));
539    }
540
541    #[test]
542    fn min_positional_counts_operands_not_flag_values() {
543        let p = jj_like(Some(1));
544        assert!(!check_owned(&toks(&["-m", "x"]), &p));
545        assert!(!check_owned(&toks(&["-m", "x", "-r", "src/a"]), &p));
546        assert!(check_owned(&toks(&["-m", "x", "src/a"]), &p));
547        assert!(check_owned(&toks(&["-m", "x", "--", "src/a"]), &p));
548        assert!(check_owned(&toks(&["-m", "x"]), &jj_like(None)));
549    }
550
551    #[test]
552    fn min_positional_is_named_in_the_reference() {
553        assert!(jj_like(Some(1)).flag_summary().ends_with("At least 1 positional argument"));
554        assert!(jj_like(Some(2)).flag_summary().ends_with("At least 2 positional arguments"));
555        assert!(!jj_like(None).flag_summary().contains("positional argument"));
556    }
557
558    fn demo(sub_fields: &str) -> Result<Vec<crate::registry::CommandSpec>, String> {
559        crate::registry::load_toml(&format!("[[command]]\nname = \"demo\"\n[[command.sub]]\nname = \"split\"\n{sub_fields}\n"), "test")
560    }
561
562    #[test]
563    fn min_positional_dispatches_through_a_loaded_definition() {
564        let specs = demo("level = \"SafeWrite\"\nrequire_any = [\"-m\"]\nmin_positional = 1\nvalued = [\"-m\", \"-r\"]").expect("loads");
565        let verdict = |words: &[&str]| crate::registry::dispatch_spec(&toks(words), &specs[0]);
566        assert_eq!(verdict(&["split", "-m", "x", "a"]), crate::verdict::Verdict::Allowed(crate::verdict::SafetyLevel::SafeWrite));
567        assert_eq!(verdict(&["split", "-m", "x"]), crate::verdict::Verdict::Denied);
568        assert_eq!(verdict(&["split", "-m", "x", "-r", "a"]), crate::verdict::Verdict::Denied);
569        assert_eq!(verdict(&["split", "a"]), crate::verdict::Verdict::Denied);
570    }
571
572    #[test]
573    fn min_positional_is_refused_where_nothing_would_count_operands() {
574        for fields in [
575            "min_positional = 1\nallow_all = true",
576            "min_positional = 1\nfirst_arg = [\"x\"]",
577            "min_positional = 1\nhandler = \"demo\"",
578            "level = \"SafeWrite\"\nmin_positional = 2\nmax_positional = 1",
579        ] {
580            let err = demo(fields).err().unwrap_or_else(|| panic!("{fields:?} loaded"));
581            assert!(err.contains("min_positional"), "{fields:?}: {err}");
582        }
583    }
584
585    #[derive(Debug, Clone)]
586    enum Unit {
587        Standalone(&'static str),
588        Valued(&'static str, &'static str),
589        Glued(&'static str),
590        Operand(&'static str),
591        Wanted(Vec<&'static str>),
592        End,
593    }
594
595    fn unit() -> impl Strategy<Value = Unit> {
596        let value = prop::sample::select(vec!["m", "x", "mx", "@-"]);
597        prop_oneof![
598            prop::sample::select(vec!["-a", "-k", "-ak", "--quiet"]).prop_map(Unit::Standalone),
599            (prop::sample::select(vec!["-r", "--revision"]), value.clone()).prop_map(|(f, v)| Unit::Valued(f, v)),
600            prop::sample::select(vec!["-rm", "-rx", "-arm", "--revision=m", "--revision=-m"]).prop_map(Unit::Glued),
601            value.prop_map(Unit::Operand),
602            prop::sample::select(vec![vec!["-m", "x"], vec!["-mx"], vec!["-am", "x"], vec!["--message", "m"], vec!["--message=m"]])
603                .prop_map(Unit::Wanted),
604            Just(Unit::End),
605        ]
606    }
607
608    proptest! {
609        #[test]
610        fn flag_given_matches_a_reading_unit_by_unit(units in prop::collection::vec(unit(), 0..8)) {
611            let mut words = Vec::new();
612            let mut expected = false;
613            let mut ended = false;
614            for u in &units {
615                match u {
616                    Unit::Standalone(f) | Unit::Glued(f) | Unit::Operand(f) => words.push(*f),
617                    Unit::Valued(f, v) => words.extend([*f, *v]),
618                    Unit::Wanted(w) => {
619                        expected |= !ended;
620                        words.extend(w.iter().copied());
621                    }
622                    Unit::End => {
623                        ended = true;
624                        words.push("--");
625                    }
626                }
627            }
628            prop_assert_eq!(given(&words), expected, "{:?}", words);
629        }
630    }
631}
632
633#[cfg(test)]
634mod passthrough_tests {
635    use super::*;
636    use crate::policy::FlagTolerance;
637    use proptest::prelude::*;
638
639    fn spec() -> OwnedPolicy {
640        let inner = |standalone: &[&str], valued: &[&str]| OwnedPolicy {
641            standalone: standalone.iter().map(|s| s.to_string()).collect(),
642            valued: valued.iter().map(|s| s.to_string()).collect(),
643            bare: false,
644            max_positional: Some(0),
645            min_positional: None,
646            tolerance: FlagTolerance::strict(),
647            passthrough: None,
648        };
649        let mut outer = inner(&["--all", "--check", "-q"], &["-p"]);
650        outer.bare = true;
651        outer.passthrough = Some(Box::new(PassthroughSpec {
652            policy: inner(&["--check", "--quiet", "-l"], &["--edition", "--color"]),
653            require_any: vec!["--check".to_string()],
654            level: SafetyLevel::SafeRead,
655        }));
656        outer
657    }
658
659    fn verdict(words: &[String]) -> Verdict {
660        let tokens: Vec<Token> = words.iter().cloned().map(Token::from_raw).collect();
661        check_with_passthrough(&tokens, &spec(), SafetyLevel::SafeWrite)
662    }
663
664    fn verdict_strs(words: &[&str]) -> Verdict {
665        let owned: Vec<String> = words.iter().map(|s| (*s).to_string()).collect();
666        verdict(&owned)
667    }
668
669    /// One whole unit of the passthrough grammar: a standalone flag or a valued flag with its value.
670    fn allowed_unit() -> impl Strategy<Value = Vec<&'static str>> {
671        prop_oneof![
672            prop::sample::select(vec!["--quiet", "-l", "--check"]).prop_map(|f| vec![f]),
673            prop::sample::select(vec!["--edition", "--color"])
674                .prop_flat_map(|f| { prop::sample::select(vec!["2024", "never", "always"]).prop_map(move |v| vec![f, v]) }),
675        ]
676    }
677
678    /// A token the passthrough lists do not hold: an unknown flag, a path or a bare word.
679    fn outsider() -> impl Strategy<Value = String> {
680        prop_oneof![
681            "--[a-z]{3,8}".prop_filter("not a listed flag", |f| !["--check", "--quiet", "--edition", "--color"].contains(&f.as_str())),
682            "-[a-km-z]{1,3}",
683            "[a-z]{1,6}(\\.rs)?",
684            "(/|~/)[a-z]{1,6}",
685            prop::sample::select(vec![
686                "--emit".to_string(),
687                "--backup".to_string(),
688                "--config=emit_mode=files".to_string(),
689                "--print-config".to_string(),
690            ]),
691        ]
692    }
693
694    fn assemble(units: &[Vec<&str>], outsider_at: Option<(usize, String)>) -> Vec<String> {
695        let mut words: Vec<String> = ["cmd", "--all", "--"].iter().map(|s| s.to_string()).collect();
696        words.push("--check".to_string());
697        for (i, unit) in units.iter().enumerate() {
698            if let Some((at, word)) = &outsider_at
699                && *at == i
700            {
701                words.push(word.clone());
702            }
703            words.extend(unit.iter().map(|s| s.to_string()));
704        }
705        if let Some((at, word)) = outsider_at
706            && at >= units.len()
707        {
708            words.push(word);
709        }
710        words
711    }
712
713    proptest! {
714        /// Never Allowed when the tail holds a token outside the passthrough lists, wherever it sits.
715        #[test]
716        fn a_tail_token_outside_the_passthrough_lists_is_never_allowed(
717            units in prop::collection::vec(allowed_unit(), 0..5),
718            at in 0usize..6,
719            word in outsider(),
720        ) {
721            let words = assemble(&units, Some((at, word)));
722            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
723        }
724
725        /// The same tails without the outsider are approved at the passthrough's level, so the
726        /// property above cannot pass by denying everything.
727        #[test]
728        fn a_tail_of_listed_flags_with_the_guard_is_allowed_at_the_passthrough_level(
729            units in prop::collection::vec(allowed_unit(), 0..5),
730        ) {
731            let words = assemble(&units, None);
732            prop_assert_eq!(verdict(&words), Verdict::Allowed(SafetyLevel::SafeRead), "{:?}", words);
733        }
734
735        /// A valued flag at the end of the tail with no value is never Allowed.
736        #[test]
737        fn a_valued_flag_with_no_value_in_the_tail_is_never_allowed(
738            units in prop::collection::vec(allowed_unit(), 0..4),
739            flag in prop::sample::select(vec!["--edition", "--color"]),
740        ) {
741            let mut words = assemble(&units, None);
742            words.push(flag.to_string());
743            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
744        }
745
746        /// A second `--` anywhere in the tail is never Allowed.
747        #[test]
748        fn a_second_separator_is_never_allowed(units in prop::collection::vec(allowed_unit(), 0..4)) {
749            let mut words = assemble(&units, None);
750            words.push("--".to_string());
751            prop_assert_eq!(verdict(&words), Verdict::Denied, "{:?}", words);
752        }
753    }
754
755    #[test]
756    fn an_unvalued_valued_flag_before_the_separator_is_denied() {
757        assert_eq!(verdict_strs(&["cmd", "-p", "--", "--check"]), Verdict::Denied);
758        assert_eq!(verdict_strs(&["cmd", "-qp", "--", "--check"]), Verdict::Denied);
759        assert_eq!(verdict_strs(&["cmd", "-p"]), Verdict::Denied);
760        assert_eq!(verdict_strs(&["cmd", "-p", "xp", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
761        assert_eq!(verdict_strs(&["cmd", "-qp", "xp", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
762        assert_eq!(verdict_strs(&["cmd", "-qpx", "--", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
763        assert_eq!(verdict_strs(&["cmd", "--check", "--", "-l"]), Verdict::Allowed(SafetyLevel::SafeRead));
764        assert_eq!(verdict_strs(&["cmd", "--check"]), Verdict::Allowed(SafetyLevel::SafeRead));
765        assert_eq!(verdict_strs(&["cmd", "--all"]), Verdict::Allowed(SafetyLevel::SafeWrite));
766    }
767}