Skip to main content

domainforge_core/authority/
compiler.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4use super::error::AuthorityError;
5use super::policy::*;
6use super::types::*;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct CompatibilityExpression {
10    pub expression: String,
11    pub location: Option<String>,
12}
13
14pub struct PolicyCompiler {
15    semantics_version: String,
16    compatibility_version: String,
17}
18
19impl PolicyCompiler {
20    pub fn new(semantics_version: String, compatibility_version: String) -> Self {
21        Self {
22            semantics_version,
23            compatibility_version,
24        }
25    }
26
27    pub fn compile(
28        &self,
29        raw_policies: Vec<RawPolicy>,
30    ) -> Result<Vec<AuthorityPolicy>, AuthorityError> {
31        let mut compiled = Vec::new();
32        for raw in raw_policies {
33            let policy = self.compile_one(raw)?;
34            compiled.push(policy);
35        }
36        Ok(compiled)
37    }
38
39    pub fn semantics_version(&self) -> &str {
40        &self.semantics_version
41    }
42
43    pub fn compatibility_version(&self) -> &str {
44        &self.compatibility_version
45    }
46
47    fn compile_one(&self, raw: RawPolicy) -> Result<AuthorityPolicy, AuthorityError> {
48        let applies_to = self.parse_structural_predicates(&raw.applies_to)?;
49        let when = if raw.when.is_empty() {
50            None
51        } else {
52            Some(self.parse_condition_predicates(&raw.when)?)
53        };
54        let requires_fact = self.parse_fact_requirements(&raw.requires_fact)?;
55
56        // A3: a `when` path with no matching `requires_fact` entry is
57        // satisfied by whatever the caller puts in the request context
58        // (ConditionPredicates::evaluate has no source-class filter of its
59        // own). Forgetting `requires_fact` silently trusts the caller, so
60        // refuse to compile the policy instead of shipping the gap.
61        if let Some(ref when) = when {
62            for path in when.conditions.keys() {
63                if !requires_fact.iter().any(|r| &r.fact_path == path) {
64                    return Err(AuthorityError::new(
65                        super::error::AuthorityErrorCode::PolicyParseError,
66                        format!(
67                            "Policy '{}': `when` condition on '{}' has no matching `requires_fact` \
68                             entry, so it would be satisfied by unverified caller-supplied context. \
69                             Add a `requires_fact` entry for '{}' naming the trusted source classes.",
70                            raw.policy_id, path, path
71                        ),
72                    ));
73                }
74            }
75        }
76
77        // A4: `required_transform` is parsed but never enforced by
78        // `FactRequirement::is_satisfied_by`. Silently accepting it would
79        // give the policy author a false sense of security. Refuse to
80        // compile until enforcement exists.
81        for req in &requires_fact {
82            if req.required_transform.is_some() {
83                return Err(AuthorityError::new(
84                    super::error::AuthorityErrorCode::PolicyParseError,
85                    format!(
86                        "Policy '{}': `required_transform` on fact '{}' is not yet enforced by the \
87                         resolver. Remove it rather than rely on an unenforced field.",
88                        raw.policy_id, req.fact_path
89                    ),
90                ));
91            }
92        }
93
94        Ok(AuthorityPolicy {
95            policy_id: raw.policy_id,
96            modality: raw.modality,
97            priority: raw.priority,
98            applies_to,
99            when,
100            requires_fact,
101            semantics_version: self.semantics_version.clone(),
102            override_spec: raw.override_spec,
103            obligation_spec: raw.obligation_spec,
104            description: raw.description,
105            evidence_ref: raw.evidence_ref,
106        })
107    }
108
109    fn parse_structural_predicates(
110        &self,
111        raw: &HashMap<String, serde_json::Value>,
112    ) -> Result<StructuralPredicates, AuthorityError> {
113        // A10: `StructuralPredicates::matches` recognizes exactly five keys
114        // ("action", "actor.id", "actor.role", "resource.id",
115        // "resource.type") and treats everything else as an open metadata
116        // lookup. A typo like "resource.typ" therefore doesn't error — it
117        // silently becomes a metadata predicate that (almost certainly)
118        // never matches, making the policy permanently inert with no
119        // diagnostic. The "resource."/"actor." prefixes are reserved for
120        // the known structural fields, so reject unrecognized keys under
121        // them at compile time instead of shipping a silently-dead policy.
122        const KNOWN_STRUCTURAL_KEYS: [&str; 5] = [
123            "action",
124            "actor.id",
125            "actor.role",
126            "resource.id",
127            "resource.type",
128        ];
129        for key in raw.keys() {
130            validate_fact_path(key)?;
131            if (key.starts_with("resource.") || key.starts_with("actor."))
132                && !KNOWN_STRUCTURAL_KEYS.contains(&key.as_str())
133            {
134                return Err(AuthorityError::new(
135                    super::error::AuthorityErrorCode::PolicyParseError,
136                    format!(
137                        "Unrecognized structural predicate key '{}'. The 'resource.' and 'actor.' \
138                         prefixes are reserved for {:?}; did you mean one of those?",
139                        key, KNOWN_STRUCTURAL_KEYS
140                    ),
141                ));
142            }
143        }
144        Ok(StructuralPredicates {
145            predicates: raw.clone(),
146        })
147    }
148
149    fn parse_condition_predicates(
150        &self,
151        raw: &HashMap<String, serde_json::Value>,
152    ) -> Result<ConditionPredicates, AuthorityError> {
153        for key in raw.keys() {
154            validate_fact_path(key)?;
155        }
156        Ok(ConditionPredicates {
157            conditions: raw.clone(),
158        })
159    }
160
161    fn parse_fact_requirements(
162        &self,
163        raw: &[RawFactRequirement],
164    ) -> Result<Vec<FactRequirement>, AuthorityError> {
165        let mut requirements = Vec::new();
166        for req in raw {
167            validate_fact_path(&req.fact_path)?;
168            requirements.push(FactRequirement {
169                fact_path: req.fact_path.clone(),
170                allowed_source_classes: req.allowed_source_classes.clone(),
171                allowed_source_ids: req.allowed_source_ids.clone().unwrap_or_default(),
172                max_age: req
173                    .max_age
174                    .as_ref()
175                    .map(|s| parse_duration(s))
176                    .transpose()?,
177                evidence_ref_required: req.evidence_ref_required.unwrap_or(false),
178                signature_required: req.signature_required.unwrap_or(false),
179                minimum_confidence: req.minimum_confidence,
180                required_transform: req.required_transform.clone(),
181                derived_from_source: req.derived_from_source.clone(),
182            });
183        }
184        Ok(requirements)
185    }
186}
187
188/// A9: parses a duration string. Fixes three foot-guns in the previous
189/// version: a bare number silently meant hours (surprising — now rejected,
190/// a unit suffix is required); negative durations were accepted (`"-5h"`
191/// made every fact look "fresh" forever — now rejected); and suffix
192/// matching checked single-char suffixes first, so `"10ms"` matched the
193/// `s` branch and became `"10m"` before parsing, producing a confusing
194/// error instead of 10 milliseconds. Longer suffixes (`ms`) are now matched
195/// before shorter ones (`s`, `m`, `h`, `d`).
196fn parse_duration(s: &str) -> Result<time::Duration, AuthorityError> {
197    let s = s.trim();
198    let invalid = || AuthorityError::invalid_environment(format!("Invalid duration: '{}'", s));
199
200    // Longer suffixes must be checked before shorter ones ("ms" before "s").
201    let parsed = if let Some(n) = s.strip_suffix("ms") {
202        n.parse::<i64>().ok().map(time::Duration::milliseconds)
203    } else if let Some(n) = s.strip_suffix('s') {
204        n.parse::<i64>().ok().map(time::Duration::seconds)
205    } else if let Some(n) = s.strip_suffix('m') {
206        n.parse::<i64>().ok().map(time::Duration::minutes)
207    } else if let Some(n) = s.strip_suffix('h') {
208        n.parse::<i64>().ok().map(time::Duration::hours)
209    } else if let Some(n) = s.strip_suffix('d') {
210        n.parse::<i64>().ok().map(time::Duration::days)
211    } else {
212        return Err(AuthorityError::invalid_environment(format!(
213            "Invalid duration: '{}' — a unit suffix (ms, s, m, h, d) is required",
214            s
215        )));
216    };
217
218    match parsed {
219        Some(d) if d >= time::Duration::ZERO => Ok(d),
220        _ => Err(invalid()),
221    }
222}
223
224pub struct CompatibilityLoweringAuditor {
225    version: String,
226}
227
228impl CompatibilityLoweringAuditor {
229    pub fn new(version: String) -> Result<Self, AuthorityError> {
230        if version.trim().is_empty() {
231            return Err(AuthorityError::invalid_environment(
232                "Compatibility lowering version is required",
233            ));
234        }
235
236        Ok(Self { version })
237    }
238
239    pub fn version(&self) -> &str {
240        &self.version
241    }
242
243    /// A5: the previous implementation lowercased `expr` and applied the
244    /// resulting *byte* offsets back onto the original string. For
245    /// non-ASCII input where lowercasing changes byte length (e.g. `İ` →
246    /// `i̇`), that could slice at a non-UTF8 boundary and panic. It also
247    /// matched " and "/" or " inside quoted string literals, so a value
248    /// like `role = "black or white"` was rejected as ambiguous. This
249    /// version scans char-by-char, tracks quote state, and never lowercases
250    /// the whole string — only individual ASCII keyword characters are
251    /// compared case-insensitively.
252    pub fn audit_expression(&self, expr: &str) -> Result<Option<LoweredPolicy>, AuthorityError> {
253        // Reject all top-level structural OR as ambiguous (spec §14.1.7, §17.7).
254        // "Top-level" = outside quoted string literals.
255        if contains_top_level(expr, " or ") {
256            return Err(AuthorityError::ambiguous_lowering(expr));
257        }
258
259        // Handle negated conditions: `not X = "Y"` lowers to when condition.
260        if let Some(inner) = strip_prefix_ci(expr, "not ") {
261            let inner_trimmed = inner.trim();
262            // Reject if the negated expression targets structural keys
263            // (spec §14.1.7): negative structural predicates are ambiguous.
264            if starts_with_ci(inner_trimmed, "resource.")
265                || starts_with_ci(inner_trimmed, "actor.")
266                || starts_with_ci(inner_trimmed, "action")
267            {
268                return Err(AuthorityError::ambiguous_lowering(expr));
269            }
270            return match parse_equality(inner_trimmed) {
271                Some((key, val)) => Ok(Some(LoweredPolicy {
272                    original: expr.to_string(),
273                    lowered_applies_to: HashMap::new(),
274                    lowered_when: {
275                        let mut m = HashMap::new();
276                        m.insert(key, serde_json::json!({"__neq": val}));
277                        m
278                    },
279                })),
280                None => Err(AuthorityError::ambiguous_lowering(expr)),
281            };
282        }
283
284        if contains_top_level(expr, " and ") {
285            let mut applies_to = HashMap::new();
286            let mut when = HashMap::new();
287            for part in split_top_level(expr, " and ") {
288                let trimmed = part.trim();
289                let (k, v) = parse_equality(trimmed)
290                    .ok_or_else(|| AuthorityError::ambiguous_lowering(expr))?;
291                if starts_with_ci(trimmed, "resource.")
292                    || starts_with_ci(trimmed, "actor.")
293                    || starts_with_ci(trimmed, "action")
294                {
295                    applies_to.insert(k, v);
296                } else {
297                    when.insert(k, v);
298                }
299            }
300            return Ok(Some(LoweredPolicy {
301                original: expr.to_string(),
302                lowered_applies_to: applies_to,
303                lowered_when: when,
304            }));
305        }
306
307        if let Some((k, v)) = parse_equality(expr) {
308            let mut applies_to = HashMap::new();
309            applies_to.insert(k, v);
310            return Ok(Some(LoweredPolicy {
311                original: expr.to_string(),
312                lowered_applies_to: applies_to,
313                lowered_when: HashMap::new(),
314            }));
315        }
316
317        // Unrecognized syntax (e.g. `!=`, `<`, `>=`, an unparenthesized
318        // mixed and/or): previously this returned `Ok(None)`, silently
319        // leaving the policy uncompiled. A policy compiler that silently
320        // drops a clause is a correctness hole, not a convenience — error
321        // instead so the gap is visible at compile time.
322        Err(AuthorityError::ambiguous_lowering(expr))
323    }
324}
325
326/// True if `keyword` (matched case-insensitively, ASCII only) occurs outside
327/// any double-quoted region of `s`.
328fn contains_top_level(s: &str, keyword: &str) -> bool {
329    find_top_level(s, keyword).is_some()
330}
331
332fn find_top_level(s: &str, keyword: &str) -> Option<usize> {
333    let chars: Vec<(usize, char)> = s.char_indices().collect();
334    let kw: Vec<char> = keyword.chars().collect();
335    let mut in_quotes = false;
336    let mut i = 0;
337    while i < chars.len() {
338        let (byte_idx, ch) = chars[i];
339        if ch == '"' {
340            in_quotes = !in_quotes;
341            i += 1;
342            continue;
343        }
344        if !in_quotes
345            && i + kw.len() <= chars.len()
346            && chars[i..i + kw.len()]
347                .iter()
348                .zip(kw.iter())
349                .all(|((_, c), k)| c.eq_ignore_ascii_case(k))
350        {
351            return Some(byte_idx);
352        }
353        i += 1;
354    }
355    None
356}
357
358/// Split `s` on every top-level (outside-quotes) occurrence of `keyword`,
359/// matched case-insensitively. Never allocates a lowercased copy of `s`, so
360/// byte offsets always land on the original string's char boundaries.
361fn split_top_level<'a>(s: &'a str, keyword: &str) -> Vec<&'a str> {
362    let chars: Vec<(usize, char)> = s.char_indices().collect();
363    let kw: Vec<char> = keyword.chars().collect();
364    let mut parts = Vec::new();
365    let mut in_quotes = false;
366    let mut last = 0usize;
367    let mut i = 0;
368    while i < chars.len() {
369        let (byte_idx, ch) = chars[i];
370        if ch == '"' {
371            in_quotes = !in_quotes;
372            i += 1;
373            continue;
374        }
375        if !in_quotes
376            && i + kw.len() <= chars.len()
377            && chars[i..i + kw.len()]
378                .iter()
379                .zip(kw.iter())
380                .all(|((_, c), k)| c.eq_ignore_ascii_case(k))
381        {
382            parts.push(&s[last..byte_idx]);
383            let (last_byte, last_ch) = chars[i + kw.len() - 1];
384            last = last_byte + last_ch.len_utf8();
385            i += kw.len();
386            continue;
387        }
388        i += 1;
389    }
390    parts.push(&s[last..]);
391    parts
392}
393
394fn starts_with_ci(s: &str, prefix: &str) -> bool {
395    let mut sc = s.chars();
396    prefix
397        .chars()
398        .all(|p| sc.next().is_some_and(|c| c.eq_ignore_ascii_case(&p)))
399}
400
401fn strip_prefix_ci<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
402    if starts_with_ci(s, prefix) {
403        let byte_len: usize = prefix
404            .chars()
405            .zip(s.chars())
406            .map(|(_, c)| c.len_utf8())
407            .sum();
408        Some(&s[byte_len..])
409    } else {
410        None
411    }
412}
413
414fn parse_equality(s: &str) -> Option<(String, serde_json::Value)> {
415    let s = s.trim();
416    if let Some(eq_pos) = find_top_level(s, " = ") {
417        let key = s[..eq_pos].trim().to_string();
418        let val = s[eq_pos + 3..].trim().trim_matches('"').to_string();
419        Some((key, serde_json::Value::String(val)))
420    } else {
421        None
422    }
423}
424
425#[derive(Debug, Clone)]
426pub struct LoweredPolicy {
427    pub original: String,
428    pub lowered_applies_to: HashMap<String, serde_json::Value>,
429    pub lowered_when: HashMap<String, serde_json::Value>,
430}
431
432#[derive(Debug, Clone, Serialize, Deserialize)]
433pub struct RawPolicy {
434    pub policy_id: String,
435    pub modality: PolicyModality,
436    pub priority: i32,
437    #[serde(default)]
438    pub applies_to: HashMap<String, serde_json::Value>,
439    #[serde(default)]
440    pub when: HashMap<String, serde_json::Value>,
441    #[serde(default)]
442    pub requires_fact: Vec<RawFactRequirement>,
443    #[serde(skip_serializing_if = "Option::is_none")]
444    pub override_spec: Option<OverrideSpec>,
445    #[serde(skip_serializing_if = "Option::is_none")]
446    pub obligation_spec: Option<ObligationSpec>,
447    #[serde(skip_serializing_if = "Option::is_none")]
448    pub description: Option<String>,
449    #[serde(skip_serializing_if = "Option::is_none")]
450    pub evidence_ref: Option<String>,
451}
452
453#[derive(Debug, Clone, Serialize, Deserialize)]
454pub struct RawFactRequirement {
455    pub fact_path: String,
456    pub allowed_source_classes: Vec<SourceClass>,
457    #[serde(skip_serializing_if = "Option::is_none")]
458    pub allowed_source_ids: Option<Vec<String>>,
459    #[serde(skip_serializing_if = "Option::is_none")]
460    pub max_age: Option<String>,
461    #[serde(skip_serializing_if = "Option::is_none")]
462    pub evidence_ref_required: Option<bool>,
463    #[serde(skip_serializing_if = "Option::is_none")]
464    pub signature_required: Option<bool>,
465    #[serde(skip_serializing_if = "Option::is_none")]
466    pub minimum_confidence: Option<f64>,
467    #[serde(skip_serializing_if = "Option::is_none")]
468    pub required_transform: Option<String>,
469    #[serde(skip_serializing_if = "Option::is_none")]
470    pub derived_from_source: Option<Vec<SourceClass>>,
471}