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::{BTreeMap, 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, Hash)]
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 ///
70 /// ⟨0.24⟩ THIS IS THE ONLY PLACE THIS ENGINE HOLDS SPEC §4's KIND VOCABULARY. Every other reference
71 /// to a kind is either a raw string being emitted or the `dispatch:` prefix test in candor-query's
72 /// dispatch frontier; there is no typed kind enum here. §4's "AN ENGINE HOLDS THIS VOCABULARY TWICE,
73 /// AND THE HALVES DRIFT" paragraph records the JVM engine classifying `ambiguous` correctly HERE
74 /// while its typed `Kind` enum lacked the kind entirely — one token, two answers, inside one engine,
75 /// concealed precisely because this half was right. Holding it once is why that is not reachable in
76 /// this engine; a future typed representation must be added at the same commit as its control
77 /// (`off_vocabulary_kinds_round_trip_and_classify_through_the_catch_all`).
78 ///
79 /// The five §4 kinds are `reflect`/`native`/`dispatch`/`callback`/`ambiguous`. `ambiguous` maps to
80 /// `dispatch` and rust is its only PRODUCER; `indy`/`task-handoff` are candor-java's migration kinds
81 /// and `dep:`/`dep-stale:` are swift's registered per-dependency-ENTRY kinds, reaching `Unresolved`
82 /// through the catch-all, which is the class §6.2 prescribes for them.
83 pub fn classify(why: &str) -> ReasonClass {
84 let w = why.trim().to_ascii_lowercase();
85 if w.starts_with("reflect") || w == "dynamicmemberlookup" {
86 ReasonClass::Reflect
87 } else if w.starts_with("native") {
88 ReasonClass::Native
89 } else if w.starts_with("callback") || w.starts_with("closure") || w.starts_with("task-handoff") {
90 ReasonClass::Indirect
91 } else if w.starts_with("dispatch") || w.starts_with("indy") || w.starts_with("ambiguous") {
92 ReasonClass::Dispatch
93 } else if w.starts_with("missing-config") || w.starts_with("no-tsconfig") || w.starts_with("no-node_modules") {
94 ReasonClass::Setup
95 } else {
96 ReasonClass::Unresolved
97 }
98 }
99
100 /// The `dynamic` alias — every GENUINE blind-spot class (excludes `setup`), incl. `unresolved` (the
101 /// catch-all) so `Unknown[dynamic]` never under-gates. The design's recommended usable strict gate.
102 pub fn dynamic_set() -> BTreeSet<ReasonClass> {
103 [
104 ReasonClass::Reflect,
105 ReasonClass::Dispatch,
106 ReasonClass::Indirect,
107 ReasonClass::Native,
108 ReasonClass::Unresolved,
109 ]
110 .into_iter()
111 .collect()
112 }
113}
114
115/// SPEC §6.2 ⟨0.24⟩ — does a function's TRANSITIVE reason-class set intersect `want` (class tokens)?
116///
117/// THE `None`/EMPTY ARM IS THE FAIL-CLOSED NET, and it is why this lives here rather than being
118/// open-coded twice. §6.2: "a function whose `Unknown` carries no recorded reason CONTRIBUTES
119/// `unresolved` to its class set — so a narrowed filter never *silently* tolerates a hole it failed to
120/// classify." Read the other way round, `!contains ⇒ exclude` over an empty set drops the entry from
121/// EVERY filter including one naming its own class: a silent under-report wearing a filter.
122///
123/// `classes` is the ACCUMULATED (post-`propagate_str`) set, never the direct `unknownWhy`: a reason
124/// names a site in the function's OWN body (§4), so a function whose `Unknown` is purely inherited
125/// carries none, and matching against the direct field answers a different question. SHARED by the
126/// `deny E Unknown[class]` gate (candor-scan) and `unverified --class` (candor-query) so a gate and the
127/// disclosure explaining it cannot disagree about which holes a class names.
128///
129/// The empty arm is a NET, not a route: it keys on the ABSENCE of a class set, so any other reason on
130/// the same function hides whatever it was covering. The reasonless case that CAN co-occur with a
131/// reason — a direct `Unknown` the unit did not name — must therefore contribute `unresolved` into the
132/// DIRECT map before propagation (candor-scan's `unknown_via_dep`, candor-query's report-side signature),
133/// not arrive here by absence.
134pub fn reason_class_matches(classes: Option<&BTreeSet<String>>, want: &BTreeSet<&str>) -> bool {
135 match classes {
136 None => want.contains(ReasonClass::Unresolved.token()),
137 Some(cs) if cs.is_empty() => want.contains(ReasonClass::Unresolved.token()),
138 Some(cs) => cs.iter().any(|t| want.contains(t.as_str())),
139 }
140}
141
142/// Parse `unknown-alias <name> = <class,…>` lines from `.candor/config` text (⟨0.19⟩, SPEC §6.2) into a
143/// name→classes map. A name that shadows a built-in (`*`/`dynamic`/a class token) is warned-and-skipped (a
144/// config alias may not redefine a built-in), as is a definition naming no valid class. Byte-shape with the
145/// java reference `Config.addAlias`.
146pub fn parse_unknown_aliases(config_text: &str) -> std::collections::BTreeMap<String, BTreeSet<ReasonClass>> {
147 let mut out = std::collections::BTreeMap::new();
148 for raw in config_text.lines() {
149 let line = raw.split('#').next().unwrap_or("").trim();
150 if line.is_empty() {
151 continue;
152 }
153 let mut it = line.splitn(2, char::is_whitespace);
154 // Case-INSENSITIVE key match, like the config loaders in java/ts/swift (which lowercase the key) —
155 // a case-sensitive match here made `Unknown-Alias …` define an alias everywhere BUT rust (a four-way
156 // parse divergence; caught in review). The rest of the line (name + classes) stays case-sensitive.
157 if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("unknown-alias")) {
158 continue;
159 }
160 let val = it.next().unwrap_or("").trim();
161 let Some((name, classes)) = val.split_once('=') else {
162 eprintln!("candor: ignoring `unknown-alias` (want `unknown-alias <name> = <class,…>`): {val}");
163 continue;
164 };
165 let name = name.trim();
166 if name.is_empty() || name == "*" || name == "dynamic" || ReasonClass::from_token(name).is_some() {
167 eprintln!("candor: ignoring `unknown-alias` with reserved/empty name `{name}` (may not shadow `*`/`dynamic`/a class token)");
168 continue;
169 }
170 let mut set = BTreeSet::new();
171 let mut bad: Vec<&str> = Vec::new();
172 for cn in classes.split(',') {
173 let cn = cn.trim();
174 if cn.is_empty() {
175 continue;
176 }
177 if cn == "dynamic" {
178 set.extend(ReasonClass::dynamic_set());
179 } else if let Some(rc) = ReasonClass::from_token(cn) {
180 set.insert(rc);
181 } else {
182 bad.push(cn);
183 }
184 }
185 // ⟨0.24⟩ **AN UNRECOGNISED TOKEN REFUSES THE WHOLE DEFINITION** — SPEC §6.2 `be0b9a9`: the rule
186 // binds every policy value list, and *"the second is the sharper one: the typo is in the
187 // vocabulary the policy is written against rather than in the policy itself, and it fails open
188 // identically."*
189 //
190 // MEASURED: `unknown-alias corp = dispatch,nativ` → the DEFINITION silently became `{dispatch}`,
191 // so `deny Unknown[corp]` exited 0 over a native-caused hole that `= dispatch,native` catches.
192 // The alias resolved, `used_aliases` recorded it, the verdict named the config — every disclosure
193 // fired correctly ABOUT A DEFINITION THAT WAS NOT THE ONE ON DISK.
194 //
195 // REFUSING THE DEFINITION rather than minting a new error channel is what makes this fit: an
196 // alias that does not exist is one the policy's own `Unknown[<name>]` cannot resolve, so it lands
197 // on the `errors` path already there and the gate routes refuse with exit 2 — naming the token
198 // AND the accepted set, as §6.2 requires. It also keeps the blast radius honest: a config
199 // defining ten aliases, one of them typo'd and NONE of them mentioned by this policy, changed
200 // nothing, and turning that into a red gate would be the mirror over-reach. The refusal is
201 // triggered by USE, exactly like `used_aliases` (recorded at the point of use, for the same
202 // reason).
203 if !bad.is_empty() {
204 eprintln!(
205 "candor: REFUSING `unknown-alias {name}` — it names unrecognised reason-class(es) `{}` \
206 (accepted: reflect, dispatch, indirect, native, unresolved, setup, plus `dynamic`). The \
207 definition is refused WHOLE rather than narrowed to the tokens that parsed: keeping the \
208 rest would silently redefine `{name}` as something narrower than the config says, and a \
209 policy using it would gate less than it reads. `{name}` is now undefined, so a policy \
210 naming it is a policy error (exit 2).",
211 bad.join("`, `")
212 );
213 } else if set.is_empty() {
214 eprintln!("candor: ignoring `unknown-alias {name}` — no valid reason-class");
215 } else {
216 out.insert(name.to_string(), set);
217 }
218 }
219 out
220}
221
222/// ⟨0.20⟩ Parse `net-partner <host>` lines from `.candor/config` (NET-DESTINATION-CLASS-DESIGN.md): the
223/// per-project set of business-partner hosts the `Net` destination-class classifier treats as
224/// `known-partner`. Multi-value (repeatable key); the value is host-normalized (`:port` stripped,
225/// lowercased) like `MODEL_HOSTS`. Case-insensitive key match, mirroring `parse_unknown_aliases` + the
226/// java/ts/swift config loaders. A partner is per-project — never a universal list.
227pub fn parse_net_partners(config_text: &str) -> BTreeSet<String> {
228 let mut out = BTreeSet::new();
229 for raw in config_text.lines() {
230 let line = raw.split('#').next().unwrap_or("").trim();
231 if line.is_empty() {
232 continue;
233 }
234 let mut it = line.splitn(2, char::is_whitespace);
235 if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("net-partner")) {
236 continue;
237 }
238 let val = it.next().unwrap_or("").trim();
239 if val.is_empty() {
240 continue;
241 }
242 // ⟨0.29⟩ A MALFORMED VALUE IS DISCLOSED, NOT SILENTLY KEPT AS JUNK. The grammar is
243 // `net-partner <host>`; the `=` spelling an operator reaches for by habit
244 // (`net-partner = partner.example`) parsed as the HOST `"= partner.example"`, which entered the
245 // set and matched nothing for the rest of the run. The direction is SAFE — the gate stays armed,
246 // so nothing is certified that should not be — which is precisely why it sat unnoticed: the
247 // operator believes a partner is declared, the verdict disagrees, and no line connects the two.
248 // ⟨0.28⟩ gave POLICY files an `ignored` block for exactly this; config files had none.
249 if val.contains(char::is_whitespace) || val.starts_with('=') {
250 eprintln!(
251 "candor: net-partner takes a bare host — `net-partner <host>`, one per line; \
252 '{val}' is not one and was IGNORED (an '=' or extra words is the usual cause) — {}",
253 raw.trim()
254 );
255 continue;
256 }
257 out.insert(host_part(val).to_ascii_lowercase());
258 }
259 out
260}
261
262/// Discover `.candor/config` text for a policy/scan anchored at `start`: `$CANDOR_CONFIG` if set + readable,
263/// else the nearest `.candor/config` walking UP from `start`, else `None`. Read-only + lenient (no
264/// process-exit — the caller decides fail-closed); used to resolve `unknown-alias` for the §6.2 gate +
265/// `parsepolicy` so both reflect the same checked-in config.
266pub fn discover_config_text(start: &std::path::Path) -> Option<String> {
267 discover_config(start).map(|(_, t)| t)
268}
269
270/// THE RUNNING BINARY'S REFUSAL WRITER, registered by whichever entry armed a sink.
271///
272/// (These paragraphs once sat ABOVE this static while documenting `discover_config`, which is below it —
273/// so rustdoc rendered that function's path/canonicalization rationale as a description of this hook.
274/// They now live on the item they describe: a doc block belongs to the next item, and separating it with
275/// a blank line is not a fix — clippy's `empty_line_after_doc_comments` rejects that, and CI said so.)
276///
277/// [`discover_config`] is SHARED and sits BELOW every gate sink, so its `exit(2)` for an unreadable
278/// config could not write the refusal document `--gate-json` was promised. Measured: on the `gate`
279/// verb route an unreadable `CANDOR_CONFIG` exited 2 with an EMPTY stream in candor-scan and
280/// candor-ts while candor-java and candor-swift wrote the refusal. The FILE sink was covered — the
281/// armed placeholder survives an exit that writes nothing — so only the stream, which cannot be
282/// pre-armed, was exposed.
283///
284/// NOT registered at startup: `set_refusal_sink` is called by the gate entries that arm a sink, so a
285/// process that never arms one still exits 2 plainly. The comment inside `discover_config` already
286/// records this cause being fixed once, for the EXIT
287/// CODE: the scan route refused and the query route did not. That fix stopped at the exit code and
288/// left the machine channel, which is exactly the split conformance PART 35 and PART 36 exist to
289/// keep apart. A hook rather than a Result because every caller of this function wants the same
290/// answer — refuse through whatever sink this process armed — and threading a new error type through
291/// all of them would create the second copy of a rule that this project keeps getting bitten by.
292static REFUSAL_SINK: std::sync::OnceLock<fn(&str) -> !> = std::sync::OnceLock::new();
293
294/// Register the process's refusal writer. Idempotent; the first registration wins.
295pub fn set_refusal_sink(f: fn(&str) -> !) {
296 let _ = REFUSAL_SINK.set(f);
297}
298
299/// Exit 2 through the registered sink when there is one, and plainly when there is not — a library
300/// consumer that never armed a sink must still get the documented exit code.
301fn refuse_unevaluable(reason: &str) -> ! {
302 if let Some(f) = REFUSAL_SINK.get() {
303 f(reason)
304 }
305 std::process::exit(2)
306}
307
308/// ⟨0.24⟩ As [`discover_config_text`], but ALSO the PATH the text came from, canonicalized.
309///
310/// **WHY THE PATH IS NOW LOAD-BEARING** (SPEC §3.1): a `.candor/config` supplying `unknown-alias`
311/// vocabulary can move a verdict 0→1, and discovery walks PARENT DIRECTORIES, so a file anywhere above
312/// the policy participates — ambient, and until now invisible in the output. *"A verdict changed by a
313/// file the operator cannot see named in the output is the ambient-input failure this whole format
314/// exists to refuse; the remedy is the same one used everywhere else here — not to forbid the input, but
315/// to make it impossible for it to act unnamed."* So the gate document NAMES it, and the path has to
316/// travel out of discovery for that to be possible.
317///
318/// CANONICALIZED because the two routes reach the same file from different working directories, and
319/// §3.1's byte-equality MUST is about the DOCUMENT: a relative path would differ between them for no
320/// reason other than where each was invoked.
321pub fn discover_config(start: &std::path::Path) -> Option<(std::path::PathBuf, String)> {
322 let canon = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
323 // CONFIGURED-BUT-UNUSABLE FAILS LOUD, ON THIS ROUTE TOO. `.ok()` turned an unreadable config into
324 // "no config", so the run continued WITHOUT whatever it declared — a policy, a baseline, an engine
325 // pin, an `unknown-alias` vocabulary. The SCAN route already refuses; this QUERY route did not, so
326 // `gate --report R --policy P` with a broken CANDOR_CONFIG exited 1 here and 2 in java and ts on the
327 // same input. §3.4's posture does not vary by verb.
328 if let Ok(p) = std::env::var("CANDOR_CONFIG") {
329 let p = std::path::PathBuf::from(p);
330 match std::fs::read_to_string(&p) {
331 Ok(t) => return Some((canon(&p), t)),
332 Err(e) => {
333 eprintln!("candor: CANDOR_CONFIG set but {} could not be read ({e}) — failing (exit 2,", p.display());
334 eprintln!(" unevaluable). A config that cannot be read is a guard the operator believes is on.");
335 refuse_unevaluable(&format!("CANDOR_CONFIG set but {} could not be read ({e})", p.display()));
336 }
337 }
338 }
339 let start = canon(start);
340 let mut cur = if start.is_dir() { Some(start.as_path()) } else { start.parent() };
341 while let Some(d) = cur {
342 let cand = d.join(".candor/config");
343 if cand.is_file() {
344 match std::fs::read_to_string(&cand) {
345 Ok(t) => return Some((canon(&cand), t)),
346 Err(e) => {
347 eprintln!("candor: {} exists but could not be read ({e}) — failing (exit 2,", cand.display());
348 eprintln!(" unevaluable). Treating it as absent would run without what it declares.");
349 refuse_unevaluable(&format!("{} exists but could not be read ({e})", cand.display()));
350 }
351 }
352 }
353 cur = d.parent();
354 }
355 None
356}
357
358/// One `deny <Effect…> [scope]` / `pure <scope>` rule (AS-EFF-006). `effects` empty ⇒ a `pure` rule
359/// (ANY effect forbidden). `scope` is a path segment-scope the rule applies to (None = whole unit).
360#[derive(Debug, Clone)]
361pub struct PolicyRule {
362 pub effects: BTreeSet<&'static str>,
363 pub scope: Option<String>,
364 /// Reason-class filter on an `Unknown` membership (REASON-SCOPED-UNKNOWN-DESIGN.md): empty ⇒
365 /// `Unknown[*]` (any reason — the bare form); non-empty ⇒ the Unknown hit fires ONLY for a fn whose
366 /// (transitive) reason classes include one of these. Ignored when `effects` doesn't contain `Unknown`.
367 pub unknown_classes: BTreeSet<ReasonClass>,
368 /// Destination-class filter on a `Net` membership (NET-DESTINATION-CLASS-DESIGN.md): empty ⇒ `Net[*]`
369 /// (any destination — the bare form); non-empty ⇒ the Net hit fires ONLY for a fn whose (transitive)
370 /// destination classes include one of these. Ignored when `effects` doesn't contain `Net`.
371 pub net_classes: BTreeSet<String>,
372 pub raw: String,
373}
374
375/// One `allow <Effect> [in <scope>] <literal>…` rule (AS-EFF-008). The effect is one of the four
376/// that carry a literal surface (`Net` hosts / `Exec` commands / `Fs` paths / `Db` tables); a
377/// function in `scope` performing it may reach ONLY the listed literals. Matching is
378/// effect-specific (`literal_allowed`).
379#[derive(Debug, Clone)]
380pub struct AllowRule {
381 pub effect: &'static str,
382 pub scope: Option<String>,
383 pub literals: BTreeSet<String>,
384 pub raw: String,
385}
386
387/// One `forbid <A> -> <B>` module-layering rule (AS-EFF-009): a function in scope `A` must not
388/// transitively call into scope `B`.
389#[derive(Debug, Clone)]
390pub struct LayerRule {
391 pub from: String,
392 pub to: String,
393 pub raw: String,
394}
395
396/// ⟨0.29⟩ One `only <A> -> <B> [<C> …]` PERMISSION rule (AS-EFF-011): a function in scope `A` may reach
397/// `A` itself and the listed scopes, and NOTHING else.
398///
399/// **`forbid` FAILS OPEN; `only` FAILS SAFE, and that is the whole reason the form exists.** A dependency
400/// you forgot to prohibit is silently permitted, so "this package is a leaf" can only be spelled by
401/// enumerating what it must not reach — a list that does not cover a package added later, and nothing says
402/// so. That is the allowlist hazard this project refuses everywhere in the analysis, living in the POLICY
403/// LANGUAGE instead. Under `only`, a dependency you forgot to permit is a loud violation.
404///
405/// Found by pointing candor's own architecture gate at candor: the natural
406/// `forbid io.poly.candor.model -> io.poly.candor` SELF-FIRES at 58 violations, because a scope matches a
407/// contiguous run of segments and `model` sits under the very prefix it is trying to protect itself from.
408///
409/// THE WALK STOPS AT A PERMITTED SCOPE, and that is a semantic decision rather than an optimisation: a
410/// permitted callee's own dependencies are governed by the rules about IT, not by this one. Descending
411/// past it would make `only` require the transitive closure of everything you permit — which is the
412/// enumeration-that-rots this form exists to replace, one level down.
413#[derive(Debug, Clone)]
414pub struct OnlyRule {
415 /// The scope being constrained. It may always reach ITSELF: an explicit `A -> A` would be noise, and
416 /// without the implicit permission the form is unusable for exactly the case it exists for.
417 pub from: String,
418 /// The scopes `from` may reach. At least one — `only A ->` with nothing after the arrow is DROPPED as
419 /// malformed rather than read as "A may reach nothing at all", which is a different rule (and one a
420 /// reader is far more likely to have typed by accident than to have meant).
421 pub to: Vec<String>,
422 pub raw: String,
423}
424
425/// ⟨0.24⟩ ONE POLICY LINE THE PARSER DID NOT HONOUR AS WRITTEN (SPEC §3.1 `901f14d` / `195d45a`).
426///
427/// **THE DEFECT.** `parsepolicy` emitted **no `errors` key at all** (measured 2026-07-28 on the
428/// conformance battery: java 10, ts 4, rust 0, swift 0). Every one of these facts existed — they were
429/// printed to stderr as "ignoring policy rule …" — so the verb whose entire purpose is to let a consumer
430/// diff what an engine made of a policy answered the question with the not-honoured half deleted. Worse,
431/// it was INCONSISTENT with this engine's own gate: the gate refuses an unrecognised class token while
432/// the parse narrowed it silently, which is two answers to one question.
433///
434/// **`kind` IS A CLOSED SET, AND IT IS THE SPEC'S, NOT THE REFERENCE ENGINE'S.** `901f14d` pins four
435/// values: `reason-class/alias`, `Net destination-class`, `effect-name`, `rule-kind`. Measured, candor-java
436/// emits `forbid form`, `allow values` and `rule kind` (space, not hyphen) — three values outside the set
437/// and one spelling divergence — and candor-ts renames `kind`→`vocabulary` and `rule`→`where` and emits
438/// `accepted` as a PROSE STRING. This engine follows the clause: a line that names a rule keyword but does
439/// not form that keyword's rule formed no rule kind, so it is `rule-kind`.
440///
441/// `accepted` is an ARRAY OF TOKENS — the tokens that WOULD have been honoured in the position the bad one
442/// occupies. Empty where the position is open-ended (a host, a path), which is a fact about the grammar
443/// rather than a gap in the report.
444#[derive(Debug, Clone)]
445pub struct PolicyError {
446 /// One of [`PolicyError::KIND_REASON_CLASS`], [`PolicyError::KIND_NET_CLASS`],
447 /// [`PolicyError::KIND_EFFECT_NAME`], [`PolicyError::KIND_RULE_KIND`].
448 pub kind: &'static str,
449 /// The offending token, verbatim. Empty when the position was EMPTY (a missing arrow, an `allow` with
450 /// no values) — which is itself the finding.
451 pub token: String,
452 /// The tokens accepted in that position. Empty ⇒ the position takes an open-ended literal.
453 pub accepted: Vec<String>,
454 /// The raw policy line, verbatim.
455 pub rule: String,
456 /// The human sentence — the same text the stderr channel carries, so the two cannot disagree.
457 pub message: String,
458 /// ⟨0.28⟩ The 1-based SOURCE LINE the error sits on — SPEC §6.2 pins the verdict's `ignored`
459 /// disclosure as `[{ line, text, reason }]`, and a consumer's next action is to go to that line.
460 /// Counted over the normalized text (bare `\r` line breaks count like `\n`, matching the split).
461 pub line: usize,
462 /// ⟨0.28⟩ The source line VERBATIM — before comment-stripping and trimming, unlike `rule`, because
463 /// §6.2's `text` is "the source line, verbatim" and the operator matches it against their file.
464 pub text: String,
465 /// ⟨0.24⟩ Does this error make the policy UNHONOURABLE, so every gate route must refuse (exit 2)?
466 ///
467 /// FATAL and REPORTED are different questions and this field is the only place they are told apart.
468 /// A dropped `nonsense line` is reported and survivable — the rest of the policy means what it says.
469 /// A rewritten `deny Unknown[dispatch,nativ]` is not: the rule that RAN is not the rule that was
470 /// written, and the direction that matters NARROWS it.
471 pub fatal: bool,
472}
473
474impl PolicyError {
475 pub const KIND_REASON_CLASS: &'static str = "reason-class/alias";
476 pub const KIND_NET_CLASS: &'static str = "Net destination-class";
477 pub const KIND_EFFECT_NAME: &'static str = "effect-name";
478 pub const KIND_RULE_KIND: &'static str = "rule-kind";
479}
480
481/// The rule kinds parsed from a CANDOR_POLICY file.
482#[derive(Default, Debug)]
483pub struct ParsedPolicy {
484 pub rules: Vec<PolicyRule>,
485 pub allow_rules: Vec<AllowRule>,
486 pub layer_rules: Vec<LayerRule>,
487 /// ⟨0.29⟩ the `only <A> -> <B> …` permission rules — see [`OnlyRule`]. Kept in their own list rather
488 /// than folded into `layer_rules` because the two read OPPOSITE ways: a `forbid` names what must not
489 /// happen, an `only` names the complete set of what may, so a route that handled one as the other
490 /// would inverse the verdict rather than approximate it.
491 pub only_rules: Vec<OnlyRule>,
492 /// ⟨0.24⟩ POLICY ERRORS — a policy that cannot be honoured AS WRITTEN (SPEC §6.2). Non-empty ⇒ every
493 /// gate route MUST refuse: exit 2, the unreadable-policy posture. Not a warning list: the rules in
494 /// `rules` are what the text would mean if the error were tolerated, and tolerating it is the defect.
495 ///
496 /// Today the only member is an unrecognised reason-class/alias token in an `Unknown[…]` filter. The
497 /// asymmetry that used to justify a warning — "a dropped policy token leaves a WIDER rule standing,
498 /// so the failure is loud" — is false in the case that matters, and the false half is FAIL-OPEN:
499 ///
500 /// - `deny Unknown[corp]` (sole unrecognised token) — the filter empties and the rule WIDENS to a
501 /// bare `deny Unknown`, while the engine prints "ignoring policy rule" and then KEEPS and
502 /// re-scopes it. Merely surprising, but a FALSE DISCLOSURE.
503 /// - `deny Unknown[dispatch,nativ]` (a typo BESIDE valid tokens) — the token is dropped, the rule
504 /// NARROWS to `[dispatch]`, and it stops gating native-caused holes entirely while the operator
505 /// reads a gate that looks armed. **That is the fail-open, and it is the common case: a typo
506 /// lands beside correct tokens far more often than alone.**
507 ///
508 /// A policy that cannot be honoured as written is not silently rewritten into a different policy.
509 ///
510 /// ⟨0.24⟩ THIS LIST NOW HOLDS EVERY LINE THE PARSER DID NOT HONOUR, fatal or not (SPEC §3.1
511 /// `195d45a`) — `parsepolicy` reports them all, and the gate routes refuse on
512 /// [`ParsedPolicy::fatal_messages`] alone. Widening the LIST without widening what REFUSES is the
513 /// whole of the change: a dropped `nonsense line` was always survivable and stays so.
514 pub errors: Vec<PolicyError>,
515 /// ⟨0.24⟩ The `.candor/config` `unknown-alias` definitions this policy actually resolved a token
516 /// through (SPEC §3.1) — **name → the reason-class TOKENS it expanded to**, not a bare name list.
517 /// Non-empty ⇒ a config file supplied vocabulary that PARTICIPATED in the verdict, and the
518 /// `--gate-json` document MUST name that file. Recorded at the point of USE, not from the alias map:
519 /// a config defining ten aliases none of which the policy mentions changed nothing, and naming it
520 /// would train the reader to ignore the field.
521 ///
522 /// ⟨0.24⟩ **THE VALUE TRAVELS WITH THE NAME, AND THAT IS A SPEC MUST** (§3.1, candor-spec `7f5b5ba`).
523 /// This engine shipped the bare name — as did java and swift — and candor-ts kept the map and won the
524 /// argument from the clause's OWN sentence: `configSources: [path]` is rejected there because *a
525 /// disclosure that names the source but not the content leaves the reader knowing they were affected
526 /// and not how*, and `["corp"]` fails that same test one level down. **`corp = reflect` and
527 /// `corp = reflect,native` gate DIFFERENTLY under one unchanged policy line**, so a reader given only
528 /// the name cannot tell which gate ran. The map is a strict superset — the keys recover the old array.
529 ///
530 /// Class TOKENS rather than `ReasonClass`, so the wire order is the token's alphabetical one (which
531 /// is what candor-ts's `[...set].sort()` produces) and not `ReasonClass`'s declaration order.
532 pub used_aliases: BTreeMap<String, BTreeSet<String>>,
533}
534
535impl ParsedPolicy {
536 /// ⟨0.24⟩ The messages of the errors that make the policy UNHONOURABLE — what every gate route
537 /// refuses on. Non-empty ⇒ exit 2, the unreadable-policy posture.
538 ///
539 /// Separate from `errors` because REPORTED and FATAL are different questions, and conflating them in
540 /// either direction is a defect: refusing on every dropped line would make `nonsense line` fail a
541 /// build, and reporting only the fatal ones is the silent narrowing this rung exists to close.
542 pub fn fatal_messages(&self) -> Vec<&str> {
543 self.errors.iter().filter(|e| e.fatal).map(|e| e.message.as_str()).collect()
544 }
545}
546
547/// The hostname part of a `host[:port]` literal, port stripped — so `api.stripe.com` in a rule accepts
548/// a reached `api.stripe.com:443`. IPv6-aware: a bracketed `[host]:port` yields the bracketed host, and
549/// a BARE IPv6 literal (>1 colon, no brackets) has no port to strip and is returned whole — a naive
550/// first-colon split collapsed every `2001:db8::*` to `2001`, so one allowed IPv6 accepted any address
551/// in that block (/code-review). A hostname/IPv4 `host` or `host:port` (≤1 colon) splits at the colon.
552pub fn host_part(h: &str) -> &str {
553 if let Some(rest) = h.strip_prefix('[') {
554 // `[ipv6]` or `[ipv6]:port` — the host is between the brackets.
555 return rest.split(']').next().unwrap_or(rest);
556 }
557 if h.matches(':').count() > 1 {
558 return h; // bare IPv6 literal — no port suffix to strip
559 }
560 h.split(':').next().unwrap_or(h)
561}
562
563/// The basename of a command (`/usr/bin/git` → `git`), so `allow Exec … git` accepts an absolute path.
564pub fn cmd_base(c: &str) -> &str {
565 c.rsplit(['/', '\\']).next().unwrap_or(c)
566}
567
568/// Whether an allowed path `a` covers a reached path `r` (SPEC §6.2: path-boundary-respecting prefix).
569/// A directory covers itself and everything beneath it, but NOT a sibling sharing a textual prefix
570/// (`/etc/app` ⊉ `/etc/apppwned`); a `..` that climbs out is never covered; absolute/relative are
571/// never conflated.
572pub fn fs_path_covered(a: &str, r: &str) -> bool {
573 if r.split(['/', '\\']).any(|c| c == "..") {
574 return false;
575 }
576 let absolute = |s: &str| s.starts_with('/') || s.starts_with('\\');
577 if absolute(a) != absolute(r) {
578 return false;
579 }
580 let norm = |s: &str| -> Vec<String> {
581 s.split(['/', '\\'])
582 .filter(|c| !c.is_empty() && *c != ".")
583 .map(|c| c.to_string())
584 .collect()
585 };
586 let (ac, rc) = (norm(a), norm(r));
587 ac.len() <= rc.len() && ac.iter().zip(&rc).all(|(x, y)| x == y)
588}
589
590/// Whether an allowed table entry `a` covers a reached table `r` (SPEC §6.2): case-insensitive
591/// exact match on the (possibly schema-qualified) name, or a `schema.*` entry covering every table
592/// in that schema. Strict on qualification — an allowed `entries` does NOT cover a reached
593/// `ledger.entries` (write both forms if your queries mix them); silent widening is the failure
594/// mode an allowlist exists to prevent.
595pub fn db_table_covered(a: &str, r: &str) -> bool {
596 let (a, r) = (a.to_lowercase(), r.to_lowercase());
597 if let Some(schema) = a.strip_suffix(".*") {
598 return r.strip_prefix(schema).is_some_and(|rest| rest.starts_with('.'));
599 }
600 a == r
601}
602
603/// Whether a reached literal is allowed under an effect-specific match (SPEC §6.2): `Net` host by
604/// name (port ignored), `Exec` command by basename, `Fs` path by boundary-respecting prefix,
605/// `Db` table by qualified name or `schema.*`.
606pub fn literal_allowed(effect: &str, reached: &str, allow: &BTreeSet<String>) -> bool {
607 match effect {
608 // `Llm` ⟨0.13⟩ rides the Net host literal (SPEC §1) — matched by hostname like `Net`.
609 "Net" | "Llm" => allow.iter().any(|a| host_part(a) == host_part(reached)),
610 "Exec" => allow.iter().any(|a| cmd_base(a) == cmd_base(reached)),
611 "Fs" => allow.iter().any(|a| fs_path_covered(a, reached)),
612 "Db" => allow.iter().any(|a| db_table_covered(a, reached)),
613 _ => allow.contains(reached),
614 }
615}
616
617/// Split a function name (or scope) into PATH SEGMENTS on either separator. Reports reach the Rust gate
618/// AND `candor-query` from BOTH the Rust engines (`::`-separated names) and the JVM/Swift/TS engines
619/// (`.`-separated names — `candor-query` is explicitly built to read them). Segmenting on `::` ALONE
620/// left a scoped `deny`/`pure` rule silently INERT on a dotted name: the scope matched nothing, so
621/// `whatif` returned a false green on the security boundary (gate-evasion). The JVM engine's own
622/// `scopeMatches` already splits on `.`; this aligns the Rust side. A `:`/`.` never appears WITHIN a
623/// real segment, so splitting on both never over-segments a Rust name (no spurious match).
624fn name_segments(s: &str) -> Vec<&str> {
625 s.split(['.', ':']).filter(|p| !p.is_empty()).collect()
626}
627
628/// A policy scope matches a function name by **path segment** (SPEC §6.2), not substring: split both
629/// into segments (on `::` or `.`); the scope matches a contiguous run of name-segments where every
630/// segment except the last matches exactly and the last is a prefix. So `domain` matches
631/// `app::domain::h`, `com.acme.domain.h`, and `domain_logic` but not `subdomain`.
632/// ⟨0.29⟩ SCOPE MATCHING FOR A **PERMISSION**, where the prefix rule is FAIL-OPEN.
633///
634/// [`scope_matches`]'s last segment is a PREFIX of its name-segment, so `util` matches `utilities`. For
635/// `deny`/`pure`/`forbid` that widening is FAIL-CLOSED — a scope that matches more forbids more — and it
636/// is why the rule exists. For the `to` list of an `only` rule it is the exact inverse: a permitted scope
637/// that matches more PERMITS more, so the matcher that keeps every other rule kind safe silently widens
638/// the one form whose entire purpose is to fail safe.
639///
640/// MEASURED on the shipped ⟨0.29⟩ implementation, before this function existed:
641///
642/// ```text
643/// only model -> util `model::go` reaching `utilities_untrusted::exfil` → policy ✓
644/// forbid model -> util the identical reach → AS-EFF-009
645/// ```
646///
647/// The operator wrote a complete permission list and the matcher quietly extended it to anything sharing
648/// a prefix with an entry. So a `to` scope matches by EXACT segment run, with no prefix on the last —
649/// `only a -> util` permits `util::x` and `crate::util::x`, and does NOT permit `utilities_untrusted::x`.
650///
651/// THE `from` SIDE KEEPS THE PREFIX RULE, deliberately: `from` selects which functions the rule BINDS, so
652/// matching more constrains more, which is the safe direction. The asymmetry is the point — each side
653/// takes the matcher whose over-approximation errs toward the gate firing.
654pub fn scope_matches_permitted(name: &str, scope: &str) -> bool {
655 let segs = name_segments(name);
656 let parts = name_segments(scope);
657 if parts.is_empty() || parts.len() > segs.len() {
658 return false;
659 }
660 segs.windows(parts.len()).any(|w| w == parts.as_slice())
661}
662
663pub fn scope_matches(name: &str, scope: &str) -> bool {
664 let segs = name_segments(name);
665 let parts = name_segments(scope);
666 if parts.is_empty() || parts.len() > segs.len() {
667 return false;
668 }
669 let (last, init) = parts.split_last().unwrap();
670 segs.windows(parts.len()).any(|w| {
671 let (w_last, w_init) = w.split_last().unwrap();
672 w_init == init && w_last.starts_with(last)
673 })
674}
675
676/// Reconstruct a rule's source form and the `Unknown`-forbidding upgrade for it: `pure <scope>` →
677/// (`"pure <scope>"`, `"deny Unknown <scope>"`); `deny <E…> <scope>` → (`"deny <E…> <scope>"`,
678/// `"deny <E…> Unknown <scope>"`). Shared so the gate note and `candor unverified` name the identical
679/// rule and upgrade — one source of truth for the disclosure's advice.
680///
681/// ⟨0.24⟩ **THE NARROWING FILTERS ARE RENDERED, and they had to start being rendered in the same commit
682/// that made them REACHABLE here.** Making `unverified_hole_rule` filter-aware is what first lets a
683/// `deny Unknown[reflect]` / `deny Net[unknown-host]` rule be the rule a hole is disclosed under — and
684/// this reconstruction dropped the bracket, so the fix would have printed the operator's narrowed rule
685/// back to them as the WIDE one (`deny Unknown`) and advised the nonsense upgrade `deny Unknown
686/// Unknown`. That is the same mis-attribution `whatif` carries, arriving through the fix for a different
687/// defect: the hazard on this rung is that each correction manufactures its own mirror, so the rendering
688/// moves with the predicate rather than after it.
689///
690/// A rule carrying NO filter renders byte-identically to before, which is what keeps conformance PARTs
691/// 12c/12d (`deny Db Net Unknown domain`, four-way) unmoved.
692///
693/// THE UPGRADE SPLITS on whether the rule already denies `Unknown`. If it does, it can only be here
694/// NARROWED — a bare `deny … Unknown` fires on every `Unknown`, so the function would be a violation and
695/// not a hole — and the upgrade is that term WIDENED to bare `Unknown`, not a second `Unknown` appended.
696pub fn rule_and_upgrade(r: &PolicyRule) -> (String, String) {
697 let scope = r.scope.clone().unwrap_or_default();
698 let suffix = if scope.is_empty() { String::new() } else { format!(" {scope}") };
699 if r.effects.is_empty() {
700 // `pure` forbids real effects but not Unknown; to REQUIRE provable purity, add a deny-Unknown.
701 return (format!("pure{suffix}"), format!("deny Unknown{suffix}"));
702 }
703 // One effect term, with its narrowing filter if it has one. Class tokens sorted by TOKEN string, as
704 // `parsepolicy` sorts them and as the java reference's `.sorted()` does — the dump and the
705 // disclosure must spell one rule one way.
706 let term = |e: &str| -> String {
707 if e == UNKNOWN && !r.unknown_classes.is_empty() {
708 let mut t: Vec<&str> = r.unknown_classes.iter().map(|c| c.token()).collect();
709 t.sort_unstable();
710 format!("{UNKNOWN}[{}]", t.join(","))
711 } else if e == "Net" && !r.net_classes.is_empty() {
712 format!("Net[{}]", r.net_classes.iter().map(String::as_str).collect::<Vec<_>>().join(","))
713 } else {
714 e.to_string()
715 }
716 };
717 let effs = r.effects.iter().map(|e| term(e)).collect::<Vec<_>>().join(" ");
718 if r.effects.contains(UNKNOWN) {
719 let widened =
720 r.effects.iter().map(|e| if *e == UNKNOWN { UNKNOWN.to_string() } else { term(e) }).collect::<Vec<_>>();
721 (format!("deny {effs}{suffix}"), format!("deny {}{suffix}", widened.join(" ")))
722 } else {
723 (format!("deny {effs}{suffix}"), format!("deny {effs} {UNKNOWN}{suffix}"))
724 }
725}
726
727/// The single predicate for a provable-purity hole (eval/fixloop/DISPATCH-NOTE.md): a function that is
728/// `Unknown`, sits in a `pure`/`deny <E>` scope, and PASSES that rule (carries none of its forbidden real
729/// effects) — so its compliance is asserted but not verified (the Unknown could hide the very effect the
730/// rule forbids; the classic case is a fn/closure-injected port). A *real* violation is the gate's job, not
731/// this. Returns the first governing rule under which the function is such a hole, or `None` if it is not
732/// one. Shared by candor-scan's gate note and candor-query's `unverified` so "what a hole is" has ONE
733/// definition — the two paths can never drift (conformance PART 12d pins their agreement).
734///
735/// ⟨0.24⟩ **"PASSES" IS NOW ASKED OF THE GATE, NOT OF A SECOND COPY OF IT.** This predicate computed the
736/// passing test from `r.effects` alone — "does the rule NAME an effect this function has?" — which is
737/// the pre-⟨0.19⟩ question, still being asked after two rungs gave rules a NARROWING FILTER. So on
738/// `deny Unknown[reflect]` over an `indirect` hole the gate TOLERATED (exit 0, the class does not match)
739/// while this read the same rule as violated; and a hole is *by definition* a function that PASSES its
740/// rule while `Unknown`, so the real hole was reclassified as a violation-that-isn't and **deleted from
741/// the disclosure** — `unverified` answering "every function in a pure/deny layer is PROVABLY clean ✓"
742/// over a function the gate had just declined to clear. MEASURED 2026-07-28, and reachable with no alias
743/// in play at all: one layer below the widening `ea0df4f` closed, in the same four verbs.
744///
745/// It now calls [`crate::gate::rule_hits`] — the gate's own firing decision — so the two cannot disagree
746/// again. That needs the function's TRANSITIVE reason classes and its ⟨0.20⟩ destination classes, the
747/// same two accumulators the gate reads, which is why they are parameters now rather than derivable.
748///
749/// **THE DIRECTION IS THE MIRROR ARGUMENT.** A filter can only ever SHRINK what a rule charges, so a
750/// filter-aware pass test can only ever find MORE holes — this cannot silently suppress a disclosure
751/// that used to appear. Pinned in both directions by
752/// `a_narrowed_rule_the_gate_tolerates_is_a_hole_and_the_one_it_fires_on_is_not`, in one run, because
753/// the fixture proving the fabrication is closed cannot show the reach closed with it. A WITHHELD filter
754/// — nothing to read — likewise counts as PASSING here: the gate did not clear the function, and an
755/// advisory note's fail-safe direction is to disclose.
756pub fn unverified_hole_rule<'a, S: AsRef<str>>(
757 name: &str,
758 effects: &[S],
759 reason_classes: Option<&BTreeSet<String>>,
760 net_classes: &[String],
761 rules: &'a [PolicyRule],
762) -> Option<&'a PolicyRule> {
763 if !effects.iter().any(|e| e.as_ref() == UNKNOWN) {
764 return None;
765 }
766 let effs: Vec<&str> = effects.iter().map(AsRef::as_ref).collect();
767 rules.iter().find(|r| {
768 // in the rule's scope (a scopeless rule governs the whole unit) …
769 if let Some(s) = &r.scope {
770 if !scope_matches(name, s) {
771 return false;
772 }
773 }
774 // … and PASSES it — the gate's own answer, narrowing filters and all. Empty `hits` IS passing.
775 crate::gate::rule_hits(r, &effs, reason_classes, net_classes).hits.is_empty()
776 })
777}
778
779/// Parse a CANDOR_POLICY file (SPEC §6.2). One rule per line; `#` comments and blanks ignored:
780///
781/// ```text
782/// deny Net Db domain # functions whose path contains segment "domain" must not perform Net or Db
783/// deny Exec # no function anywhere may perform Exec
784/// deny Unknown api # functions in "api" must be fully resolvable (forbid the unverifiable)
785/// pure parse # functions whose path contains segment "parse" must be effect-free
786/// allow Net in billing api.stripe.com
787/// forbid domain -> infra
788/// ```
789///
790/// In a `deny` rule, leading tokens that name a known effect (or `Unknown`) are forbidden; the FIRST
791/// non-effect token is the scope and ends the rule. A `deny` naming no known effect is dropped (it is
792/// NOT a `pure` rule). Malformed/unknown lines are ignored with a warning — never silently widened.
793/// The §6.2 token separator: ASCII whitespace ONLY (space/tab/CR/LF/VT/FF). `split_whitespace`/`trim`
794/// use Unicode `White_Space`, which would split a NBSP/ideographic space that Java drops — a gateless-
795/// green cross-engine divergence (adversarial DSL review). A non-ASCII space stays part of its token, so
796/// the rule is malformed and ignored, uniformly.
797fn is_ascii_ws(c: char) -> bool {
798 matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
799}
800
801pub fn parse_policy(text: &str) -> ParsedPolicy {
802 parse_policy_impl(text, true, &std::collections::BTreeMap::new())
803}
804/// As [`parse_policy`] but with `.candor/config` `unknown-alias` definitions (⟨0.19⟩, SPEC §6.2): an
805/// `Unknown[<name>]` filter resolves a user-defined `<name>` to its reason classes. The gate + `parsepolicy`
806/// pass the discovered aliases (via [`parse_unknown_aliases`]); a config alias never changes what bare
807/// `deny E Unknown` means (always `Unknown[*]`), so the rule stays legible from the policy alone.
808pub fn parse_policy_with_aliases(text: &str, aliases: &std::collections::BTreeMap<String, std::collections::BTreeSet<ReasonClass>>) -> ParsedPolicy {
809 parse_policy_impl(text, true, aliases)
810}
811/// ⟨0.24⟩ [`parse_policy_with_aliases`] but SILENT — for a caller that must inspect
812/// [`ParsedPolicy::errors`] / [`ParsedPolicy::used_aliases`] BEFORE it parses for real (candor-scan
813/// refuses before touching the classifier's accumulators). Silent so the ordinary parse warnings are not
814/// printed twice on the same text.
815pub fn parse_policy_silent(
816 text: &str,
817 aliases: &std::collections::BTreeMap<String, BTreeSet<ReasonClass>>,
818) -> ParsedPolicy {
819 parse_policy_impl(text, false, aliases)
820}
821/// Same as [`parse_policy`] but SILENT about malformed rules — for a SECOND, advisory re-parse within the
822/// same run (candor-scan parses once for the gate check and again for the `unverified` disclosure), so the
823/// CI log doesn't print every "ignoring policy rule …" warning twice (#21). The first parse already warned.
824pub fn parse_policy_quiet(text: &str) -> ParsedPolicy {
825 parse_policy_impl(text, false, &std::collections::BTreeMap::new())
826}
827fn parse_policy_impl(text: &str, warn: bool, aliases: &std::collections::BTreeMap<String, std::collections::BTreeSet<ReasonClass>>) -> ParsedPolicy {
828 macro_rules! warn_ignore { ($($a:tt)*) => { if warn { eprintln!($($a)*); } } }
829 let mut out = ParsedPolicy::default();
830 // ⟨0.28⟩ The source position of the line under the cursor, for `PolicyError::{line, text}` — bound
831 // BEFORE the macro below so its body (whose free identifiers resolve at definition scope) can read
832 // them; the loop updates both per iteration. §6.2's `ignored` disclosure is `[{line, text, reason}]`.
833 let mut cur_line: usize;
834 let mut cur_text: &str;
835 // ⟨0.24⟩ Record a line the parser did not honour (SPEC §3.1 `195d45a`), on the ONE list `parsepolicy`
836 // reports and the gate routes filter for `fatal`. The stderr sentence and `message` are the SAME
837 // string by construction — a disclosure that can drift from the one beside it is how this family
838 // produced a FALSE disclosure once already (conformance PART 13b).
839 macro_rules! not_honoured {
840 ($fatal:expr, $kind:expr, $token:expr, $accepted:expr, $rule:expr, $msg:expr) => {{
841 let message: String = $msg;
842 out.errors.push(PolicyError {
843 kind: $kind,
844 token: ($token).to_string(),
845 accepted: ($accepted).iter().map(|s: &&str| s.to_string()).collect(),
846 rule: ($rule).to_string(),
847 message,
848 line: cur_line,
849 text: cur_text.to_string(),
850 fatal: $fatal,
851 });
852 }};
853 }
854 // `str::lines()` splits on \n and \r\n but NOT bare \r — a classic-Mac file then collapses to ONE
855 // line, and since \r is also an in-line ASCII-ws token separator (is_ascii_ws), every rule after the
856 // first was glued into the first rule's tokens and dropped (sweep [16], a gateless-green divergence).
857 // Java's Files.readAllLines (the reference) breaks on bare \r too — normalize to match it. Allocation
858 // only when a bare \r is actually present (the overwhelmingly-common \n / \r\n files are untouched).
859 let normalized;
860 let text = if text.contains('\r') {
861 normalized = text.replace("\r\n", "\n").replace('\r', "\n");
862 normalized.as_str()
863 } else {
864 text
865 };
866 for (line_idx, raw_line) in text.lines().enumerate() {
867 cur_line = line_idx + 1;
868 cur_text = raw_line;
869 let line = raw_line.split('#').next().unwrap_or("").trim_matches(is_ascii_ws);
870 if line.is_empty() {
871 continue;
872 }
873 let mut toks = line.split(is_ascii_ws).filter(|s| !s.is_empty());
874 match toks.next().unwrap_or("") {
875 "allow" => {
876 let effect = match toks.next().unwrap_or("") {
877 "Net" => "Net",
878 // `Llm` ⟨0.13⟩ rides the Net host literal (SPEC §1) — `allow Llm <host…>` restricts which
879 // MODEL hosts a scope may reach, matched by hostname like Net (its reached surface IS the
880 // Net host surface). Match candor-java's Policy.parsePolicy.
881 "Llm" => "Llm",
882 "Exec" => "Exec",
883 "Fs" => "Fs",
884 "Db" => "Db",
885 other => {
886 let msg = format!(
887 "unknown effect-name `{other}` in `allow` (accepted: Db, Exec, Fs, Llm, Net \
888 \u{2014} `allow` covers only the effects carrying a literal surface: Net/Llm \
889 hosts, Exec commands, Fs paths, Db tables): {line}"
890 );
891 warn_ignore!("candor: policy error — {msg}");
892 // ⟨0.24⟩ FATAL (SPEC §6.2 `1e1748a`). MEASURED four-way before this:
893 // `allow Nett host.example` -> exit 0 on rust, ts, java AND swift. The rule is
894 // DELETED and the certification silently vanishes, so the operator reads an
895 // armed allowlist that does not exist.
896 //
897 // The grammar defence that kept the token rule inside the bracket does NOT
898 // reach here: `allow`'s effect position is a fixed, closed set with **no scope
899 // reading available**, so an unrecognised token there is unambiguously a typo
900 // and there is no legitimate policy it could be. This document already calls a
901 // dropped rule "the limit case of silently rewritten into a different policy…
902 // a bigger rewrite than a narrowed filter" — and the bigger rewrite was
903 // warning-only while the smaller one was already exit 2.
904 not_honoured!(
905 true,
906 PolicyError::KIND_EFFECT_NAME,
907 other,
908 ["Db", "Exec", "Fs", "Llm", "Net"],
909 line,
910 msg
911 );
912 continue;
913 }
914 };
915 let mut rest: Vec<&str> = toks.collect();
916 let scope = if rest.first() == Some(&"in") {
917 let s = rest.get(1).map(|s| s.to_string());
918 rest.drain(..2.min(rest.len()));
919 s
920 } else {
921 None
922 };
923 let literals: BTreeSet<String> = rest.iter().map(|h| h.to_string()).collect();
924 if literals.is_empty() {
925 let msg = format!("`allow {effect}` names no values: {line}");
926 warn_ignore!("candor: ignoring policy rule ({msg})");
927 // `accepted` is EMPTY on purpose: the position takes an open-ended literal (a host, a
928 // path, a command, a table), so there is no token list to offer. A fact about the
929 // grammar, not a gap in the report.
930 not_honoured!(false, PolicyError::KIND_RULE_KIND, "", [], line, msg);
931 continue;
932 }
933 out.allow_rules.push(AllowRule { effect, scope, literals, raw: line.to_string() });
934 }
935 "deny" => {
936 let mut effects = BTreeSet::new();
937 let mut scope = None;
938 // Reason-class filter on `Unknown` (REASON-SCOPED-UNKNOWN-DESIGN.md): empty ⇒ `Unknown[*]`
939 // (any reason — the bare form); non-empty ⇒ only those classes. `*` = all.
940 let mut unknown_classes: BTreeSet<ReasonClass> = BTreeSet::new();
941 let mut unknown_star = false;
942 // Destination-class filter on `Net` (NET-DESTINATION-CLASS-DESIGN.md): empty ⇒ `Net[*]`
943 // (any destination — the bare form); non-empty ⇒ only those classes. `*` = all.
944 let mut net_classes: BTreeSet<String> = BTreeSet::new();
945 let mut net_star = false;
946 for t in toks {
947 // `Net[unknown-host]` / `Net[*]` / `Net[known-telemetry,unknown-host]`: the destination-scoped form.
948 if let Some(inner) = t.strip_prefix("Net[").and_then(|s| s.strip_suffix(']')) {
949 effects.insert("Net");
950 for cn in inner.split(',') {
951 let cn = cn.trim();
952 if cn.is_empty() {
953 continue;
954 }
955 if cn == "*" {
956 net_star = true;
957 } else if crate::NET_DEST_CLASSES.contains(&cn) {
958 net_classes.insert(cn.to_string());
959 } else {
960 // ⟨0.24⟩ A POLICY ERROR, not a warning — SPEC §6.2 `be0b9a9`. Byte-identical
961 // in shape to the reason-class arm below, and byte-identical in harm:
962 // MEASURED `deny Net[known-telemetry,unknown-hosst]` → exit 0 where the
963 // correctly-spelled rule exits 1. The typo is dropped, the filter NARROWS
964 // to `[known-telemetry]`, and the gate stops covering unidentifiable
965 // destinations while the operator reads a gate that looks armed.
966 not_honoured!(
967 true,
968 PolicyError::KIND_NET_CLASS,
969 cn,
970 ["known-telemetry", "known-partner", "unknown-host", "*"],
971 line,
972 format!(
973 "unrecognised Net destination-class `{cn}` in `{line}` — \
974 accepted: known-telemetry, known-partner, unknown-host, plus `*`"
975 )
976 );
977 }
978 }
979 continue;
980 }
981 // `Unknown[dispatch,reflect]` / `Unknown[*]` / `Unknown[dynamic]`: the reason-scoped form.
982 if let Some(inner) = t.strip_prefix("Unknown[").and_then(|s| s.strip_suffix(']')) {
983 effects.insert(UNKNOWN);
984 for cn in inner.split(',') {
985 let cn = cn.trim();
986 if cn.is_empty() {
987 continue;
988 }
989 if cn == "*" {
990 unknown_star = true;
991 } else if cn == "dynamic" {
992 unknown_classes.extend(ReasonClass::dynamic_set());
993 } else if let Some(rc) = ReasonClass::from_token(cn) {
994 unknown_classes.insert(rc);
995 } else if let Some(a) = aliases.get(cn) {
996 unknown_classes.extend(a.iter().copied()); // ⟨0.19⟩ config `unknown-alias`
997 // ⟨0.24⟩ → the verdict names it AND what it expanded to (SPEC §3.1
998 // `7f5b5ba`): the NAME alone cannot tell a reader which gate ran.
999 out.used_aliases
1000 .insert(cn.to_string(), a.iter().map(|c| c.token().to_string()).collect());
1001 } else {
1002 // ⟨0.24⟩ A POLICY ERROR, not a warning — see `ParsedPolicy::errors`. The
1003 // token is still dropped below so `rules` stays well-formed for the
1004 // advisory readers (`unverified`, `parsepolicy`); the gate routes refuse
1005 // on `errors` before any of it is used as a verdict.
1006 not_honoured!(
1007 true,
1008 PolicyError::KIND_REASON_CLASS,
1009 cn,
1010 [
1011 "reflect",
1012 "dispatch",
1013 "indirect",
1014 "native",
1015 "unresolved",
1016 "setup",
1017 "dynamic",
1018 "*"
1019 ],
1020 line,
1021 format!(
1022 "unrecognised reason-class/alias `{cn}` in `{line}` — accepted: \
1023 reflect, dispatch, indirect, native, unresolved, setup, plus the \
1024 aliases `dynamic` and `*`, plus any `unknown-alias` defined in \
1025 the `.candor/config` beside the policy. (⟨0.24⟩ an \
1026 `unknown-alias` whose OWN definition names an unrecognised class \
1027 is refused WHOLE, so a typo in the config surfaces as an \
1028 undefined alias here — check the `unknown-alias` lines too, and \
1029 the line above this one.)"
1030 )
1031 );
1032 }
1033 }
1034 continue;
1035 }
1036 let e = if t == UNKNOWN { Some(UNKNOWN) } else { cap_from_name(t) };
1037 match e {
1038 Some(e) => {
1039 effects.insert(e);
1040 if e == UNKNOWN {
1041 unknown_star = true; // bare Unknown ⇒ all classes
1042 }
1043 if e == "Net" {
1044 net_star = true; // bare Net ⇒ all destinations
1045 }
1046 }
1047 None => {
1048 scope = Some(t.to_string());
1049 break;
1050 }
1051 }
1052 }
1053 if effects.is_empty() {
1054 // The accepted set is the §1 effect vocabulary plus `Unknown` — SORTED, so the
1055 // document is deterministic and diffable across engines.
1056 let mut acc: Vec<&str> = candor_report::EFFECTS.to_vec();
1057 acc.push(UNKNOWN);
1058 acc.sort_unstable();
1059 let msg = format!(
1060 "`deny` names no known effect (accepted: {}): {line}",
1061 acc.join(", ")
1062 );
1063 warn_ignore!("candor: policy error — {msg}");
1064 // ⟨0.24⟩ FATAL (SPEC §6.2 `1e1748a`). MEASURED four-way: `deny Nett app` -> exit 0
1065 // on all four; the rule is DELETED and the gate is green. `Nett` is read as the
1066 // SCOPE (the first unrecognised token ends the effect list), so the line parses to
1067 // a deny of NOTHING.
1068 //
1069 // **A `deny` whose effect list ends up EMPTY is malformed under EITHER reading** —
1070 // typo-in-the-effect or scope-with-no-effect are both nonsense — so there is no
1071 // legitimate policy it could be and refusing it loses nothing. What stays open is
1072 // only the genuinely ambiguous middle (`deny Net Exex app`: at least one valid
1073 // effect plus an unrecognised trailing token that MIGHT be a scope), which the
1074 // parser cannot tell from a legitimate scope and which `parsepolicy` shows either
1075 // way by dumping the `scope` it read.
1076 not_honoured!(
1077 true,
1078 PolicyError::KIND_EFFECT_NAME,
1079 scope.as_deref().unwrap_or(""),
1080 acc,
1081 line,
1082 msg
1083 );
1084 continue;
1085 }
1086 // `*` (or bare `Unknown`) means all classes ⇒ empty filter (matches any Unknown).
1087 if unknown_star {
1088 unknown_classes.clear();
1089 } else if !unknown_classes.is_empty() && !unknown_classes.contains(&ReasonClass::Unresolved) {
1090 // A2 under-gating lint: a narrowed scope that omits `unresolved` (the catch-all for holes
1091 // an engine couldn't classify) may silently tolerate exactly those — flag it (advisory).
1092 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}");
1093 }
1094 // `*` (or bare `Net`) means all destinations ⇒ empty filter (matches any Net).
1095 if net_star {
1096 net_classes.clear();
1097 }
1098 out.rules.push(PolicyRule { effects, scope, unknown_classes, net_classes, raw: line.to_string() });
1099 }
1100 "pure" => out.rules.push(PolicyRule {
1101 effects: BTreeSet::new(),
1102 scope: toks.next().map(str::to_string),
1103 unknown_classes: BTreeSet::new(),
1104 net_classes: BTreeSet::new(),
1105 raw: line.to_string(),
1106 }),
1107 "forbid" => {
1108 let a = toks.next().unwrap_or("");
1109 let arrow = toks.next().unwrap_or("");
1110 let b = toks.next().unwrap_or("");
1111 if a.is_empty() || arrow != "->" || b.is_empty() {
1112 let msg = format!("`forbid` is malformed (want `forbid <scope> -> <scope>`): {line}");
1113 warn_ignore!("candor: ignoring layering rule ({msg})");
1114 // The token reported is whatever sat in the ARROW position — `->` must be its own
1115 // token, so `forbid glued->arrow` finds nothing there and that absence is the finding.
1116 not_honoured!(false, PolicyError::KIND_RULE_KIND, arrow, ["->"], line, msg);
1117 continue;
1118 }
1119 out.layer_rules.push(LayerRule {
1120 from: a.to_string(),
1121 to: b.to_string(),
1122 raw: line.to_string(),
1123 });
1124 }
1125 // ⟨0.29⟩ `only <A> -> <B> [<C> …]` — the PERMISSION form. Everything after the arrow is a
1126 // scope, so the rule takes a LIST where `forbid` takes one destination; that is the whole
1127 // ergonomic difference, and it is why the tail is not read left-to-right for anything else.
1128 "only" => {
1129 let a = toks.next().unwrap_or("");
1130 let arrow = toks.next().unwrap_or("");
1131 let to: Vec<String> = toks.map(str::to_string).collect();
1132 if a.is_empty() || arrow != "->" || to.is_empty() {
1133 let msg = format!(
1134 "`only` is malformed (want `only <scope> -> <scope> [<scope> …]`): {line}"
1135 );
1136 warn_ignore!("candor: ignoring permission rule ({msg})");
1137 // Same witness as `forbid`: whatever sat in the ARROW position, since `->` must be
1138 // its own token and `only glued->arrow` finds nothing there.
1139 not_honoured!(false, PolicyError::KIND_RULE_KIND, arrow, ["->"], line, msg);
1140 continue;
1141 }
1142 out.only_rules.push(OnlyRule {
1143 from: a.to_string(),
1144 to,
1145 raw: line.to_string(),
1146 });
1147 }
1148 other => {
1149 let msg = format!(
1150 "unknown rule kind `{other}` (accepted: allow, deny, forbid, only, pure): {line}"
1151 );
1152 warn_ignore!("candor: ignoring policy rule ({msg})");
1153 not_honoured!(
1154 false,
1155 PolicyError::KIND_RULE_KIND,
1156 other,
1157 ["allow", "deny", "forbid", "only", "pure"],
1158 line,
1159 msg
1160 );
1161 }
1162 }
1163 }
1164 out
1165}
1166
1167#[cfg(test)]
1168mod tests {
1169 #[test]
1170 fn db_table_covering_is_strict() {
1171 use super::db_table_covered as c;
1172 assert!(c("ledger.entries", "Ledger.Entries")); // case-insensitive exact
1173 assert!(c("ledger.*", "ledger.entries")); // schema wildcard
1174 assert!(!c("ledger.*", "ledgerx.entries")); // boundary-respecting
1175 assert!(!c("entries", "ledger.entries")); // no silent qualification widening
1176 assert!(c("entries", "entries"));
1177 }
1178
1179 #[test]
1180 fn allow_db_parses_and_gates() {
1181 let p = super::parse_policy("allow Db in billing ledger.* customers\n");
1182 assert_eq!(p.allow_rules.len(), 1);
1183 assert_eq!(p.allow_rules[0].effect, "Db");
1184 assert!(super::literal_allowed("Db", "ledger.entries", &p.allow_rules[0].literals));
1185 assert!(super::literal_allowed("Db", "customers", &p.allow_rules[0].literals));
1186 assert!(!super::literal_allowed("Db", "audit.log", &p.allow_rules[0].literals));
1187 }
1188
1189 use super::*;
1190
1191 #[test]
1192 fn policy_parses() {
1193 let p = parse_policy(
1194 "# the domain layer must stay pure of I/O\n\
1195 deny Net Db domain\n\
1196 deny Exec\n\
1197 pure parse\n\
1198 nonsense line\n\
1199 deny notaneffect\n",
1200 );
1201 let rules = &p.rules;
1202 assert_eq!(rules.len(), 3);
1203 assert_eq!(rules[0].effects, ["Db", "Net"].into_iter().collect::<BTreeSet<_>>());
1204 assert_eq!(rules[0].scope.as_deref(), Some("domain"));
1205 assert!(rules[1].effects.contains("Exec") && rules[1].scope.is_none());
1206 assert!(rules[2].effects.is_empty() && rules[2].scope.as_deref() == Some("parse"));
1207 // sweep [16]: a classic-Mac (bare \r) multi-rule policy must NOT collapse to the first rule.
1208 let cr = parse_policy("deny Net a\rdeny Exec b\rdeny Db c\r");
1209 assert_eq!(cr.rules.len(), 3, "bare-CR lines must each parse");
1210 assert!(cr.rules.iter().any(|r| r.effects.contains("Exec") && r.scope.as_deref() == Some("b")));
1211 // mixed \r\n and bare \r normalize identically.
1212 assert_eq!(parse_policy("deny Net a\r\ndeny Exec b\r").rules.len(), 2);
1213 // `Unknown` is a denyable token; a bare `deny` with no effect is ignored.
1214 assert_eq!(parse_policy("deny Unknown core").rules[0].effects, ["Unknown"].into_iter().collect());
1215 assert!(parse_policy("deny\ndeny \n").rules.is_empty());
1216 // a `deny` whose first token is a non-effect names no effect -> dropped, NOT a pure rule.
1217 assert!(parse_policy("deny notaneffect scope").rules.is_empty());
1218 // the first non-effect token ENDS the rule: a later effect token is not collected.
1219 let p2 = parse_policy("deny Net foo Db");
1220 assert_eq!(p2.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
1221 assert_eq!(p2.rules[0].scope.as_deref(), Some("foo"));
1222 // NBSP is NOT a token separator (only ASCII White_Space is) — pinned to MATCH Java, which
1223 // drops it: a `deny\u{a0}Net` is one token `deny\u{a0}Net`, NOT `deny` + `Net`, so it names no
1224 // known effect and is dropped. Splitting on Unicode whitespace here would let candor see a deny
1225 // the JVM engine doesn't — a gateless-divergence between impls. (See is_ascii_ws.)
1226 assert!(parse_policy("deny\u{a0}Net core").rules.is_empty(),
1227 "an NBSP between deny and the effect must NOT split into separate tokens");
1228 // The NBSP rides INTO the scope token rather than separating it: `deny Net\u{a0}domain` is
1229 // `deny` + `Net` + `\u{a0}domain` — Net is the effect, the scope keeps the NBSP verbatim.
1230 let nb = parse_policy("deny Net \u{a0}domain");
1231 assert_eq!(nb.rules.len(), 1);
1232 assert_eq!(nb.rules[0].effects, ["Net"].into_iter().collect::<BTreeSet<_>>());
1233 assert_eq!(nb.rules[0].scope.as_deref(), Some("\u{a0}domain"));
1234 }
1235
1236 #[test]
1237 fn reason_scoped_unknown_parses() {
1238 use super::ReasonClass::*;
1239 // `Unknown[dispatch,indirect]` narrows the Unknown membership to those classes.
1240 let p = parse_policy("deny Net Unknown[dispatch,indirect] dom\n");
1241 let r = &p.rules[0];
1242 assert!(r.effects.contains("Unknown") && r.effects.contains("Net"));
1243 assert_eq!(r.scope.as_deref(), Some("dom"));
1244 assert_eq!(r.unknown_classes, [Dispatch, Indirect].into_iter().collect());
1245 // bare `Unknown` and `Unknown[*]` ⇒ empty filter (all classes).
1246 assert!(parse_policy("deny Net Unknown dom\n").rules[0].unknown_classes.is_empty(), "bare Unknown ⇒ all");
1247 assert!(parse_policy("deny Net Unknown[*] dom\n").rules[0].unknown_classes.is_empty(), "Unknown[*] ⇒ all");
1248 // `dynamic` alias = every genuine class incl. unresolved, excl. setup.
1249 assert_eq!(
1250 parse_policy("deny Net Unknown[dynamic] dom\n").rules[0].unknown_classes,
1251 [Reflect, Dispatch, Indirect, Native, Unresolved].into_iter().collect()
1252 );
1253 // config `unknown-alias` (⟨0.19⟩): a user-defined name resolves; a reserved name is rejected.
1254 let aliases = super::parse_unknown_aliases(
1255 "unknown-alias risky = reflect,native\nunknown-alias telemetry = indirect\nunknown-alias reflect = native\n");
1256 assert_eq!(aliases.get("risky"), Some(&[Reflect, Native].into_iter().collect()));
1257 assert_eq!(aliases.get("telemetry"), Some(&[Indirect].into_iter().collect()));
1258 assert!(!aliases.contains_key("reflect"), "a config alias may not shadow a class token");
1259 // the `unknown-alias` KEY matches case-insensitively (parity with java/ts/swift, which lowercase it)
1260 assert_eq!(super::parse_unknown_aliases("Unknown-Alias hot = native\n").get("hot"),
1261 Some(&[Native].into_iter().collect()), "the unknown-alias key must match case-insensitively");
1262 let pr = super::parse_policy_with_aliases("deny Net Unknown[risky] api\n", &aliases);
1263 assert_eq!(pr.rules[0].unknown_classes, [Reflect, Native].into_iter().collect());
1264 // an UNDEFINED alias name is dropped-with-warning → empty filter (behaves like bare Unknown[*])
1265 assert!(super::parse_policy_with_aliases("deny Net Unknown[nope] api\n", &aliases).rules[0].unknown_classes.is_empty());
1266 // classify: raw reason tokens → normative classes (mirrors java ReasonClass.classify).
1267 assert_eq!(ReasonClass::classify("reflect:Class.forName"), Reflect);
1268 assert_eq!(ReasonClass::classify("native:extern fn"), Native);
1269 assert_eq!(ReasonClass::classify("callback:unresolved call"), Indirect);
1270 assert_eq!(ReasonClass::classify("ambiguous:same-name local defs"), Dispatch);
1271 assert_eq!(ReasonClass::classify("unresolved"), Unresolved);
1272 assert_eq!(ReasonClass::classify("whatever-new"), Unresolved); // conservative catch-all
1273 }
1274
1275 /// THE CONTROL SPEC §4 ⟨0.24⟩ MAKES A SHOULD: a FABRICATED, off-vocabulary kind must still behave as
1276 /// §2 forward-compatibility requires. Without it, "added a fifth kind" and "stopped checking the kind
1277 /// set" are the same diff — the classifier is one `_ =>` arm away from either.
1278 ///
1279 /// This engine holds the §4 vocabulary ONCE (the raw `kind:detail` string, read back only through
1280 /// `classify`), so there is no typed half here to drift from it. That is why the JVM engine's failure
1281 /// — a string classifier correct on `ambiguous` since July while its typed `Kind` enum lacked the kind
1282 /// entirely, one token classified two ways inside one engine — is not reproducible here. If a typed
1283 /// kind representation is ever added, this test is where its half gets its control.
1284 #[test]
1285 fn off_vocabulary_kinds_round_trip_and_classify_through_the_catch_all() {
1286 use ReasonClass::*;
1287 // A kind no engine emits and no section names. §2: tolerated, and classified CONSERVATIVELY —
1288 // `unresolved`, the catch-all, so a narrowed `Unknown[unresolved]`/`[dynamic]`/`[*]` still bites it.
1289 assert_eq!(ReasonClass::classify("banana:whatever"), Unresolved);
1290 assert_eq!(ReasonClass::classify("banana:dispatch of a banana"), Unresolved,
1291 "a canonical kind appearing in the DETAIL must not leak into the classification");
1292 // …and it must not be swallowed into a narrower class. These are the four wrong answers.
1293 for wrong in [Reflect, Dispatch, Indirect, Native] {
1294 assert_ne!(ReasonClass::classify("banana:whatever"), wrong);
1295 }
1296 // The five §4 ⟨0.24⟩ kinds all classify, and `ambiguous` is the fifth — pinned beside the
1297 // fabricated one deliberately: one arm chain answers both, so a change that stops distinguishing
1298 // them fails here rather than in the field.
1299 assert_eq!(ReasonClass::classify("reflect:x"), Reflect);
1300 assert_eq!(ReasonClass::classify("native:x"), Native);
1301 assert_eq!(ReasonClass::classify("dispatch:Owner.member"), Dispatch);
1302 assert_eq!(ReasonClass::classify("callback:x"), Indirect);
1303 assert_eq!(ReasonClass::classify("ambiguous:x"), Dispatch);
1304 // ⟨0.24⟩ `dep:<hash>` / `dep-stale:<pkg>` are REGISTERED §4 kinds, not migration ones — swift
1305 // emits them per dependency ENTRY, and this engine CONSUMES swift/ts reports through
1306 // candor-query. §6.2 pins their class as `unresolved`, which is where the catch-all lands them;
1307 // pinned so a future prefix arm cannot move them without saying so.
1308 assert_eq!(ReasonClass::classify("dep:9f2c1a"), Unresolved);
1309 assert_eq!(ReasonClass::classify("dep-stale:somepkg"), Unresolved);
1310 }
1311
1312 #[test]
1313 fn net_destination_class_parses_and_classifies() {
1314 // `Net[unknown-host,known-telemetry]` narrows the Net membership to those destination classes.
1315 let p = parse_policy("deny Net[unknown-host,known-telemetry] dom\n");
1316 let r = &p.rules[0];
1317 assert!(r.effects.contains("Net"));
1318 assert_eq!(r.scope.as_deref(), Some("dom"));
1319 assert_eq!(
1320 r.net_classes,
1321 ["unknown-host", "known-telemetry"].iter().map(|s| s.to_string()).collect()
1322 );
1323 // bare `Net` and `Net[*]` ⇒ empty filter (all destinations).
1324 assert!(parse_policy("deny Net dom\n").rules[0].net_classes.is_empty(), "bare Net ⇒ all");
1325 assert!(parse_policy("deny Net[*] dom\n").rules[0].net_classes.is_empty(), "Net[*] ⇒ all");
1326 // an unknown destination-class is dropped-with-warning → empty filter (behaves like bare Net[*]).
1327 assert!(parse_policy("deny Net[nope] dom\n").rules[0].net_classes.is_empty());
1328 // the classifier: telemetry (subdomain-aware), model host, unresolved, and the config-partner path.
1329 let no_partners = BTreeSet::new();
1330 assert_eq!(crate::net_dest_class("sentry.io", &no_partners), "known-telemetry");
1331 assert_eq!(crate::net_dest_class("us.i.posthog.com", &no_partners), "known-telemetry"); // 0.20.1 corpus-grown
1332 assert_eq!(crate::net_dest_class("o1.ingest.sentry.io", &no_partners), "known-telemetry");
1333 assert_eq!(crate::net_dest_class("api.openai.com", &no_partners), "known-partner", "a model host is known-partner");
1334 assert_eq!(crate::net_dest_class("evil.example.com", &no_partners), "unknown-host");
1335 let partners: BTreeSet<String> = ["api.stripe.com".to_string()].into_iter().collect();
1336 assert_eq!(crate::net_dest_class("api.stripe.com", &partners), "known-partner", "config-declared partner");
1337 assert_eq!(crate::net_dest_class("api.stripe.com", &no_partners), "unknown-host", "partner is config-only");
1338 // `net-partner` config parsing: host-normalized, case-insensitive key, multi-value.
1339 let pset = super::parse_net_partners("net-partner Api.Stripe.com:443\nNET-PARTNER hooks.stripe.com\n");
1340 assert!(pset.contains("api.stripe.com") && pset.contains("hooks.stripe.com"));
1341 }
1342
1343 #[test]
1344 fn allowlist_parses() {
1345 let p = parse_policy(
1346 "allow Net in billing api.stripe.com hooks.stripe.com\n\
1347 allow Exec in ci git\n\
1348 allow Fs in config /etc/app\n\
1349 allow Net github.com\n\
1350 allow Clock whatever\n\
1351 allow Net in nohosts\n\
1352 allow\n",
1353 );
1354 assert_eq!(p.allow_rules.len(), 4); // Clock carries no literal surface — rejected; Db now does
1355 assert_eq!((p.allow_rules[0].effect, p.allow_rules[0].scope.as_deref()), ("Net", Some("billing")));
1356 assert_eq!(
1357 p.allow_rules[0].literals,
1358 ["api.stripe.com", "hooks.stripe.com"].iter().map(|s| s.to_string()).collect()
1359 );
1360 assert_eq!((p.allow_rules[1].effect, p.allow_rules[1].scope.as_deref()), ("Exec", Some("ci")));
1361 assert!(p.allow_rules[1].literals.contains("git"));
1362 assert_eq!((p.allow_rules[2].effect, p.allow_rules[2].scope.as_deref()), ("Fs", Some("config")));
1363 assert_eq!((p.allow_rules[3].effect, p.allow_rules[3].scope.is_none()), ("Net", true));
1364
1365 let set = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect::<BTreeSet<_>>();
1366 assert!(literal_allowed("Net", "api.stripe.com:443", &set(&["api.stripe.com"])));
1367 // IPv6: a bare literal is matched WHOLE (no first-colon collapse), so a different address in the
1368 // same block is NOT accepted; a bracketed `[host]:port` matches the bare host. (/code-review.)
1369 assert!(literal_allowed("Net", "2001:db8::aa", &set(&["2001:db8::aa"])));
1370 assert!(!literal_allowed("Net", "2001:db8::ff", &set(&["2001:db8::aa"])));
1371 assert!(!literal_allowed("Net", "2001:dead::1", &set(&["2001:db8::aa"])));
1372 assert!(literal_allowed("Net", "[2001:db8::aa]:443", &set(&["2001:db8::aa"])));
1373 assert_eq!(host_part("2001:db8::aa"), "2001:db8::aa");
1374 assert_eq!(host_part("[2001:db8::aa]:443"), "2001:db8::aa");
1375 assert_eq!(host_part("api.stripe.com:443"), "api.stripe.com");
1376 assert!(literal_allowed("Exec", "/usr/bin/git", &set(&["git"])));
1377 assert!(!literal_allowed("Exec", "/usr/bin/curl", &set(&["git"])));
1378 assert!(literal_allowed("Fs", "/etc/app/conf.toml", &set(&["/etc/app"])));
1379 assert!(!literal_allowed("Fs", "/etc/shadow", &set(&["/etc/app"])));
1380 assert_eq!(cmd_base("/usr/bin/git"), "git");
1381 }
1382
1383 #[test]
1384 fn layering_rule_parses() {
1385 let p = parse_policy(
1386 "forbid domain -> infra\n\
1387 forbid app::web -> app::db \n\
1388 forbid domain infra\n\
1389 forbid domain ->\n\
1390 forbid\n",
1391 );
1392 assert_eq!(p.layer_rules.len(), 2);
1393 assert_eq!((p.layer_rules[0].from.as_str(), p.layer_rules[0].to.as_str()), ("domain", "infra"));
1394 assert_eq!((p.layer_rules[1].from.as_str(), p.layer_rules[1].to.as_str()), ("app::web", "app::db"));
1395 }
1396
1397 /// ⟨0.29⟩ `only <A> -> <B> [<C> …]` — the PERMISSION form. The tail is a LIST, which is the whole
1398 /// ergonomic difference from `forbid`; a missing arrow or an EMPTY tail is dropped rather than read
1399 /// as "A may reach nothing", a rule far likelier to be a typo than an intention.
1400 #[test]
1401 fn parses_the_only_permission_form_and_drops_the_malformed() {
1402 let p = parse_policy(
1403 "only model -> util\n\
1404 only app::web -> app::db app::dto \n\
1405 only model util\n\
1406 only model ->\n\
1407 only\n",
1408 );
1409 assert_eq!(p.only_rules.len(), 2, "the two well-formed lines, and only those");
1410 assert_eq!(p.only_rules[0].from.as_str(), "model");
1411 assert_eq!(p.only_rules[0].to, vec!["util".to_string()]);
1412 assert_eq!(p.only_rules[1].from.as_str(), "app::web");
1413 assert_eq!(p.only_rules[1].to, vec!["app::db".to_string(), "app::dto".to_string()],
1414 "every token after the arrow is a permitted scope");
1415 // …and an `only` line is a RULE for the zero-rule refusal: a policy holding one is ARMED, so a
1416 // route that counted only deny/allow/forbid would call this file empty and refuse a live gate.
1417 assert!(!p.rules.is_empty() || !p.only_rules.is_empty(),
1418 "an only-only policy must not read as a zero-rule file");
1419 }
1420
1421 #[test]
1422 fn scope_matches_by_segment_not_substring() {
1423 assert!(scope_matches("app::domain::handle", "domain"));
1424 assert!(scope_matches("domain::handle", "domain"));
1425 assert!(scope_matches("app::domain", "domain"));
1426 assert!(scope_matches("crate::domain_logic", "domain"));
1427 assert!(!scope_matches("app::subdomain::handle", "domain"));
1428 assert!(!scope_matches("app::not_my_domain::f", "domain"));
1429 // multi-segment: intermediates exact, last is a prefix, contiguous.
1430 assert!(scope_matches("crate::net::client::send", "net::client"));
1431 assert!(scope_matches("crate::net::client_pool::get", "net::client"));
1432 assert!(!scope_matches("crate::net::server::send", "net::client"));
1433 assert!(!scope_matches("crate::network::client::send", "net::client"));
1434 assert!(!scope_matches("crate::net::x::client", "net::client"));
1435 assert!(!scope_matches("net", "net::client"));
1436 // DOTTED names (JVM/Swift/TS reports `candor-query` consumes): a scope must match across `.` too,
1437 // else a scoped deny/pure rule is silently inert → whatif false-green (gate-evasion). Both a
1438 // `.`-written and a `::`-written scope must match a dotted name.
1439 assert!(scope_matches("com.acme.domain.Pricing.quote", "domain"));
1440 assert!(scope_matches("com.acme.domain.Pricing.quote", "acme.domain"));
1441 assert!(scope_matches("com.acme.domain.Pricing.quote", "acme::domain"));
1442 assert!(scope_matches("com.acme.infra.Net.fetch", "infra.Net"));
1443 assert!(!scope_matches("com.acme.subdomain.h", "domain"));
1444 assert!(!scope_matches("com.acme.domain.h", "infra"));
1445 }
1446
1447 #[test]
1448 fn fs_path_covered_respects_boundaries() {
1449 assert!(fs_path_covered("/etc/app", "/etc/app"));
1450 assert!(fs_path_covered("/etc/app", "/etc/app/cfg.toml"));
1451 assert!(fs_path_covered("/etc/app/", "/etc/app/cfg"));
1452 assert!(!fs_path_covered("/etc/app", "/etc/apppwned"));
1453 assert!(!fs_path_covered("/etc/app", "/etc/application/x"));
1454 assert!(!fs_path_covered("/etc/app/cfg", "/etc/app"));
1455 assert!(!fs_path_covered("/etc/app", "/etc/app/../passwd"));
1456 assert!(fs_path_covered("/", "/etc/app/x"));
1457 assert!(!fs_path_covered("etc/app", "/etc/app/cfg"));
1458 assert!(!fs_path_covered("/etc/app", "etc/app/cfg"));
1459 assert!(fs_path_covered("etc/app", "etc/app/cfg"));
1460 }
1461
1462 /// ⟨0.24⟩ THE PROVABLE-PURITY DISCLOSURE MUST ASK THE GATE WHAT "PASSES" MEANS — SPEC §6.2, and both
1463 /// directions in ONE test, because killing an over-charge is exactly where a silent under-report gets
1464 /// introduced and the fixture proving the fabrication is closed cannot show the reach closed with it.
1465 ///
1466 /// A hole is a function that PASSES its rule while `Unknown`. `unverified_hole_rule` used to compute
1467 /// PASSES from `r.effects` alone — the pre-⟨0.19⟩ question, asked after two rungs gave rules a
1468 /// NARROWING FILTER — so a rule the gate TOLERATES was read here as violated and the hole was DELETED
1469 /// from the disclosure. MEASURED 2026-07-28: `deny Unknown[reflect]` over an `indirect` hole → gate
1470 /// exit 0, `unverified` "every function in a pure/deny layer is PROVABLY clean ✓".
1471 ///
1472 /// ROW 1 (the fix) — the filter does NOT match, so the gate tolerates and this IS a hole.
1473 /// ROW 2 (the mirror) — the SAME rule, SAME function, filter spelled to MATCH: the gate fires, so it
1474 /// is a violation and NOT a hole. Without row 2 the fix is satisfied by a predicate that calls
1475 /// everything a hole, which is the mirror over-report of the thing being fixed.
1476 /// ROW 3 — the ⟨0.20⟩ `Net[dest…]` filter, the same shape on the other narrowing axis.
1477 /// ROW 4 — no filter at all: byte-identical to pre-⟨0.24⟩, which is what keeps conformance PARTs
1478 /// 12c/12d (four-way) from moving.
1479 #[test]
1480 fn a_narrowed_rule_the_gate_tolerates_is_a_hole_and_the_one_it_fires_on_is_not() {
1481 let effs = ["Unknown"];
1482 let indirect: BTreeSet<String> = ["indirect".to_string()].into_iter().collect();
1483 let hole = |src: &str, classes: Option<&BTreeSet<String>>, nets: &[String]| -> Option<String> {
1484 let p = parse_policy(src);
1485 unverified_hole_rule("app::go", &effs, classes, nets, &p.rules).map(|r| rule_and_upgrade(r).1)
1486 };
1487
1488 // ROW 1 — tolerated by the gate (indirect ∉ {reflect}) ⇒ a hole, and the upgrade WIDENS the
1489 // filter rather than appending a second `Unknown`.
1490 assert_eq!(
1491 hole("deny Unknown[reflect]\n", Some(&indirect), &[]).as_deref(),
1492 Some("deny Unknown"),
1493 "a rule the gate TOLERATES leaves the function unproven — that is the disclosure's whole subject"
1494 );
1495
1496 // ROW 2 — THE MIRROR. Same rule, same signature, filter spelled to match: the gate FIRES, so this
1497 // is a violation and the disclosure must stay silent about it.
1498 assert_eq!(
1499 hole("deny Unknown[indirect]\n", Some(&indirect), &[]),
1500 None,
1501 "a rule the gate FIRES on is a violation, not a hole — filter-awareness must not start \
1502 disclosing the gate's own findings back as unproven passes"
1503 );
1504 assert_eq!(hole("deny Unknown[dynamic]\n", Some(&indirect), &[]), None, "`dynamic` covers indirect");
1505
1506 // ROW 3 — the ⟨0.20⟩ destination filter, both ways, on a fn carrying Net BESIDE its Unknown.
1507 let netfn = ["Net".to_string(), "Unknown".to_string()];
1508 let telemetry = vec!["known-telemetry".to_string()];
1509 let p = parse_policy("deny Net[unknown-host]\n");
1510 assert_eq!(
1511 unverified_hole_rule("app::go", &netfn, Some(&indirect), &telemetry, &p.rules)
1512 .map(|r| rule_and_upgrade(r).1)
1513 .as_deref(),
1514 Some("deny Net[unknown-host] Unknown"),
1515 "a `Net[dest…]` the fn's destinations do not match is tolerated, so the Unknown beside it is a hole"
1516 );
1517 let p = parse_policy("deny Net[known-telemetry]\n");
1518 assert_eq!(
1519 unverified_hole_rule("app::go", &netfn, Some(&indirect), &telemetry, &p.rules).map(|r| r.raw.clone()),
1520 None,
1521 "MIRROR: the matching destination filter FIRES, so it is a violation and not a hole"
1522 );
1523
1524 // ROW 4 — UNFILTERED, unchanged. `deny Unknown` fires on every Unknown (never a hole); `pure` and
1525 // `deny Fs` pass a fn with no real effect (always a hole) — the forms PARTs 12c/12d pin four-way.
1526 assert_eq!(hole("deny Unknown\n", Some(&indirect), &[]), None);
1527 assert_eq!(hole("pure\n", Some(&indirect), &[]).as_deref(), Some("deny Unknown"));
1528 assert_eq!(hole("deny Net Db domain\ndeny Fs\n", Some(&indirect), &[]).as_deref(), Some("deny Fs Unknown"));
1529 assert_eq!(
1530 hole("deny Net Db go\n", Some(&indirect), &[]).as_deref(),
1531 Some("deny Db Net Unknown go"),
1532 "the sorted multi-effect upgrade PART 12c-deny pins in all four engines"
1533 );
1534
1535 // A WITHHELD filter — no class set to read — counts as PASSING, so the hole is disclosed rather
1536 // than dropped. The gate withholds there too; between an advisory note that speaks and one that
1537 // goes quiet over a rule that never ran, only the first stays true.
1538 assert_eq!(hole("deny Unknown[reflect]\n", None, &[]).as_deref(), Some("deny Unknown"));
1539 }
1540}
1541
1542// ── ⟨0.27⟩ SPEC §3.4 `engine` — the engine↔baseline coupling ─────────────────────────────────────
1543/// What an `engine` pin says about the build that is running. Data, not a print-and-exit, so every
1544/// branch is testable — including the two that MUST NOT change the exit code.
1545#[derive(Debug, PartialEq, Eq)]
1546pub enum PinVerdict {
1547 /// No pin, or a pin qualified for another implementation. Today's behaviour, exactly.
1548 Absent,
1549 Match,
1550 /// A different version — the engine↔baseline coupling is broken. Exit 2 (UNEVALUABLE, never 1).
1551 Mismatch,
1552 /// Present but unreadable (`engine latest`, a bare `engine`, trailing junk). Exit 2: a pin that
1553 /// cannot be read is a guard the operator believes is on. This is the one place §6.2's
1554 /// warn-and-skip posture INVERTS — skipping a key that ADDS something costs that key; skipping a
1555 /// PIN costs the guard.
1556 Malformed,
1557 /// Well-formed, and this build cannot state its own release. UNANSWERABLE — §3.1's rule applies:
1558 /// disclosed, never scored, INCLUDING as satisfied.
1559 Undetermined,
1560}
1561
1562/// The pin that applies to `impl_name` — the qualified form wins over the unqualified one, and the
1563/// LAST occurrence wins (matching candor-java's map semantics). Two lines that DISAGREE about the same
1564/// key return a value that cannot parse, so they surface as [`PinVerdict::Malformed`] rather than one
1565/// silently discarding the other: two lines disagreeing about which engine to run is not a preference
1566/// to resolve, it is a question the config leaves unanswered.
1567pub fn engine_pin_for(text: &str, impl_name: &str) -> Option<String> {
1568 const IMPLS: [&str; 5] = ["java", "rust", "ts", "swift", "agents"];
1569 let (mut wild, mut qual): (Option<String>, Option<String>) = (None, None);
1570 let mut bad = false;
1571 for raw in text.lines() {
1572 let line = raw.split('#').next().unwrap_or("").trim();
1573 if line.is_empty() {
1574 continue;
1575 }
1576 let mut it = line.split_whitespace();
1577 if !it.next().is_some_and(|k| k.eq_ignore_ascii_case("engine")) {
1578 continue;
1579 }
1580 let rest: Vec<&str> = it.collect();
1581 let slot = |cur: &mut Option<String>, v: String| {
1582 if cur.as_ref().is_some_and(|p| *p != v) {
1583 *cur = Some(format!("{} / {v}", cur.as_ref().unwrap()));
1584 } else {
1585 *cur = Some(v);
1586 }
1587 };
1588 // A KNOWN QUALIFIER DECIDES OWNERSHIP BEFORE ARITY. Checking the one-token case first made `engine swift` a WILDCARD pin whose version is the literal "swift" -> MALFORMED -> exit 2 in every engine, so one operator forgetting a version on a qualified line killed the whole family. SPEC 3.4 says the skip is whole-line 'whatever follows it' -- and nothing following it is a case of that too.
1589 if let Some(head) = rest.first() {
1590 if IMPLS.contains(&head.to_ascii_lowercase().as_str()) {
1591 if head.eq_ignore_ascii_case(impl_name) {
1592 if rest.len() == 2 { slot(&mut qual, rest[1].to_string()); } else { bad = true; }
1593 }
1594 continue; // another impl's line, whatever follows it
1595 }
1596 }
1597 match rest.len() {
1598 0 => bad = true, // a bare `engine` line
1599 1 => slot(&mut wild, rest[0].to_string()), // engine <version>
1600 _ => bad = true, // trailing junk / unknown qualifier
1601 }
1602 }
1603 if bad {
1604 return Some("<unreadable>".to_string());
1605 }
1606 // AN UNREADABLE UNQUALIFIED LINE IS NOT HIDDEN BY A QUALIFIED PIN. `qual ?? wild` returned the qua
1607 // lified value, so `engine garbage` beside a good qualified line passed SILENTLY here while candor-java ex
1608 // ited 2 — the exact mirror of the bug just fixed in java, four engines the other way. Unreadability is a property of the LINE; precedence only decides which VERSION applies.
1609 if let Some(w) = &wild {
1610 if normalize_version(w).is_none() { return Some(w.clone()); }
1611 }
1612 qual.or(wild)
1613}
1614
1615/// [`PinVerdict`] for `pin` against `running`. Pure: no printing, no exit.
1616pub fn pin_verdict(pin: Option<&str>, running: &str) -> PinVerdict {
1617 let Some(pin) = pin else { return PinVerdict::Absent };
1618 let Some(want) = normalize_version(pin) else { return PinVerdict::Malformed };
1619 if running.trim().is_empty() || running == "unknown" {
1620 return PinVerdict::Undetermined;
1621 }
1622 if want == normalize_version(running).unwrap_or_else(|| running.trim().to_string()) {
1623 PinVerdict::Match
1624 } else {
1625 PinVerdict::Mismatch
1626 }
1627}
1628
1629/// A pin token → its comparable form, or None when it is not a version at all. A leading `v` is
1630/// optional (the GitHub-tag `v0.27.0` and the crate `0.27.0` are the same pin) and a two-part `0.27`
1631/// means `0.27.0`. Anything else — `latest`, a branch name — is MALFORMED rather than a version that
1632/// can never match: the difference decides whether the operator reads "wrong version" or "that is not
1633/// a version".
1634fn normalize_version(raw: &str) -> Option<String> {
1635 let s = raw.trim().strip_prefix(['v', 'V']).unwrap_or_else(|| raw.trim());
1636 let parts: Vec<&str> = s.split('.').collect();
1637 if !(parts.len() == 2 || parts.len() == 3) || !parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) {
1638 return None;
1639 }
1640 Some(if parts.len() == 2 { format!("{s}.0") } else { s.to_string() })
1641}