Skip to main content

domainforge_core/authority/
policy.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4use super::error::AuthorityError;
5use super::types::*;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct AuthorityPolicy {
9    pub policy_id: String,
10    pub modality: PolicyModality,
11    pub priority: i32,
12    pub applies_to: StructuralPredicates,
13    #[serde(default)]
14    pub when: Option<ConditionPredicates>,
15    #[serde(default)]
16    pub requires_fact: Vec<FactRequirement>,
17    pub semantics_version: String,
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub override_spec: Option<OverrideSpec>,
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub obligation_spec: Option<ObligationSpec>,
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub description: Option<String>,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub evidence_ref: Option<String>,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct StructuralPredicates {
30    #[serde(flatten)]
31    pub predicates: HashMap<String, serde_json::Value>,
32}
33
34impl StructuralPredicates {
35    pub fn matches(&self, request: &AuthorityRequest) -> bool {
36        for (key, expected) in &self.predicates {
37            let actual = match key.as_str() {
38                "action" => serde_json::Value::String(request.operation.clone()),
39                "actor.id" => serde_json::Value::String(request.actor.id.clone()),
40                "actor.role" => request
41                    .actor
42                    .role
43                    .as_ref()
44                    .map(|r| serde_json::Value::String(r.clone()))
45                    .unwrap_or(serde_json::Value::Null),
46                "resource.id" => request
47                    .resource
48                    .id
49                    .as_ref()
50                    .map(|r| serde_json::Value::String(r.clone()))
51                    .unwrap_or(serde_json::Value::Null),
52                "resource.type" => request
53                    .resource
54                    .type_
55                    .as_ref()
56                    .map(|r| serde_json::Value::String(r.clone()))
57                    .unwrap_or(serde_json::Value::Null),
58                _ => request
59                    .metadata
60                    .get(key)
61                    .cloned()
62                    .unwrap_or(serde_json::Value::Null),
63            };
64            if *expected != actual {
65                return false;
66            }
67        }
68        true
69    }
70
71    pub fn specificity_score(&self, profile: &SpecificityProfile) -> SpecificityVector {
72        let mut dims = Vec::new();
73        for dim_name in &profile.dimensions {
74            let score = self
75                .predicates
76                .iter()
77                .filter(|(k, _)| *k == dim_name || k.starts_with(&format!("{}.", dim_name)))
78                .count() as u32;
79            dims.push((dim_name.clone(), score));
80        }
81        SpecificityVector::new(dims)
82    }
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize, Default)]
86pub struct ConditionPredicates {
87    #[serde(flatten)]
88    pub conditions: HashMap<String, serde_json::Value>,
89}
90
91impl ConditionPredicates {
92    pub fn evaluate(&self, facts: &[FactEnvelope]) -> Result<ThreeValuedResult, AuthorityError> {
93        if self.conditions.is_empty() {
94            return Ok(ThreeValuedResult::True);
95        }
96
97        let mut results = Vec::new();
98        for (path, expected) in &self.conditions {
99            let fact = facts.iter().find(|f| f.path == *path);
100            match fact {
101                Some(f) if f.value.is_null() => {
102                    results.push(ThreeValuedResult::Unknown);
103                }
104                Some(f) => {
105                    if let Some(obj) = expected.as_object() {
106                        if let Some(neq) = obj.get("__neq") {
107                            results.push(if &f.value != neq {
108                                ThreeValuedResult::True
109                            } else {
110                                ThreeValuedResult::False
111                            });
112                            continue;
113                        }
114                    }
115
116                    if &f.value == expected {
117                        results.push(ThreeValuedResult::True);
118                    } else {
119                        results.push(ThreeValuedResult::False);
120                    }
121                }
122                None => {
123                    results.push(ThreeValuedResult::Unknown);
124                }
125            }
126        }
127
128        let all_true = results.iter().all(|r| *r == ThreeValuedResult::True);
129        let any_false = results.contains(&ThreeValuedResult::False);
130        let any_unknown = results.contains(&ThreeValuedResult::Unknown);
131
132        if any_false {
133            Ok(ThreeValuedResult::False)
134        } else if any_unknown {
135            Ok(ThreeValuedResult::Unknown)
136        } else if all_true {
137            Ok(ThreeValuedResult::True)
138        } else {
139            Ok(ThreeValuedResult::Unknown)
140        }
141    }
142
143    pub fn condition_specificity_score(&self, profile: &SpecificityProfile) -> u32 {
144        let condition_dim = "condition";
145        if profile.dimensions.contains(&condition_dim.to_string()) {
146            self.conditions.len() as u32
147        } else {
148            0
149        }
150    }
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
154pub struct OverrideSpec {
155    pub permits: String,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct ObligationSpec {
160    pub action: String,
161    #[serde(skip_serializing_if = "Option::is_none")]
162    pub deadline: Option<String>,
163}
164
165impl AuthorityPolicy {
166    pub fn validate(&self) -> Result<(), AuthorityError> {
167        if self.policy_id.is_empty() {
168            return Err(AuthorityError::new(
169                super::error::AuthorityErrorCode::PolicyParseError,
170                "policy_id is required",
171            ));
172        }
173        if self.modality == PolicyModality::Override && self.override_spec.is_none() {
174            return Err(AuthorityError::new(
175                super::error::AuthorityErrorCode::PolicyParseError,
176                format!(
177                    "Override policy '{}' must have override_spec",
178                    self.policy_id
179                ),
180            ));
181        }
182        Ok(())
183    }
184
185    pub fn is_candidate(&self, request: &AuthorityRequest) -> bool {
186        self.applies_to.matches(request)
187    }
188
189    pub fn evaluate_conditions(
190        &self,
191        facts: &[FactEnvelope],
192    ) -> Result<ThreeValuedResult, AuthorityError> {
193        match &self.when {
194            Some(cond) => cond.evaluate(facts),
195            None => Ok(ThreeValuedResult::True),
196        }
197    }
198
199    pub fn check_fact_requirements(
200        &self,
201        facts: &[FactEnvelope],
202        now: &chrono::DateTime<chrono::Utc>,
203    ) -> Vec<(FactRequirement, bool, Option<FactEnvelope>)> {
204        self.requires_fact
205            .iter()
206            .map(|req| {
207                let matched = facts.iter().find(|f| req.is_satisfied_by(f, now));
208                let satisfied = matched.is_some();
209                (req.clone(), satisfied, matched.cloned())
210            })
211            .collect()
212    }
213
214    pub fn compute_specificity(&self, profile: &SpecificityProfile) -> SpecificityVector {
215        let mut dims = self.applies_to.specificity_score(profile).dimensions;
216        if let Some(ref when) = self.when {
217            let cond_idx = dims.iter().position(|(d, _)| d == "condition");
218            if let Some(idx) = cond_idx {
219                dims[idx].1 += when.condition_specificity_score(profile);
220            }
221        }
222        SpecificityVector::new(dims)
223    }
224}