Skip to main content

candor_classify/
policy.rs

1//! The canonical CANDOR_POLICY DSL parser (candor-spec SPEC §6.2).
2//!
3//! This is the **single** Rust implementation of the policy grammar — shared by the nightly dylint
4//! gate (`src/lib.rs`, AS-EFF-006/008/009) and the stable `candor-query` (`whatif`, and the
5//! `parsepolicy` dump the cross-impl conformance suite diffs against the JVM engine). Keeping one
6//! parser here is what makes "the gate means the same thing in every language" a fact rather than a
7//! hope: the Rust gate, the Rust pre-edit tool, and the cross-impl differential all read THIS code.
8//!
9//! Pure, stable Rust (string parsing only — no rustc types), so it lives beside the classifier.
10
11use crate::cap_from_name;
12use std::collections::BTreeSet;
13
14/// The honesty marker (SPEC §4). Denyable so `deny Unknown <scope>` forbids the *unverifiable* case.
15pub const UNKNOWN: &str = "Unknown";
16
17/// The NORMATIVE projection of a raw `unknown_why` reason onto a fixed, cross-engine reason CLASS
18/// (candor-spec REASON-SCOPED-UNKNOWN-DESIGN.md §1). Reason-scoped policies (`deny E Unknown[class]`)
19/// quantify over these classes, so the mapping MUST be identical in every engine — this mirrors the
20/// java reference `ReasonClass` (its `classify(String)` path, since rust emits raw string reasons). The
21/// class set is CLOSED (six members); a raw reason matching no pinned prefix maps to `Unresolved` —
22/// conservative: it stays in scope of any `Unknown[*]` / `Unknown[dynamic]` policy, never silently
23/// tolerated.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
25pub enum ReasonClass {
26    /// reflection / metaprogramming
27    Reflect,
28    /// unresolved virtual/dynamic dispatch, same-name ambiguity, invokedynamic
29    Dispatch,
30    /// callback / closure / function-value / async-continuation indirection
31    Indirect,
32    /// FFI / native boundary
33    Native,
34    /// generic unresolvable call/import, AND the catch-all for any unrecognized raw reason
35    Unresolved,
36    /// analysis not wired up (fixable, not a real dynamic hole): missing-config / no-tsconfig
37    Setup,
38}
39
40impl ReasonClass {
41    /// The lowercase policy-facing token (`deny E Unknown[<token>]`).
42    pub fn token(self) -> &'static str {
43        match self {
44            ReasonClass::Reflect => "reflect",
45            ReasonClass::Dispatch => "dispatch",
46            ReasonClass::Indirect => "indirect",
47            ReasonClass::Native => "native",
48            ReasonClass::Unresolved => "unresolved",
49            ReasonClass::Setup => "setup",
50        }
51    }
52
53    /// Parse a policy-facing token back to a class; `None` if it names no class.
54    pub fn from_token(t: &str) -> Option<ReasonClass> {
55        Some(match t {
56            "reflect" => ReasonClass::Reflect,
57            "dispatch" => ReasonClass::Dispatch,
58            "indirect" => ReasonClass::Indirect,
59            "native" => ReasonClass::Native,
60            "unresolved" => ReasonClass::Unresolved,
61            "setup" => ReasonClass::Setup,
62            _ => return None,
63        })
64    }
65
66    /// Map a raw `unknown_why` reason to its normative class — prefix-based (raw reasons carry a
67    /// `kind:detail` shape, e.g. `dispatch:foo::Bar`), unrecognized → `Unresolved`. Byte-identical
68    /// intent to the java `ReasonClass.classify(String)`.
69    pub fn classify(why: &str) -> ReasonClass {
70        let w = why.trim().to_ascii_lowercase();
71        if w.starts_with("reflect") || w == "dynamicmemberlookup" {
72            ReasonClass::Reflect
73        } else if w.starts_with("native") {
74            ReasonClass::Native
75        } else if w.starts_with("callback") || w.starts_with("closure") || w.starts_with("task-handoff") {
76            ReasonClass::Indirect
77        } else if w.starts_with("dispatch") || w.starts_with("indy") || w.starts_with("ambiguous") {
78            ReasonClass::Dispatch
79        } else if w.starts_with("missing-config") || w.starts_with("no-tsconfig") || w.starts_with("no-node_modules") {
80            ReasonClass::Setup
81        } else {
82            ReasonClass::Unresolved
83        }
84    }
85
86    /// The `dynamic` alias — every GENUINE blind-spot class (excludes `setup`), incl. `unresolved` (the
87    /// catch-all) so `Unknown[dynamic]` never under-gates. The design's recommended usable strict gate.
88    pub fn dynamic_set() -> BTreeSet<ReasonClass> {
89        [
90            ReasonClass::Reflect,
91            ReasonClass::Dispatch,
92            ReasonClass::Indirect,
93            ReasonClass::Native,
94            ReasonClass::Unresolved,
95        ]
96        .into_iter()
97        .collect()
98    }
99}
100
101/// Parse `unknown-alias <name> = <class,…>` lines from `.candor/config` text (⟨0.19⟩, SPEC §6.2) into a
102/// name→classes map. A name that shadows a built-in (`*`/`dynamic`/a class token) is warned-and-skipped (a
103/// config alias may not redefine a built-in), as is a definition naming no valid class. Byte-shape with the
104/// java reference `Config.addAlias`.
105pub fn parse_unknown_aliases(config_text: &str) -> std::collections::BTreeMap<String, BTreeSet<ReasonClass>> {
106    let mut out = std::collections::BTreeMap::new();
107    for raw in config_text.lines() {
108        let line = raw.split('#').next().unwrap_or("").trim();
109        if line.is_empty() {
110            continue;
111        }
112        let mut it = line.splitn(2, char::is_whitespace);
113        // Case-INSENSITIVE key match, like the config loaders in java/ts/swift (which lowercase the key) —
114        // a case-sensitive match here made `Unknown-Alias …` define an alias everywhere BUT rust (a four-way
115        // parse divergence; caught in review). The rest of the line (name + classes) stays case-sensitive.
116        if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("unknown-alias")) {
117            continue;
118        }
119        let val = it.next().unwrap_or("").trim();
120        let Some((name, classes)) = val.split_once('=') else {
121            eprintln!("candor: ignoring `unknown-alias` (want `unknown-alias <name> = <class,…>`): {val}");
122            continue;
123        };
124        let name = name.trim();
125        if name.is_empty() || name == "*" || name == "dynamic" || ReasonClass::from_token(name).is_some() {
126            eprintln!("candor: ignoring `unknown-alias` with reserved/empty name `{name}` (may not shadow `*`/`dynamic`/a class token)");
127            continue;
128        }
129        let mut set = BTreeSet::new();
130        for cn in classes.split(',') {
131            let cn = cn.trim();
132            if cn.is_empty() {
133                continue;
134            }
135            if cn == "dynamic" {
136                set.extend(ReasonClass::dynamic_set());
137            } else if let Some(rc) = ReasonClass::from_token(cn) {
138                set.insert(rc);
139            } else {
140                eprintln!("candor: `unknown-alias {name}` names unknown reason-class `{cn}` — skipped");
141            }
142        }
143        if set.is_empty() {
144            eprintln!("candor: ignoring `unknown-alias {name}` — no valid reason-class");
145        } else {
146            out.insert(name.to_string(), set);
147        }
148    }
149    out
150}
151
152/// Discover `.candor/config` text for a policy/scan anchored at `start`: `$CANDOR_CONFIG` if set + readable,
153/// else the nearest `.candor/config` walking UP from `start`, else `None`. Read-only + lenient (no
154/// process-exit — the caller decides fail-closed); used to resolve `unknown-alias` for the §6.2 gate +
155/// `parsepolicy` so both reflect the same checked-in config.
156pub fn discover_config_text(start: &std::path::Path) -> Option<String> {
157    if let Ok(p) = std::env::var("CANDOR_CONFIG") {
158        return std::fs::read_to_string(&p).ok();
159    }
160    let start = std::fs::canonicalize(start).unwrap_or_else(|_| start.to_path_buf());
161    let mut cur = if start.is_dir() { Some(start.as_path()) } else { start.parent() };
162    while let Some(d) = cur {
163        let cand = d.join(".candor/config");
164        if cand.is_file() {
165            return std::fs::read_to_string(&cand).ok();
166        }
167        cur = d.parent();
168    }
169    None
170}
171
172/// One `deny <Effect…> [scope]` / `pure <scope>` rule (AS-EFF-006). `effects` empty ⇒ a `pure` rule
173/// (ANY effect forbidden). `scope` is a path segment-scope the rule applies to (None = whole unit).
174#[derive(Debug, Clone)]
175pub struct PolicyRule {
176    pub effects: BTreeSet<&'static str>,
177    pub scope: Option<String>,
178    /// Reason-class filter on an `Unknown` membership (REASON-SCOPED-UNKNOWN-DESIGN.md): empty ⇒
179    /// `Unknown[*]` (any reason — the bare form); non-empty ⇒ the Unknown hit fires ONLY for a fn whose
180    /// (transitive) reason classes include one of these. Ignored when `effects` doesn't contain `Unknown`.
181    pub unknown_classes: BTreeSet<ReasonClass>,
182    pub raw: String,
183}
184
185/// One `allow <Effect> [in <scope>] <literal>…` rule (AS-EFF-008). The effect is one of the four
186/// that carry a literal surface (`Net` hosts / `Exec` commands / `Fs` paths / `Db` tables); a
187/// function in `scope` performing it may reach ONLY the listed literals. Matching is
188/// effect-specific (`literal_allowed`).
189#[derive(Debug, Clone)]
190pub struct AllowRule {
191    pub effect: &'static str,
192    pub scope: Option<String>,
193    pub literals: BTreeSet<String>,
194    pub raw: String,
195}
196
197/// One `forbid <A> -> <B>` module-layering rule (AS-EFF-009): a function in scope `A` must not
198/// transitively call into scope `B`.
199#[derive(Debug, Clone)]
200pub struct LayerRule {
201    pub from: String,
202    pub to: String,
203    pub raw: String,
204}
205
206/// The rule kinds parsed from a CANDOR_POLICY file.
207#[derive(Default, Debug)]
208pub struct ParsedPolicy {
209    pub rules: Vec<PolicyRule>,
210    pub allow_rules: Vec<AllowRule>,
211    pub layer_rules: Vec<LayerRule>,
212}
213
214/// The hostname part of a `host[:port]` literal, port stripped — so `api.stripe.com` in a rule accepts
215/// a reached `api.stripe.com:443`. IPv6-aware: a bracketed `[host]:port` yields the bracketed host, and
216/// a BARE IPv6 literal (>1 colon, no brackets) has no port to strip and is returned whole — a naive
217/// first-colon split collapsed every `2001:db8::*` to `2001`, so one allowed IPv6 accepted any address
218/// in that block (/code-review). A hostname/IPv4 `host` or `host:port` (≤1 colon) splits at the colon.
219pub fn host_part(h: &str) -> &str {
220    if let Some(rest) = h.strip_prefix('[') {
221        // `[ipv6]` or `[ipv6]:port` — the host is between the brackets.
222        return rest.split(']').next().unwrap_or(rest);
223    }
224    if h.matches(':').count() > 1 {
225        return h; // bare IPv6 literal — no port suffix to strip
226    }
227    h.split(':').next().unwrap_or(h)
228}
229
230/// The basename of a command (`/usr/bin/git` → `git`), so `allow Exec … git` accepts an absolute path.
231pub fn cmd_base(c: &str) -> &str {
232    c.rsplit(['/', '\\']).next().unwrap_or(c)
233}
234
235/// Whether an allowed path `a` covers a reached path `r` (SPEC §6.2: path-boundary-respecting prefix).
236/// A directory covers itself and everything beneath it, but NOT a sibling sharing a textual prefix
237/// (`/etc/app` ⊉ `/etc/apppwned`); a `..` that climbs out is never covered; absolute/relative are
238/// never conflated.
239pub fn fs_path_covered(a: &str, r: &str) -> bool {
240    if r.split(['/', '\\']).any(|c| c == "..") {
241        return false;
242    }
243    let absolute = |s: &str| s.starts_with('/') || s.starts_with('\\');
244    if absolute(a) != absolute(r) {
245        return false;
246    }
247    let norm = |s: &str| -> Vec<String> {
248        s.split(['/', '\\'])
249            .filter(|c| !c.is_empty() && *c != ".")
250            .map(|c| c.to_string())
251            .collect()
252    };
253    let (ac, rc) = (norm(a), norm(r));
254    ac.len() <= rc.len() && ac.iter().zip(&rc).all(|(x, y)| x == y)
255}
256
257/// Whether an allowed table entry `a` covers a reached table `r` (SPEC §6.2): case-insensitive
258/// exact match on the (possibly schema-qualified) name, or a `schema.*` entry covering every table
259/// in that schema. Strict on qualification — an allowed `entries` does NOT cover a reached
260/// `ledger.entries` (write both forms if your queries mix them); silent widening is the failure
261/// mode an allowlist exists to prevent.
262pub fn db_table_covered(a: &str, r: &str) -> bool {
263    let (a, r) = (a.to_lowercase(), r.to_lowercase());
264    if let Some(schema) = a.strip_suffix(".*") {
265        return r.strip_prefix(schema).is_some_and(|rest| rest.starts_with('.'));
266    }
267    a == r
268}
269
270/// Whether a reached literal is allowed under an effect-specific match (SPEC §6.2): `Net` host by
271/// name (port ignored), `Exec` command by basename, `Fs` path by boundary-respecting prefix,
272/// `Db` table by qualified name or `schema.*`.
273pub fn literal_allowed(effect: &str, reached: &str, allow: &BTreeSet<String>) -> bool {
274    match effect {
275        // `Llm` ⟨0.13⟩ rides the Net host literal (SPEC §1) — matched by hostname like `Net`.
276        "Net" | "Llm" => allow.iter().any(|a| host_part(a) == host_part(reached)),
277        "Exec" => allow.iter().any(|a| cmd_base(a) == cmd_base(reached)),
278        "Fs" => allow.iter().any(|a| fs_path_covered(a, reached)),
279        "Db" => allow.iter().any(|a| db_table_covered(a, reached)),
280        _ => allow.contains(reached),
281    }
282}
283
284/// Split a function name (or scope) into PATH SEGMENTS on either separator. Reports reach the Rust gate
285/// AND `candor-query` from BOTH the Rust engines (`::`-separated names) and the JVM/Swift/TS engines
286/// (`.`-separated names — `candor-query` is explicitly built to read them). Segmenting on `::` ALONE
287/// left a scoped `deny`/`pure` rule silently INERT on a dotted name: the scope matched nothing, so
288/// `whatif` returned a false green on the security boundary (gate-evasion). The JVM engine's own
289/// `scopeMatches` already splits on `.`; this aligns the Rust side. A `:`/`.` never appears WITHIN a
290/// real segment, so splitting on both never over-segments a Rust name (no spurious match).
291fn name_segments(s: &str) -> Vec<&str> {
292    s.split(['.', ':']).filter(|p| !p.is_empty()).collect()
293}
294
295/// A policy scope matches a function name by **path segment** (SPEC §6.2), not substring: split both
296/// into segments (on `::` or `.`); the scope matches a contiguous run of name-segments where every
297/// segment except the last matches exactly and the last is a prefix. So `domain` matches
298/// `app::domain::h`, `com.acme.domain.h`, and `domain_logic` but not `subdomain`.
299pub fn scope_matches(name: &str, scope: &str) -> bool {
300    let segs = name_segments(name);
301    let parts = name_segments(scope);
302    if parts.is_empty() || parts.len() > segs.len() {
303        return false;
304    }
305    let (last, init) = parts.split_last().unwrap();
306    segs.windows(parts.len()).any(|w| {
307        let (w_last, w_init) = w.split_last().unwrap();
308        w_init == init && w_last.starts_with(last)
309    })
310}
311
312/// Reconstruct a rule's source form and the `Unknown`-forbidding upgrade for it: `pure <scope>` →
313/// (`"pure <scope>"`, `"deny Unknown <scope>"`); `deny <E…> <scope>` → (`"deny <E…> <scope>"`,
314/// `"deny <E…> Unknown <scope>"`). Shared so the gate note and `candor unverified` name the identical
315/// rule and upgrade — one source of truth for the disclosure's advice.
316pub fn rule_and_upgrade(r: &PolicyRule) -> (String, String) {
317    let scope = r.scope.clone().unwrap_or_default();
318    let suffix = if scope.is_empty() { String::new() } else { format!(" {scope}") };
319    if r.effects.is_empty() {
320        // `pure` forbids real effects but not Unknown; to REQUIRE provable purity, add a deny-Unknown.
321        (format!("pure{suffix}"), format!("deny Unknown{suffix}"))
322    } else {
323        let effs = r.effects.iter().copied().collect::<Vec<_>>().join(" ");
324        (format!("deny {effs}{suffix}"), format!("deny {effs} Unknown{suffix}"))
325    }
326}
327
328/// The single predicate for a provable-purity hole (eval/fixloop/DISPATCH-NOTE.md): a function that is
329/// `Unknown`, sits in a `pure`/`deny <E>` scope, and PASSES that rule (carries none of its forbidden real
330/// effects) — so its compliance is asserted but not verified (the Unknown could hide the very effect the
331/// rule forbids; the classic case is a fn/closure-injected port). A *real* violation is the gate's job, not
332/// this. Returns the first governing rule under which the function is such a hole, or `None` if it is not
333/// one. Shared by candor-scan's gate note and candor-query's `unverified` so "what a hole is" has ONE
334/// definition — the two paths can never drift (conformance PART 12d pins their agreement).
335pub fn unverified_hole_rule<'a, S: AsRef<str>>(
336    name: &str,
337    effects: &[S],
338    rules: &'a [PolicyRule],
339) -> Option<&'a PolicyRule> {
340    if !effects.iter().any(|e| e.as_ref() == UNKNOWN) {
341        return None;
342    }
343    rules.iter().find(|r| {
344        // in the rule's scope (a scopeless rule governs the whole unit) …
345        if let Some(s) = &r.scope {
346            if !scope_matches(name, s) {
347                return false;
348            }
349        }
350        // … and PASSES it (no forbidden real effect — else it is a violation the gate already reports).
351        let violates = if r.effects.is_empty() {
352            effects.iter().any(|e| e.as_ref() != UNKNOWN)
353        } else {
354            effects.iter().any(|e| r.effects.contains(e.as_ref()))
355        };
356        !violates
357    })
358}
359
360/// Parse a CANDOR_POLICY file (SPEC §6.2). One rule per line; `#` comments and blanks ignored:
361///
362/// ```text
363/// deny Net Db  domain     # functions whose path contains segment "domain" must not perform Net or Db
364/// deny Exec               # no function anywhere may perform Exec
365/// deny Unknown  api        # functions in "api" must be fully resolvable (forbid the unverifiable)
366/// pure         parse      # functions whose path contains segment "parse" must be effect-free
367/// allow Net in billing  api.stripe.com
368/// forbid domain -> infra
369/// ```
370///
371/// In a `deny` rule, leading tokens that name a known effect (or `Unknown`) are forbidden; the FIRST
372/// non-effect token is the scope and ends the rule. A `deny` naming no known effect is dropped (it is
373/// NOT a `pure` rule). Malformed/unknown lines are ignored with a warning — never silently widened.
374/// The §6.2 token separator: ASCII whitespace ONLY (space/tab/CR/LF/VT/FF). `split_whitespace`/`trim`
375/// use Unicode `White_Space`, which would split a NBSP/ideographic space that Java drops — a gateless-
376/// green cross-engine divergence (adversarial DSL review). A non-ASCII space stays part of its token, so
377/// the rule is malformed and ignored, uniformly.
378fn is_ascii_ws(c: char) -> bool {
379    matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
380}
381
382pub fn parse_policy(text: &str) -> ParsedPolicy {
383    parse_policy_impl(text, true, &std::collections::BTreeMap::new())
384}
385/// As [`parse_policy`] but with `.candor/config` `unknown-alias` definitions (⟨0.19⟩, SPEC §6.2): an
386/// `Unknown[<name>]` filter resolves a user-defined `<name>` to its reason classes. The gate + `parsepolicy`
387/// pass the discovered aliases (via [`parse_unknown_aliases`]); a config alias never changes what bare
388/// `deny E Unknown` means (always `Unknown[*]`), so the rule stays legible from the policy alone.
389pub fn parse_policy_with_aliases(text: &str, aliases: &std::collections::BTreeMap<String, std::collections::BTreeSet<ReasonClass>>) -> ParsedPolicy {
390    parse_policy_impl(text, true, aliases)
391}
392/// Same as [`parse_policy`] but SILENT about malformed rules — for a SECOND, advisory re-parse within the
393/// same run (candor-scan parses once for the gate check and again for the `unverified` disclosure), so the
394/// CI log doesn't print every "ignoring policy rule …" warning twice (#21). The first parse already warned.
395pub fn parse_policy_quiet(text: &str) -> ParsedPolicy {
396    parse_policy_impl(text, false, &std::collections::BTreeMap::new())
397}
398fn parse_policy_impl(text: &str, warn: bool, aliases: &std::collections::BTreeMap<String, std::collections::BTreeSet<ReasonClass>>) -> ParsedPolicy {
399    macro_rules! warn_ignore { ($($a:tt)*) => { if warn { eprintln!($($a)*); } } }
400    let mut out = ParsedPolicy::default();
401    // `str::lines()` splits on \n and \r\n but NOT bare \r — a classic-Mac file then collapses to ONE
402    // line, and since \r is also an in-line ASCII-ws token separator (is_ascii_ws), every rule after the
403    // first was glued into the first rule's tokens and dropped (sweep [16], a gateless-green divergence).
404    // Java's Files.readAllLines (the reference) breaks on bare \r too — normalize to match it. Allocation
405    // only when a bare \r is actually present (the overwhelmingly-common \n / \r\n files are untouched).
406    let normalized;
407    let text = if text.contains('\r') {
408        normalized = text.replace("\r\n", "\n").replace('\r', "\n");
409        normalized.as_str()
410    } else {
411        text
412    };
413    for raw_line in text.lines() {
414        let line = raw_line.split('#').next().unwrap_or("").trim_matches(is_ascii_ws);
415        if line.is_empty() {
416            continue;
417        }
418        let mut toks = line.split(is_ascii_ws).filter(|s| !s.is_empty());
419        match toks.next().unwrap_or("") {
420            "allow" => {
421                let effect = match toks.next().unwrap_or("") {
422                    "Net" => "Net",
423                    // `Llm` ⟨0.13⟩ rides the Net host literal (SPEC §1) — `allow Llm <host…>` restricts which
424                    // MODEL hosts a scope may reach, matched by hostname like Net (its reached surface IS the
425                    // Net host surface). Match candor-java's Policy.parsePolicy.
426                    "Llm" => "Llm",
427                    "Exec" => "Exec",
428                    "Fs" => "Fs",
429                    "Db" => "Db",
430                    _ => {
431                        warn_ignore!(
432"candor: ignoring policy rule (allow supports only Net hosts / Llm hosts / Exec commands / Fs paths / Db tables): {line}"
433                        );
434                        continue;
435                    }
436                };
437                let mut rest: Vec<&str> = toks.collect();
438                let scope = if rest.first() == Some(&"in") {
439                    let s = rest.get(1).map(|s| s.to_string());
440                    rest.drain(..2.min(rest.len()));
441                    s
442                } else {
443                    None
444                };
445                let literals: BTreeSet<String> = rest.iter().map(|h| h.to_string()).collect();
446                if literals.is_empty() {
447                    warn_ignore!("candor: ignoring policy rule (allow {effect} names no values): {line}");
448                    continue;
449                }
450                out.allow_rules.push(AllowRule { effect, scope, literals, raw: line.to_string() });
451            }
452            "deny" => {
453                let mut effects = BTreeSet::new();
454                let mut scope = None;
455                // Reason-class filter on `Unknown` (REASON-SCOPED-UNKNOWN-DESIGN.md): empty ⇒ `Unknown[*]`
456                // (any reason — the bare form); non-empty ⇒ only those classes. `*` = all.
457                let mut unknown_classes: BTreeSet<ReasonClass> = BTreeSet::new();
458                let mut unknown_star = false;
459                for t in toks {
460                    // `Unknown[dispatch,reflect]` / `Unknown[*]` / `Unknown[dynamic]`: the reason-scoped form.
461                    if let Some(inner) = t.strip_prefix("Unknown[").and_then(|s| s.strip_suffix(']')) {
462                        effects.insert(UNKNOWN);
463                        for cn in inner.split(',') {
464                            let cn = cn.trim();
465                            if cn.is_empty() {
466                                continue;
467                            }
468                            if cn == "*" {
469                                unknown_star = true;
470                            } else if cn == "dynamic" {
471                                unknown_classes.extend(ReasonClass::dynamic_set());
472                            } else if let Some(rc) = ReasonClass::from_token(cn) {
473                                unknown_classes.insert(rc);
474                            } else if let Some(a) = aliases.get(cn) {
475                                unknown_classes.extend(a.iter().copied()); // ⟨0.19⟩ config `unknown-alias`
476                            } else {
477                                warn_ignore!("candor: policy rule names unknown reason-class/alias `{cn}` (known: reflect,dispatch,indirect,native,unresolved,setup; aliases: dynamic,*, or a config `unknown-alias`): {line}");
478                            }
479                        }
480                        continue;
481                    }
482                    let e = if t == UNKNOWN { Some(UNKNOWN) } else { cap_from_name(t) };
483                    match e {
484                        Some(e) => {
485                            effects.insert(e);
486                            if e == UNKNOWN {
487                                unknown_star = true; // bare Unknown ⇒ all classes
488                            }
489                        }
490                        None => {
491                            scope = Some(t.to_string());
492                            break;
493                        }
494                    }
495                }
496                if effects.is_empty() {
497                    warn_ignore!("candor: ignoring policy rule (no known effect named): {line}");
498                    continue;
499                }
500                // `*` (or bare `Unknown`) means all classes ⇒ empty filter (matches any Unknown).
501                if unknown_star {
502                    unknown_classes.clear();
503                } else if !unknown_classes.is_empty() && !unknown_classes.contains(&ReasonClass::Unresolved) {
504                    // A2 under-gating lint: a narrowed scope that omits `unresolved` (the catch-all for holes
505                    // an engine couldn't classify) may silently tolerate exactly those — flag it (advisory).
506                    warn_ignore!("candor: policy rule narrows `Unknown[…]` but omits `unresolved` — may UNDER-gate on holes the engine couldn't classify; add `unresolved` (or use `dynamic`) to stay conservative: {line}");
507                }
508                out.rules.push(PolicyRule { effects, scope, unknown_classes, raw: line.to_string() });
509            }
510            "pure" => out.rules.push(PolicyRule {
511                effects: BTreeSet::new(),
512                scope: toks.next().map(str::to_string),
513                unknown_classes: BTreeSet::new(),
514                raw: line.to_string(),
515            }),
516            "forbid" => {
517                let a = toks.next().unwrap_or("");
518                let arrow = toks.next().unwrap_or("");
519                let b = toks.next().unwrap_or("");
520                if a.is_empty() || arrow != "->" || b.is_empty() {
521                    warn_ignore!("candor: ignoring layering rule (want `forbid <scope> -> <scope>`): {line}");
522                    continue;
523                }
524                out.layer_rules.push(LayerRule {
525                    from: a.to_string(),
526                    to: b.to_string(),
527                    raw: line.to_string(),
528                });
529            }
530            other => warn_ignore!("candor: ignoring policy rule (unknown kind `{other}`): {line}"),
531        }
532    }
533    out
534}
535
536#[cfg(test)]
537mod tests {
538    #[test]
539    fn db_table_covering_is_strict() {
540        use super::db_table_covered as c;
541        assert!(c("ledger.entries", "Ledger.Entries")); // case-insensitive exact
542        assert!(c("ledger.*", "ledger.entries"));       // schema wildcard
543        assert!(!c("ledger.*", "ledgerx.entries"));     // boundary-respecting
544        assert!(!c("entries", "ledger.entries"));       // no silent qualification widening
545        assert!(c("entries", "entries"));
546    }
547
548    #[test]
549    fn allow_db_parses_and_gates() {
550        let p = super::parse_policy("allow Db in billing  ledger.* customers\n");
551        assert_eq!(p.allow_rules.len(), 1);
552        assert_eq!(p.allow_rules[0].effect, "Db");
553        assert!(super::literal_allowed("Db", "ledger.entries", &p.allow_rules[0].literals));
554        assert!(super::literal_allowed("Db", "customers", &p.allow_rules[0].literals));
555        assert!(!super::literal_allowed("Db", "audit.log", &p.allow_rules[0].literals));
556    }
557
558    use super::*;
559
560    #[test]
561    fn policy_parses() {
562        let p = parse_policy(
563            "# the domain layer must stay pure of I/O\n\
564             deny Net Db  domain\n\
565             deny Exec\n\
566             pure  parse\n\
567             nonsense line\n\
568             deny notaneffect\n",
569        );
570        let rules = &p.rules;
571        assert_eq!(rules.len(), 3);
572        assert_eq!(rules[0].effects, ["Db", "Net"].into_iter().collect::<BTreeSet<_>>());
573        assert_eq!(rules[0].scope.as_deref(), Some("domain"));
574        assert!(rules[1].effects.contains("Exec") && rules[1].scope.is_none());
575        assert!(rules[2].effects.is_empty() && rules[2].scope.as_deref() == Some("parse"));
576        // sweep [16]: a classic-Mac (bare \r) multi-rule policy must NOT collapse to the first rule.
577        let cr = parse_policy("deny Net a\rdeny Exec b\rdeny Db c\r");
578        assert_eq!(cr.rules.len(), 3, "bare-CR lines must each parse");
579        assert!(cr.rules.iter().any(|r| r.effects.contains("Exec") && r.scope.as_deref() == Some("b")));
580        // mixed \r\n and bare \r normalize identically.
581        assert_eq!(parse_policy("deny Net a\r\ndeny Exec b\r").rules.len(), 2);
582        // `Unknown` is a denyable token; a bare `deny` with no effect is ignored.
583        assert_eq!(parse_policy("deny Unknown core").rules[0].effects, ["Unknown"].into_iter().collect());
584        assert!(parse_policy("deny\ndeny   \n").rules.is_empty());
585        // a `deny` whose first token is a non-effect names no effect -> dropped, NOT a pure rule.
586        assert!(parse_policy("deny notaneffect scope").rules.is_empty());
587        // the first non-effect token ENDS the rule: a later effect token is not collected.
588        let p2 = parse_policy("deny Net foo Db");
589        assert_eq!(p2.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
590        assert_eq!(p2.rules[0].scope.as_deref(), Some("foo"));
591        // NBSP is NOT a token separator (only ASCII White_Space is) — pinned to MATCH Java, which
592        // drops it: a `deny\u{a0}Net` is one token `deny\u{a0}Net`, NOT `deny` + `Net`, so it names no
593        // known effect and is dropped. Splitting on Unicode whitespace here would let candor see a deny
594        // the JVM engine doesn't — a gateless-divergence between impls. (See is_ascii_ws.)
595        assert!(parse_policy("deny\u{a0}Net core").rules.is_empty(),
596                "an NBSP between deny and the effect must NOT split into separate tokens");
597        // The NBSP rides INTO the scope token rather than separating it: `deny Net\u{a0}domain` is
598        // `deny` + `Net` + `\u{a0}domain` — Net is the effect, the scope keeps the NBSP verbatim.
599        let nb = parse_policy("deny Net \u{a0}domain");
600        assert_eq!(nb.rules.len(), 1);
601        assert_eq!(nb.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
602        assert_eq!(nb.rules[0].scope.as_deref(), Some("\u{a0}domain"));
603    }
604
605    #[test]
606    fn reason_scoped_unknown_parses() {
607        use super::ReasonClass::*;
608        // `Unknown[dispatch,indirect]` narrows the Unknown membership to those classes.
609        let p = parse_policy("deny Net Unknown[dispatch,indirect] dom\n");
610        let r = &p.rules[0];
611        assert!(r.effects.contains("Unknown") && r.effects.contains("Net"));
612        assert_eq!(r.scope.as_deref(), Some("dom"));
613        assert_eq!(r.unknown_classes, [Dispatch, Indirect].into_iter().collect());
614        // bare `Unknown` and `Unknown[*]` ⇒ empty filter (all classes).
615        assert!(parse_policy("deny Net Unknown dom\n").rules[0].unknown_classes.is_empty(), "bare Unknown ⇒ all");
616        assert!(parse_policy("deny Net Unknown[*] dom\n").rules[0].unknown_classes.is_empty(), "Unknown[*] ⇒ all");
617        // `dynamic` alias = every genuine class incl. unresolved, excl. setup.
618        assert_eq!(
619            parse_policy("deny Net Unknown[dynamic] dom\n").rules[0].unknown_classes,
620            [Reflect, Dispatch, Indirect, Native, Unresolved].into_iter().collect()
621        );
622        // config `unknown-alias` (⟨0.19⟩): a user-defined name resolves; a reserved name is rejected.
623        let aliases = super::parse_unknown_aliases(
624            "unknown-alias risky = reflect,native\nunknown-alias telemetry = indirect\nunknown-alias reflect = native\n");
625        assert_eq!(aliases.get("risky"), Some(&[Reflect, Native].into_iter().collect()));
626        assert_eq!(aliases.get("telemetry"), Some(&[Indirect].into_iter().collect()));
627        assert!(!aliases.contains_key("reflect"), "a config alias may not shadow a class token");
628        // the `unknown-alias` KEY matches case-insensitively (parity with java/ts/swift, which lowercase it)
629        assert_eq!(super::parse_unknown_aliases("Unknown-Alias hot = native\n").get("hot"),
630                   Some(&[Native].into_iter().collect()), "the unknown-alias key must match case-insensitively");
631        let pr = super::parse_policy_with_aliases("deny Net Unknown[risky] api\n", &aliases);
632        assert_eq!(pr.rules[0].unknown_classes, [Reflect, Native].into_iter().collect());
633        // an UNDEFINED alias name is dropped-with-warning → empty filter (behaves like bare Unknown[*])
634        assert!(super::parse_policy_with_aliases("deny Net Unknown[nope] api\n", &aliases).rules[0].unknown_classes.is_empty());
635        // classify: raw reason tokens → normative classes (mirrors java ReasonClass.classify).
636        assert_eq!(ReasonClass::classify("reflect:Class.forName"), Reflect);
637        assert_eq!(ReasonClass::classify("native:extern fn"), Native);
638        assert_eq!(ReasonClass::classify("callback:unresolved call"), Indirect);
639        assert_eq!(ReasonClass::classify("ambiguous:same-name local defs"), Dispatch);
640        assert_eq!(ReasonClass::classify("unresolved"), Unresolved);
641        assert_eq!(ReasonClass::classify("whatever-new"), Unresolved); // conservative catch-all
642    }
643
644    #[test]
645    fn allowlist_parses() {
646        let p = parse_policy(
647            "allow Net in billing  api.stripe.com  hooks.stripe.com\n\
648             allow Exec in ci  git\n\
649             allow Fs in config  /etc/app\n\
650             allow Net  github.com\n\
651             allow Clock  whatever\n\
652             allow Net in nohosts\n\
653             allow\n",
654        );
655        assert_eq!(p.allow_rules.len(), 4); // Clock carries no literal surface — rejected; Db now does
656        assert_eq!((p.allow_rules[0].effect, p.allow_rules[0].scope.as_deref()), ("Net", Some("billing")));
657        assert_eq!(
658            p.allow_rules[0].literals,
659            ["api.stripe.com", "hooks.stripe.com"].iter().map(|s| s.to_string()).collect()
660        );
661        assert_eq!((p.allow_rules[1].effect, p.allow_rules[1].scope.as_deref()), ("Exec", Some("ci")));
662        assert!(p.allow_rules[1].literals.contains("git"));
663        assert_eq!((p.allow_rules[2].effect, p.allow_rules[2].scope.as_deref()), ("Fs", Some("config")));
664        assert_eq!((p.allow_rules[3].effect, p.allow_rules[3].scope.is_none()), ("Net", true));
665
666        let set = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<BTreeSet<_>>();
667        assert!(literal_allowed("Net", "api.stripe.com:443", &set(&["api.stripe.com"])));
668        // IPv6: a bare literal is matched WHOLE (no first-colon collapse), so a different address in the
669        // same block is NOT accepted; a bracketed `[host]:port` matches the bare host. (/code-review.)
670        assert!(literal_allowed("Net", "2001:db8::aa", &set(&["2001:db8::aa"])));
671        assert!(!literal_allowed("Net", "2001:db8::ff", &set(&["2001:db8::aa"])));
672        assert!(!literal_allowed("Net", "2001:dead::1", &set(&["2001:db8::aa"])));
673        assert!(literal_allowed("Net", "[2001:db8::aa]:443", &set(&["2001:db8::aa"])));
674        assert_eq!(host_part("2001:db8::aa"), "2001:db8::aa");
675        assert_eq!(host_part("[2001:db8::aa]:443"), "2001:db8::aa");
676        assert_eq!(host_part("api.stripe.com:443"), "api.stripe.com");
677        assert!(literal_allowed("Exec", "/usr/bin/git", &set(&["git"])));
678        assert!(!literal_allowed("Exec", "/usr/bin/curl", &set(&["git"])));
679        assert!(literal_allowed("Fs", "/etc/app/conf.toml", &set(&["/etc/app"])));
680        assert!(!literal_allowed("Fs", "/etc/shadow", &set(&["/etc/app"])));
681        assert_eq!(cmd_base("/usr/bin/git"), "git");
682    }
683
684    #[test]
685    fn layering_rule_parses() {
686        let p = parse_policy(
687            "forbid domain -> infra\n\
688             forbid  app::web  ->  app::db \n\
689             forbid domain infra\n\
690             forbid domain ->\n\
691             forbid\n",
692        );
693        assert_eq!(p.layer_rules.len(), 2);
694        assert_eq!((p.layer_rules[0].from.as_str(), p.layer_rules[0].to.as_str()), ("domain", "infra"));
695        assert_eq!((p.layer_rules[1].from.as_str(), p.layer_rules[1].to.as_str()), ("app::web", "app::db"));
696    }
697
698    #[test]
699    fn scope_matches_by_segment_not_substring() {
700        assert!(scope_matches("app::domain::handle", "domain"));
701        assert!(scope_matches("domain::handle", "domain"));
702        assert!(scope_matches("app::domain", "domain"));
703        assert!(scope_matches("crate::domain_logic", "domain"));
704        assert!(!scope_matches("app::subdomain::handle", "domain"));
705        assert!(!scope_matches("app::not_my_domain::f", "domain"));
706        // multi-segment: intermediates exact, last is a prefix, contiguous.
707        assert!(scope_matches("crate::net::client::send", "net::client"));
708        assert!(scope_matches("crate::net::client_pool::get", "net::client"));
709        assert!(!scope_matches("crate::net::server::send", "net::client"));
710        assert!(!scope_matches("crate::network::client::send", "net::client"));
711        assert!(!scope_matches("crate::net::x::client", "net::client"));
712        assert!(!scope_matches("net", "net::client"));
713        // DOTTED names (JVM/Swift/TS reports `candor-query` consumes): a scope must match across `.` too,
714        // else a scoped deny/pure rule is silently inert → whatif false-green (gate-evasion). Both a
715        // `.`-written and a `::`-written scope must match a dotted name.
716        assert!(scope_matches("com.acme.domain.Pricing.quote", "domain"));
717        assert!(scope_matches("com.acme.domain.Pricing.quote", "acme.domain"));
718        assert!(scope_matches("com.acme.domain.Pricing.quote", "acme::domain"));
719        assert!(scope_matches("com.acme.infra.Net.fetch", "infra.Net"));
720        assert!(!scope_matches("com.acme.subdomain.h", "domain"));
721        assert!(!scope_matches("com.acme.domain.h", "infra"));
722    }
723
724    #[test]
725    fn fs_path_covered_respects_boundaries() {
726        assert!(fs_path_covered("/etc/app", "/etc/app"));
727        assert!(fs_path_covered("/etc/app", "/etc/app/cfg.toml"));
728        assert!(fs_path_covered("/etc/app/", "/etc/app/cfg"));
729        assert!(!fs_path_covered("/etc/app", "/etc/apppwned"));
730        assert!(!fs_path_covered("/etc/app", "/etc/application/x"));
731        assert!(!fs_path_covered("/etc/app/cfg", "/etc/app"));
732        assert!(!fs_path_covered("/etc/app", "/etc/app/../passwd"));
733        assert!(fs_path_covered("/", "/etc/app/x"));
734        assert!(!fs_path_covered("etc/app", "/etc/app/cfg"));
735        assert!(!fs_path_covered("/etc/app", "etc/app/cfg"));
736        assert!(fs_path_covered("etc/app", "etc/app/cfg"));
737    }
738}