Skip to main content

vault_core/
permex.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Permission expressions — a small boolean language over vault entries.
4//!
5//! Replaces the flat list of `(scope_type, scope_value, permission)` rows, which
6//! could only ever mean "any of these matches". Admins can now express what they
7//! actually want:
8//!
9//! ```text
10//! project:Alpha AND NOT category:secret
11//! (project:web OR project:api) AND env:production
12//! tag:shared OR type:certificate
13//! ```
14//!
15//! # Grammar
16//!
17//! ```text
18//! expr      := or_expr
19//! or_expr   := and_expr (OR and_expr)*
20//! and_expr  := not_expr (AND not_expr)*
21//! not_expr  := NOT not_expr | primary
22//! primary   := '(' expr ')' | predicate
23//! predicate := field ':' glob
24//! ```
25//!
26//! Precedence is `NOT` > `AND` > `OR`; parentheses override. Operators are
27//! case-insensitive and `&&` / `||` / `!` are accepted as aliases. Adjacency is
28//! **not** implicit AND — an operator is always required, so an expression can
29//! never quietly mean something other than it reads.
30//!
31//! # Fields
32//!
33//! | Field       | Matches against                                    |
34//! |-------------|----------------------------------------------------|
35//! | `vault`     | everything (the value is ignored)                  |
36//! | `project`   | the entry's project ids **and** their display names |
37//! | `category`  | any of the entry's categories                      |
38//! | `tag`       | any of the entry's tags                            |
39//! | `env`       | the entry's environment                            |
40//! | `type`      | the entry's secret type (default `api_key`)        |
41//!
42//! # Two rules worth knowing
43//!
44//! **`field:*` is unconditional.** It means "no constraint on this field",
45//! not "has at least one value matching `*`". Without that, `project:*` would
46//! match unfiled entries (every entry carries the `Universal` catch-all) while
47//! `category:*` would not (an entry can have no categories at all) — the same
48//! wildcard behaving differently depending on the field.
49//!
50//! **A specific project grant is never satisfied by `Universal`.** Every entry
51//! belongs to it, so matching it would silently turn any project grant into a
52//! vault-wide one.
53
54use crate::users::glob_matches;
55use std::fmt;
56
57/// The catch-all project every entry carries.
58const UNIVERSAL: &str = "Universal";
59
60// ── AST ───────────────────────────────────────────────────────────────────────
61
62/// Which part of an entry a predicate tests.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum Field {
65    Vault,
66    Project,
67    Category,
68    Tag,
69    Env,
70    Type,
71}
72
73impl Field {
74    fn parse(s: &str) -> Option<Field> {
75        match s.to_ascii_lowercase().as_str() {
76            "vault" => Some(Field::Vault),
77            "project" | "proj" => Some(Field::Project),
78            "category" | "cat" => Some(Field::Category),
79            "tag" => Some(Field::Tag),
80            "env" | "environment" => Some(Field::Env),
81            "type" | "secrettype" => Some(Field::Type),
82            _ => None,
83        }
84    }
85
86    fn name(self) -> &'static str {
87        match self {
88            Field::Vault => "vault",
89            Field::Project => "project",
90            Field::Category => "category",
91            Field::Tag => "tag",
92            Field::Env => "env",
93            Field::Type => "type",
94        }
95    }
96}
97
98/// A parsed permission expression.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Expr {
101    Pred { field: Field, glob: String },
102    And(Box<Expr>, Box<Expr>),
103    Or(Box<Expr>, Box<Expr>),
104    Not(Box<Expr>),
105}
106
107impl fmt::Display for Expr {
108    /// Renders back to source form. Round-trips through [`parse`].
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        match self {
111            Expr::Pred { field, glob } => {
112                let needs_quotes = glob.is_empty()
113                    || glob
114                        .chars()
115                        .any(|c| c.is_whitespace() || c == '(' || c == ')' || c == '"');
116                if needs_quotes {
117                    write!(f, "{}:\"{}\"", field.name(), glob.replace('"', "\\\""))
118                } else {
119                    write!(f, "{}:{}", field.name(), glob)
120                }
121            }
122            Expr::And(a, b) => write!(f, "({a} AND {b})"),
123            Expr::Or(a, b) => write!(f, "({a} OR {b})"),
124            Expr::Not(a) => write!(f, "NOT {a}"),
125        }
126    }
127}
128
129// ── Entry view ────────────────────────────────────────────────────────────────
130
131/// The parts of a vault entry an expression can test.
132///
133/// Borrowed rather than owned: evaluation runs once per entry per request, and
134/// the source JSON already outlives it.
135#[derive(Debug, Default, Clone)]
136pub struct EntryView<'a> {
137    pub categories: Vec<&'a str>,
138    pub project_ids: Vec<&'a str>,
139    /// Display names for `project_ids`, so rules can be written against either.
140    pub project_names: Vec<String>,
141    pub tags: Vec<&'a str>,
142    pub environment: Option<&'a str>,
143    pub secret_type: Option<&'a str>,
144}
145
146impl<'a> EntryView<'a> {
147    /// Extracts the testable fields from a raw vault entry.
148    ///
149    /// `project_names` maps project id → display name; ids without a mapping
150    /// fall back to the id itself.
151    pub fn from_entry(
152        entry: &'a serde_json::Value,
153        project_names: &std::collections::HashMap<String, String>,
154    ) -> EntryView<'a> {
155        let strs = |key: &str| -> Vec<&'a str> {
156            entry
157                .get(key)
158                .and_then(|v| v.as_array())
159                .map(|a| a.iter().filter_map(|v| v.as_str()).collect())
160                .unwrap_or_default()
161        };
162        let project_ids = strs("projectIds");
163        let names = project_ids
164            .iter()
165            .map(|id| {
166                project_names
167                    .get(*id)
168                    .cloned()
169                    .unwrap_or_else(|| (*id).to_string())
170            })
171            .collect();
172        EntryView {
173            categories: strs("categories"),
174            project_ids,
175            project_names: names,
176            tags: strs("tags"),
177            environment: entry.get("environment").and_then(|v| v.as_str()),
178            secret_type: entry.get("secretType").and_then(|v| v.as_str()),
179        }
180    }
181}
182
183// ── Evaluation ────────────────────────────────────────────────────────────────
184
185/// Does `expr` grant access to `entry`?
186pub fn eval(expr: &Expr, entry: &EntryView<'_>) -> bool {
187    match expr {
188        Expr::And(a, b) => eval(a, entry) && eval(b, entry),
189        Expr::Or(a, b) => eval(a, entry) || eval(b, entry),
190        Expr::Not(a) => !eval(a, entry),
191        Expr::Pred { field, glob } => eval_pred(*field, glob, entry),
192    }
193}
194
195fn eval_pred(field: Field, glob: &str, e: &EntryView<'_>) -> bool {
196    // `field:*` places no constraint on the field — see the module docs.
197    let wildcard = glob == "*";
198    match field {
199        Field::Vault => true,
200        Field::Category => wildcard || e.categories.iter().any(|c| glob_matches(glob, c)),
201        Field::Tag => wildcard || e.tags.iter().any(|t| glob_matches(glob, t)),
202        Field::Env => wildcard || e.environment.is_some_and(|v| glob_matches(glob, v)),
203        // Entries without an explicit type are api_key by convention.
204        Field::Type => wildcard || glob_matches(glob, e.secret_type.unwrap_or("api_key")),
205        Field::Project => {
206            if wildcard {
207                return true;
208            }
209            // Skip the catch-all: every entry carries it, so allowing it to
210            // match would promote any project grant to vault-wide.
211            e.project_ids.iter().enumerate().any(|(i, id)| {
212                if *id == UNIVERSAL {
213                    return false;
214                }
215                glob_matches(glob, id)
216                    || e.project_names
217                        .get(i)
218                        .is_some_and(|n| glob_matches(glob, n))
219            })
220        }
221    }
222}
223
224// ── Containment ───────────────────────────────────────────────────────────────
225
226/// Does everything `new` grants also fall inside what `grantor` grants?
227///
228/// Used to stop a delegate conferring more than they hold. **Sound, not complete**: it
229/// answers `true` only when containment follows from the shape of the two expressions
230/// (equal, a narrowing `AND`, every branch of an `OR`, a wildcard or matching glob on the
231/// same field), and `false` when unsure, so a legitimate grant it cannot prove is refused
232/// and the owner makes it instead. It never answers `true` wrongly.
233pub fn covers(grantor: &Expr, new: &Expr) -> bool {
234    if grantor == new {
235        return true;
236    }
237    match (grantor, new) {
238        // a AND b is inside a, and inside b.
239        (g, Expr::And(a, b)) => covers(g, a) || covers(g, b),
240        // a OR b is inside g only if both halves are.
241        (g, Expr::Or(a, b)) => covers(g, a) && covers(g, b),
242        (Expr::Or(x, y), n) => covers(x, n) || covers(y, n),
243        (Expr::And(x, y), n) => covers(x, n) && covers(y, n),
244        (
245            Expr::Pred {
246                field: Field::Vault,
247                ..
248            },
249            _,
250        ) => true,
251        (
252            Expr::Pred {
253                field: gf,
254                glob: gg,
255            },
256            Expr::Pred {
257                field: nf,
258                glob: ng,
259            },
260        ) => gf == nf && (gg == "*" || gg == ng || (!ng.contains('*') && glob_matches(gg, ng))),
261        _ => false,
262    }
263}
264
265// ── Lexer ─────────────────────────────────────────────────────────────────────
266
267#[derive(Debug, Clone, PartialEq, Eq)]
268enum Tok {
269    Pred(Field, String),
270    And,
271    Or,
272    Not,
273    LParen,
274    RParen,
275}
276
277fn lex(src: &str) -> Result<Vec<Tok>, String> {
278    let chars: Vec<char> = src.chars().collect();
279    let mut out = Vec::new();
280    let mut i = 0usize;
281
282    while i < chars.len() {
283        let c = chars[i];
284        if c.is_whitespace() {
285            i += 1;
286            continue;
287        }
288
289        match c {
290            '(' => {
291                out.push(Tok::LParen);
292                i += 1;
293                continue;
294            }
295            ')' => {
296                out.push(Tok::RParen);
297                i += 1;
298                continue;
299            }
300            '!' => {
301                out.push(Tok::Not);
302                i += 1;
303                continue;
304            }
305            '&' => {
306                i += if i + 1 < chars.len() && chars[i + 1] == '&' {
307                    2
308                } else {
309                    1
310                };
311                out.push(Tok::And);
312                continue;
313            }
314            '|' => {
315                i += if i + 1 < chars.len() && chars[i + 1] == '|' {
316                    2
317                } else {
318                    1
319                };
320                out.push(Tok::Or);
321                continue;
322            }
323            _ => {}
324        }
325
326        // A bare word: either an operator keyword or the field half of a predicate.
327        let start = i;
328        while i < chars.len()
329            && !chars[i].is_whitespace()
330            && chars[i] != '('
331            && chars[i] != ')'
332            && chars[i] != ':'
333        {
334            i += 1;
335        }
336        let word: String = chars[start..i].iter().collect();
337        if word.is_empty() {
338            return Err(format!("unexpected character '{c}' at position {start}"));
339        }
340
341        // Not followed by ':' → it must be an operator.
342        if i >= chars.len() || chars[i] != ':' {
343            match word.to_ascii_uppercase().as_str() {
344                "AND" => out.push(Tok::And),
345                "OR" => out.push(Tok::Or),
346                "NOT" => out.push(Tok::Not),
347                _ => {
348                    return Err(format!(
349                        "expected AND, OR, NOT or a `field:value` term, found '{word}'"
350                    ))
351                }
352            }
353            continue;
354        }
355
356        i += 1; // consume ':'
357        let Some(field) = Field::parse(&word) else {
358            return Err(format!(
359                "unknown field '{word}' — expected one of vault, project, category, tag, env, type"
360            ));
361        };
362
363        // Value: quoted (may contain spaces) or bare up to whitespace/paren.
364        let value = if i < chars.len() && chars[i] == '"' {
365            i += 1;
366            let mut v = String::new();
367            loop {
368                if i >= chars.len() {
369                    return Err("unterminated quoted value".to_string());
370                }
371                match chars[i] {
372                    '\\' if i + 1 < chars.len() => {
373                        v.push(chars[i + 1]);
374                        i += 2;
375                    }
376                    '"' => {
377                        i += 1;
378                        break;
379                    }
380                    ch => {
381                        v.push(ch);
382                        i += 1;
383                    }
384                }
385            }
386            v
387        } else {
388            let vs = i;
389            while i < chars.len() && !chars[i].is_whitespace() && chars[i] != '(' && chars[i] != ')'
390            {
391                i += 1;
392            }
393            chars[vs..i].iter().collect()
394        };
395
396        if value.is_empty() {
397            return Err(format!(
398                "field '{word}' has no value — write {word}:* to match everything"
399            ));
400        }
401        out.push(Tok::Pred(field, value));
402    }
403
404    Ok(out)
405}
406
407/// The longest expression accepted, in tokens (a predicate, operator or parenthesis each count one).
408pub const MAX_TOKENS: usize = 256;
409
410// ── Parser ────────────────────────────────────────────────────────────────────
411
412struct Parser {
413    toks: Vec<Tok>,
414    pos: usize,
415}
416
417impl Parser {
418    fn peek(&self) -> Option<&Tok> {
419        self.toks.get(self.pos)
420    }
421    fn next(&mut self) -> Option<Tok> {
422        let t = self.toks.get(self.pos).cloned();
423        self.pos += 1;
424        t
425    }
426
427    fn parse_or(&mut self) -> Result<Expr, String> {
428        let mut lhs = self.parse_and()?;
429        while matches!(self.peek(), Some(Tok::Or)) {
430            self.next();
431            let rhs = self.parse_and()?;
432            lhs = Expr::Or(Box::new(lhs), Box::new(rhs));
433        }
434        Ok(lhs)
435    }
436
437    fn parse_and(&mut self) -> Result<Expr, String> {
438        let mut lhs = self.parse_not()?;
439        while matches!(self.peek(), Some(Tok::And)) {
440            self.next();
441            let rhs = self.parse_not()?;
442            lhs = Expr::And(Box::new(lhs), Box::new(rhs));
443        }
444        Ok(lhs)
445    }
446
447    fn parse_not(&mut self) -> Result<Expr, String> {
448        if matches!(self.peek(), Some(Tok::Not)) {
449            self.next();
450            return Ok(Expr::Not(Box::new(self.parse_not()?)));
451        }
452        self.parse_primary()
453    }
454
455    fn parse_primary(&mut self) -> Result<Expr, String> {
456        match self.next() {
457            Some(Tok::Pred(field, glob)) => Ok(Expr::Pred { field, glob }),
458            Some(Tok::LParen) => {
459                let inner = self.parse_or()?;
460                match self.next() {
461                    Some(Tok::RParen) => Ok(inner),
462                    _ => Err("missing closing ')'".to_string()),
463                }
464            }
465            Some(Tok::RParen) => Err("unexpected ')'".to_string()),
466            Some(Tok::And) | Some(Tok::Or) => Err("expression begins with an operator".to_string()),
467            Some(Tok::Not) => unreachable!("handled in parse_not"),
468            None => Err("unexpected end of expression".to_string()),
469        }
470    }
471}
472
473/// Parses a permission expression.
474///
475/// Returns `Err` with a human-readable reason for anything malformed. Callers
476/// must treat a parse failure as **deny** — never as "no restriction".
477pub fn parse(src: &str) -> Result<Expr, String> {
478    let toks = lex(src)?;
479    if toks.is_empty() {
480        return Err("empty expression".to_string());
481    }
482    // The parser, the evaluator and `Drop` all recurse once per nesting level or chained operator,
483    // and an expression arrives over the network. Bounding the token count bounds the stack.
484    if toks.len() > MAX_TOKENS {
485        return Err(format!(
486            "expression is too long ({} tokens; the limit is {MAX_TOKENS})",
487            toks.len()
488        ));
489    }
490    let mut p = Parser { toks, pos: 0 };
491    let expr = p.parse_or()?;
492    if p.pos != p.toks.len() {
493        return Err("trailing input after the end of the expression".to_string());
494    }
495    Ok(expr)
496}
497
498/// Convenience: parse and evaluate, treating a malformed expression as deny.
499pub fn eval_str(src: &str, entry: &EntryView<'_>) -> bool {
500    parse(src).map(|e| eval(&e, entry)).unwrap_or(false)
501}
502
503// ── Compiling legacy permission rows ──────────────────────────────────────────
504
505/// Builds the expression equivalent to a set of legacy `(scope_type, scope_value)`
506/// rows, which always meant "any of these matches".
507///
508/// Returns `None` when there are no rows — the caller must treat that as
509/// "no grant", not "no restriction".
510pub fn compile_scopes<'a, I>(scopes: I) -> Option<Expr>
511where
512    I: IntoIterator<Item = (&'a str, &'a str)>,
513{
514    let mut acc: Option<Expr> = None;
515    for (scope_type, scope_value) in scopes {
516        let field = match Field::parse(scope_type) {
517            Some(f) => f,
518            None => continue, // unknown legacy scope type: ignore rather than over-grant
519        };
520        let pred = Expr::Pred {
521            field,
522            glob: scope_value.to_string(),
523        };
524        acc = Some(match acc {
525            None => pred,
526            Some(prev) => Expr::Or(Box::new(prev), Box::new(pred)),
527        });
528    }
529    acc
530}
531
532/// Combines a class expression with an individual one.
533///
534/// Both present → **AND**: a class restriction cannot be undone by an individual
535/// grant, which is what makes classes an actual boundary. Exactly one present →
536/// that one. Neither → `None`, meaning no grant at all.
537///
538/// The AND is why "neither" must be `None` rather than a vacuous truth: treating
539/// an absent expression as `true` would make a user with no permissions
540/// whatsoever evaluate to `true AND true` and see everything.
541//
542// (This block documents `combine`, below. It sat above `any_of` for several
543// phases, so `any_of` appeared to be the function that ANDs — it is not.)
544/// ORs two optional expressions, used for "write implies read".
545pub fn any_of(a: Option<Expr>, b: Option<Expr>) -> Option<Expr> {
546    match (a, b) {
547        (Some(x), Some(y)) => Some(Expr::Or(Box::new(x), Box::new(y))),
548        (Some(x), None) | (None, Some(x)) => Some(x),
549        (None, None) => None,
550    }
551}
552
553pub fn combine(class: Option<Expr>, individual: Option<Expr>) -> Option<Expr> {
554    match (class, individual) {
555        (Some(c), Some(i)) => Some(Expr::And(Box::new(c), Box::new(i))),
556        (Some(c), None) => Some(c),
557        (None, Some(i)) => Some(i),
558        (None, None) => None,
559    }
560}
561
562/// Rewrites a permission expression so **every** top-level alternative must
563/// match, instead of any one of them.
564///
565/// This is what "strict write scoping" means in a codebase where scopes became
566/// expressions. `compile_scopes` joins a subject's scopes with `Or`, so a user
567/// scoped to two projects may write anything in *either*. Under strict mode an
568/// entry must satisfy all of them — in practice, be in both.
569///
570/// Only the top-level `Or` chain is rewritten. Nested groups an author wrote by
571/// hand are left alone: `(a OR b) AND c` was deliberate, and silently turning
572/// its inner alternation into a conjunction would change a rule its author
573/// already expressed precisely. Strictness is about the implicit OR that
574/// scope-joining introduced, not about second-guessing explicit logic.
575///
576/// Strict mode can only ever *narrow* what is permitted. That direction matters:
577/// a bug here should lock someone out, not let them through.
578pub fn require_all(expr: Expr) -> Expr {
579    match expr {
580        Expr::Or(a, b) => Expr::And(Box::new(require_all(*a)), Box::new(require_all(*b))),
581        other => other,
582    }
583}
584
585// ── Tests ─────────────────────────────────────────────────────────────────────
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use serde_json::json;
591    use std::collections::HashMap;
592
593    fn names(pairs: &[(&str, &str)]) -> HashMap<String, String> {
594        pairs
595            .iter()
596            .map(|(a, b)| (a.to_string(), b.to_string()))
597            .collect()
598    }
599
600    fn view<'a>(e: &'a serde_json::Value, pn: &HashMap<String, String>) -> EntryView<'a> {
601        EntryView::from_entry(e, pn)
602    }
603
604    fn entry() -> serde_json::Value {
605        json!({
606            "provider": "X",
607            "categories": ["dev", "shared"],
608            "projectIds": ["Universal", "p1"],
609            "tags": ["team-a"],
610            "environment": "production",
611            "secretType": "api_key",
612        })
613    }
614
615    #[test]
616    fn matches_the_shared_typescript_parity_fixture() {
617        let fixture: serde_json::Value =
618            serde_json::from_str(include_str!("../../tests/fixtures/parity/permex.json")).unwrap();
619        let projects = fixture["projects"]
620            .as_array()
621            .unwrap()
622            .iter()
623            .filter_map(|p| {
624                Some((
625                    p["id"].as_str()?.to_string(),
626                    p["name"].as_str()?.to_string(),
627                ))
628            })
629            .collect::<HashMap<_, _>>();
630
631        for case in fixture["cases"].as_array().unwrap() {
632            let parse_optional = |key: &str| {
633                case[key]
634                    .as_str()
635                    .filter(|src| !src.is_empty())
636                    .map(parse)
637                    .transpose()
638                    .unwrap_or_else(|err| panic!("{}: {err}", case["name"]))
639            };
640            let mut expr = combine(parse_optional("class"), parse_optional("individual"));
641            if case["strict"].as_bool() == Some(true) {
642                expr = expr.map(require_all);
643            }
644            for (entry, expected) in fixture["entries"]
645                .as_array()
646                .unwrap()
647                .iter()
648                .zip(case["matches"].as_array().unwrap())
649            {
650                assert_eq!(
651                    expr.as_ref()
652                        .is_some_and(|e| eval(e, &EntryView::from_entry(entry, &projects))),
653                    expected.as_bool().unwrap(),
654                    "{}: {}",
655                    case["name"],
656                    entry["id"],
657                );
658            }
659        }
660    }
661
662    // ── Parsing ───────────────────────────────────────────────────────────────
663
664    #[test]
665    fn precedence_is_not_then_and_then_or() {
666        // a OR b AND c  ==  a OR (b AND c)
667        let e = parse("category:a OR category:b AND category:c").unwrap();
668        assert_eq!(e.to_string(), "(category:a OR (category:b AND category:c))");
669    }
670
671    #[test]
672    fn not_binds_tighter_than_and() {
673        let e = parse("NOT category:a AND category:b").unwrap();
674        assert_eq!(e.to_string(), "(NOT category:a AND category:b)");
675    }
676
677    #[test]
678    fn parentheses_override_precedence() {
679        let e = parse("(category:a OR category:b) AND category:c").unwrap();
680        assert_eq!(e.to_string(), "((category:a OR category:b) AND category:c)");
681    }
682
683    #[test]
684    fn symbolic_operators_are_aliases() {
685        assert_eq!(
686            parse("category:a && category:b").unwrap(),
687            parse("category:a AND category:b").unwrap()
688        );
689        assert_eq!(
690            parse("category:a || category:b").unwrap(),
691            parse("category:a OR category:b").unwrap()
692        );
693        assert_eq!(
694            parse("!category:a").unwrap(),
695            parse("NOT category:a").unwrap()
696        );
697    }
698
699    #[test]
700    fn operators_are_case_insensitive() {
701        assert_eq!(
702            parse("category:a and category:b").unwrap(),
703            parse("category:a AND category:b").unwrap()
704        );
705    }
706
707    #[test]
708    fn quoted_values_may_contain_spaces() {
709        let e = parse(r#"project:"My Project""#).unwrap();
710        assert_eq!(
711            e,
712            Expr::Pred {
713                field: Field::Project,
714                glob: "My Project".into()
715            }
716        );
717    }
718
719    #[test]
720    fn field_aliases_resolve() {
721        assert_eq!(parse("proj:a").unwrap(), parse("project:a").unwrap());
722        assert_eq!(parse("cat:a").unwrap(), parse("category:a").unwrap());
723    }
724
725    #[test]
726    fn expressions_round_trip_through_display() {
727        for src in [
728            "project:a",
729            "(project:a AND NOT category:b)",
730            "((project:a OR tag:x) AND env:production)",
731        ] {
732            let once = parse(src).unwrap();
733            let twice = parse(&once.to_string()).unwrap();
734            assert_eq!(once, twice, "round-trip failed for {src}");
735        }
736    }
737
738    // ── Malformed input must fail, never silently permit ──────────────────────
739
740    #[test]
741    fn malformed_expressions_are_rejected() {
742        for bad in [
743            "",                      // empty
744            "category:",             // no value
745            "bogus:a",               // unknown field
746            "category:a AND",        // dangling operator
747            "AND category:a",        // leading operator
748            "(category:a",           // unclosed paren
749            "category:a)",           // stray close
750            "category:a category:b", // adjacency is not implicit AND
751            "just-a-word",           // not a term
752        ] {
753            assert!(parse(bad).is_err(), "expected {bad:?} to be rejected");
754        }
755    }
756
757    // Bug: a 10 KB expression (5,000 nested parentheses or chained ORs) overflowed the stack of
758    // the real server, because parse, eval and drop all recurse once per level.
759    #[test]
760    fn very_long_expressions_are_refused_not_recursed_into() {
761        let parens = format!("{}vault:*{}", "(".repeat(5_000), ")".repeat(5_000));
762        assert!(parse(&parens).unwrap_err().contains("too long"));
763        let ors = format!("{}vault:*", "vault:* OR ".repeat(5_000));
764        assert!(parse(&ors).unwrap_err().contains("too long"));
765        let nots = format!("{}vault:*", "NOT ".repeat(5_000));
766        assert!(parse(&nots).is_err());
767        let ok = format!("{}vault:*", "vault:* OR ".repeat(100));
768        assert!(parse(&ok).is_ok());
769    }
770
771    #[test]
772    fn eval_str_denies_on_malformed_input() {
773        let pn = names(&[]);
774        let e = entry();
775        assert!(
776            !eval_str("category:a AND", &view(&e, &pn)),
777            "a broken expression must deny, not permit"
778        );
779        assert!(!eval_str("", &view(&e, &pn)));
780    }
781
782    // ── Evaluation ────────────────────────────────────────────────────────────
783
784    #[test]
785    fn predicates_match_their_own_field() {
786        let pn = names(&[("p1", "Alpha")]);
787        let e = entry();
788        let v = view(&e, &pn);
789        assert!(eval_str("category:dev", &v));
790        assert!(
791            eval_str("project:Alpha", &v),
792            "project matches by display name"
793        );
794        assert!(eval_str("project:p1", &v), "project matches by id");
795        assert!(eval_str("tag:team-a", &v));
796        assert!(eval_str("env:production", &v));
797        assert!(eval_str("type:api_key", &v));
798        assert!(!eval_str("category:nope", &v));
799        assert!(!eval_str("env:staging", &v));
800    }
801
802    #[test]
803    fn globs_work_inside_predicates() {
804        let pn = names(&[("p1", "Alpha")]);
805        let e = entry();
806        assert!(eval_str("project:Al*", &view(&e, &pn)));
807        assert!(eval_str("tag:team-?", &view(&e, &pn)));
808        assert!(!eval_str("project:Be*", &view(&e, &pn)));
809    }
810
811    #[test]
812    fn boolean_combinations_evaluate() {
813        let pn = names(&[("p1", "Alpha")]);
814        let e = entry();
815        let v = view(&e, &pn);
816        assert!(eval_str("category:dev AND env:production", &v));
817        assert!(!eval_str("category:dev AND env:staging", &v));
818        assert!(eval_str("category:nope OR tag:team-a", &v));
819        assert!(eval_str("project:Alpha AND NOT category:secret", &v));
820        assert!(!eval_str("project:Alpha AND NOT category:dev", &v));
821        assert!(eval_str(
822            "(category:nope OR project:Alpha) AND env:production",
823            &v
824        ));
825    }
826
827    #[test]
828    fn untyped_entries_are_treated_as_api_key() {
829        let pn = names(&[]);
830        let e = json!({ "provider": "X", "projectIds": ["Universal"] });
831        assert!(eval_str("type:api_key", &view(&e, &pn)));
832    }
833
834    // ── The two rules that bit us before ──────────────────────────────────────
835
836    #[test]
837    fn wildcards_are_unconditional_across_every_field() {
838        let pn = names(&[]);
839        // Unfiled: no categories, no tags, no env, only the Universal project.
840        let e = json!({ "provider": "X", "projectIds": ["Universal"] });
841        let v = view(&e, &pn);
842        for src in [
843            "project:*",
844            "category:*",
845            "tag:*",
846            "env:*",
847            "type:*",
848            "vault:*",
849        ] {
850            assert!(eval_str(src, &v), "{src} must match an unfiled entry");
851        }
852    }
853
854    #[test]
855    fn a_specific_project_grant_is_never_satisfied_by_universal() {
856        let pn = names(&[]);
857        let e = json!({ "provider": "X", "projectIds": ["Universal"] });
858        assert!(
859            !eval_str("project:Universal", &view(&e, &pn)),
860            "matching the catch-all would promote any project grant to vault-wide"
861        );
862    }
863
864    // ── Legacy compilation and composition ────────────────────────────────────
865
866    #[test]
867    fn legacy_rows_compile_to_an_or_chain() {
868        let e = compile_scopes(vec![("project", "Alpha"), ("category", "dev")]).unwrap();
869        assert_eq!(e.to_string(), "(project:Alpha OR category:dev)");
870    }
871
872    #[test]
873    fn compiling_no_rows_yields_no_grant() {
874        assert!(compile_scopes(Vec::<(&str, &str)>::new()).is_none());
875    }
876
877    #[test]
878    fn unknown_legacy_scope_types_are_dropped_not_widened() {
879        // A row we cannot interpret must never become a broader grant.
880        assert!(compile_scopes(vec![("nonsense", "*")]).is_none());
881    }
882
883    #[test]
884    fn combine_ands_class_with_individual() {
885        let c = parse("project:*").unwrap();
886        let i = parse("NOT category:secret").unwrap();
887        let combined = combine(Some(c), Some(i)).unwrap();
888        assert_eq!(combined.to_string(), "(project:* AND NOT category:secret)");
889    }
890
891    #[test]
892    fn a_class_exclusion_cannot_be_undone_individually() {
893        let pn = names(&[("p1", "Alpha")]);
894        let secret =
895            json!({ "provider": "S", "categories": ["secret"], "projectIds": ["Universal", "p1"] });
896        let combined = combine(
897            Some(parse("NOT category:secret").unwrap()), // class says: never secrets
898            Some(parse("project:*").unwrap()),           // individual says: all projects
899        )
900        .unwrap();
901        assert!(
902            !eval(&combined, &view(&secret, &pn)),
903            "the class exclusion must win over the individual grant"
904        );
905    }
906
907    #[test]
908    fn no_expressions_at_all_means_no_grant() {
909        // Guards the emptiness rule: with AND composition, treating absent as
910        // `true` would give a user with no permissions full access.
911        assert!(combine(None, None).is_none());
912    }
913
914    #[test]
915    fn covers_is_sound_and_says_no_when_unsure() {
916        let p = |s: &str| parse(s).unwrap();
917        // Same, narrower by AND, a wildcard grantor, a glob that matches a literal.
918        assert!(covers(&p("type:api_key"), &p("type:api_key")));
919        assert!(covers(&p("type:api_key"), &p("type:api_key AND env:prod")));
920        assert!(covers(&p("type:*"), &p("type:ssh_key")));
921        assert!(covers(&p("project:prod-*"), &p("project:prod-api")));
922        assert!(covers(&p("type:a OR type:b"), &p("type:b")));
923        assert!(covers(&p("vault:*"), &p("tag:x OR type:y")));
924        // Wider, different field, an OR that leaks, a NOT.
925        assert!(!covers(&p("type:api_key"), &p("type:*")));
926        assert!(!covers(&p("type:api_key"), &p("env:prod")));
927        assert!(!covers(
928            &p("type:api_key"),
929            &p("type:api_key OR type:ssh_key")
930        ));
931        assert!(!covers(&p("type:api_key"), &p("NOT type:ssh_key")));
932        assert!(!covers(&p("project:prod-*"), &p("project:*")));
933    }
934}