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        Ok(AuthorityPolicy {
57            policy_id: raw.policy_id,
58            modality: raw.modality,
59            priority: raw.priority,
60            applies_to,
61            when,
62            requires_fact,
63            semantics_version: self.semantics_version.clone(),
64            override_spec: raw.override_spec,
65            obligation_spec: raw.obligation_spec,
66            description: raw.description,
67            evidence_ref: raw.evidence_ref,
68        })
69    }
70
71    fn parse_structural_predicates(
72        &self,
73        raw: &HashMap<String, serde_json::Value>,
74    ) -> Result<StructuralPredicates, AuthorityError> {
75        for key in raw.keys() {
76            validate_fact_path(key)?;
77        }
78        Ok(StructuralPredicates {
79            predicates: raw.clone(),
80        })
81    }
82
83    fn parse_condition_predicates(
84        &self,
85        raw: &HashMap<String, serde_json::Value>,
86    ) -> Result<ConditionPredicates, AuthorityError> {
87        for key in raw.keys() {
88            validate_fact_path(key)?;
89        }
90        Ok(ConditionPredicates {
91            conditions: raw.clone(),
92        })
93    }
94
95    fn parse_fact_requirements(
96        &self,
97        raw: &[RawFactRequirement],
98    ) -> Result<Vec<FactRequirement>, AuthorityError> {
99        let mut requirements = Vec::new();
100        for req in raw {
101            validate_fact_path(&req.fact_path)?;
102            requirements.push(FactRequirement {
103                fact_path: req.fact_path.clone(),
104                allowed_source_classes: req.allowed_source_classes.clone(),
105                allowed_source_ids: req.allowed_source_ids.clone().unwrap_or_default(),
106                max_age: req
107                    .max_age
108                    .as_ref()
109                    .map(|s| parse_duration(s))
110                    .transpose()?,
111                evidence_ref_required: req.evidence_ref_required.unwrap_or(false),
112                signature_required: req.signature_required.unwrap_or(false),
113                minimum_confidence: req.minimum_confidence,
114                required_transform: req.required_transform.clone(),
115                derived_from_source: req.derived_from_source.clone(),
116            });
117        }
118        Ok(requirements)
119    }
120}
121
122fn parse_duration(s: &str) -> Result<chrono::Duration, AuthorityError> {
123    let s = s.trim();
124    let seconds = if s.ends_with('s') {
125        s.trim_end_matches('s').parse::<i64>().ok()
126    } else if s.ends_with('m') {
127        s.trim_end_matches('m').parse::<i64>().ok().map(|v| v * 60)
128    } else if s.ends_with('h') {
129        s.trim_end_matches('h')
130            .parse::<i64>()
131            .ok()
132            .map(|v| v * 3600)
133    } else if s.ends_with('d') {
134        s.trim_end_matches('d')
135            .parse::<i64>()
136            .ok()
137            .map(|v| v * 86400)
138    } else {
139        s.parse::<i64>().ok().map(|v| v * 3600) // default hours
140    };
141    seconds
142        .map(chrono::Duration::seconds)
143        .ok_or_else(|| AuthorityError::invalid_environment(format!("Invalid duration: '{}'", s)))
144}
145
146pub struct CompatibilityLoweringAuditor {
147    version: String,
148}
149
150impl CompatibilityLoweringAuditor {
151    pub fn new(version: String) -> Result<Self, AuthorityError> {
152        if version.trim().is_empty() {
153            return Err(AuthorityError::invalid_environment(
154                "Compatibility lowering version is required",
155            ));
156        }
157
158        Ok(Self { version })
159    }
160
161    pub fn version(&self) -> &str {
162        &self.version
163    }
164
165    pub fn audit_expression(&self, expr: &str) -> Result<Option<LoweredPolicy>, AuthorityError> {
166        let expr_lc = expr.to_lowercase();
167
168        // Reject all structural OR as ambiguous (spec §14.1.7, §17.7)
169        if expr_lc.contains(" or ") {
170            return Err(AuthorityError::ambiguous_lowering(expr));
171        }
172
173        // Handle negated conditions: `not X = "Y"` lowers to when condition
174        // Reject negative structural predicates (spec §14.1.7)
175        if let Some(inner) = expr_lc.strip_prefix("not ") {
176            let inner_trimmed = inner.trim();
177            // Reject if the negated expression targets structural keys
178            if inner_trimmed.starts_with("resource.")
179                || inner_trimmed.starts_with("actor.")
180                || inner_trimmed.starts_with("action")
181            {
182                return Err(AuthorityError::ambiguous_lowering(expr));
183            }
184            // Lower `not fact.path = "value"` to when condition with negated comparison
185            if let Some(eq_pos) = inner_trimmed.find(" = ") {
186                let key = expr[4..][..eq_pos].trim().to_string();
187                let val = expr[4..][eq_pos + 3..].trim().trim_matches('"').to_string();
188                return Ok(Some(LoweredPolicy {
189                    original: expr.to_string(),
190                    lowered_applies_to: HashMap::new(),
191                    lowered_when: {
192                        let mut m = HashMap::new();
193                        m.insert(key, serde_json::json!({"__neq": val}));
194                        m
195                    },
196                }));
197            }
198            return Err(AuthorityError::ambiguous_lowering(expr));
199        }
200
201        if expr_lc.contains(" and ") {
202            // Split on case-insensitive " and " boundaries
203            let mut parts: Vec<&str> = Vec::new();
204            let mut last = 0;
205            let lc_bytes = expr_lc.as_bytes();
206            let pattern = b" and ";
207            let plen = pattern.len();
208            for i in 0..=lc_bytes.len().saturating_sub(plen) {
209                if &lc_bytes[i..i + plen] == pattern {
210                    parts.push(&expr[last..i]);
211                    last = i + plen;
212                }
213            }
214            parts.push(&expr[last..]);
215            let mut applies_to = HashMap::new();
216            let mut when = HashMap::new();
217            for part in parts {
218                let trimmed = part.trim();
219                let trimmed_lc = trimmed.to_lowercase();
220                if trimmed_lc.starts_with("resource.")
221                    || trimmed_lc.starts_with("actor.")
222                    || trimmed_lc.starts_with("action")
223                {
224                    if let Some((k, v)) = parse_equality(trimmed) {
225                        applies_to.insert(k, v);
226                    }
227                } else if let Some((k, v)) = parse_equality(trimmed) {
228                    when.insert(k, v);
229                }
230            }
231            return Ok(Some(LoweredPolicy {
232                original: expr.to_string(),
233                lowered_applies_to: applies_to,
234                lowered_when: when,
235            }));
236        }
237
238        if let Some((k, v)) = parse_equality(expr) {
239            let mut applies_to = HashMap::new();
240            applies_to.insert(k, v);
241            return Ok(Some(LoweredPolicy {
242                original: expr.to_string(),
243                lowered_applies_to: applies_to,
244                lowered_when: HashMap::new(),
245            }));
246        }
247
248        Ok(None)
249    }
250}
251
252fn parse_equality(s: &str) -> Option<(String, serde_json::Value)> {
253    let s = s.trim();
254    if let Some(eq_pos) = s.find(" = ") {
255        let key = s[..eq_pos].trim().to_string();
256        let val = s[eq_pos + 3..].trim().trim_matches('"').to_string();
257        Some((key, serde_json::Value::String(val)))
258    } else {
259        None
260    }
261}
262
263#[derive(Debug, Clone)]
264pub struct LoweredPolicy {
265    pub original: String,
266    pub lowered_applies_to: HashMap<String, serde_json::Value>,
267    pub lowered_when: HashMap<String, serde_json::Value>,
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct RawPolicy {
272    pub policy_id: String,
273    pub modality: PolicyModality,
274    pub priority: i32,
275    #[serde(default)]
276    pub applies_to: HashMap<String, serde_json::Value>,
277    #[serde(default)]
278    pub when: HashMap<String, serde_json::Value>,
279    #[serde(default)]
280    pub requires_fact: Vec<RawFactRequirement>,
281    #[serde(skip_serializing_if = "Option::is_none")]
282    pub override_spec: Option<OverrideSpec>,
283    #[serde(skip_serializing_if = "Option::is_none")]
284    pub obligation_spec: Option<ObligationSpec>,
285    #[serde(skip_serializing_if = "Option::is_none")]
286    pub description: Option<String>,
287    #[serde(skip_serializing_if = "Option::is_none")]
288    pub evidence_ref: Option<String>,
289}
290
291#[derive(Debug, Clone, Serialize, Deserialize)]
292pub struct RawFactRequirement {
293    pub fact_path: String,
294    pub allowed_source_classes: Vec<SourceClass>,
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub allowed_source_ids: Option<Vec<String>>,
297    #[serde(skip_serializing_if = "Option::is_none")]
298    pub max_age: Option<String>,
299    #[serde(skip_serializing_if = "Option::is_none")]
300    pub evidence_ref_required: Option<bool>,
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub signature_required: Option<bool>,
303    #[serde(skip_serializing_if = "Option::is_none")]
304    pub minimum_confidence: Option<f64>,
305    #[serde(skip_serializing_if = "Option::is_none")]
306    pub required_transform: Option<String>,
307    #[serde(skip_serializing_if = "Option::is_none")]
308    pub derived_from_source: Option<Vec<SourceClass>>,
309}