Skip to main content

lean_ctx_ext/core/trust/
policy.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Small policy-evaluation primitives.
3
4use serde::{Deserialize, Serialize};
5
6use super::classification::{ClassifiedData, SecurityClassification};
7use super::identity::IdentityContext;
8
9/// Result of a local policy evaluation.
10#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
11pub enum PolicyDecision {
12    /// The requested action may proceed.
13    Allow,
14    /// The requested action must not proceed.
15    Deny,
16    /// The action may proceed only with an audit/evidence record.
17    Audit,
18}
19
20/// A portable rule descriptor. Enterprise systems may attach richer rule
21/// languages while preserving these interoperable fields.
22#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
23pub struct PolicyRule {
24    /// Condition such as `classification>=confidential`, `always`, or `*`.
25    pub condition: String,
26    /// Exact action or prefix wildcard to which the rule applies.
27    pub action: String,
28    /// Whether a matching action must produce evidence.
29    pub evidence_required: bool,
30}
31
32impl PolicyRule {
33    /// Creates a rule descriptor.
34    #[must_use]
35    pub fn new(
36        condition: impl Into<String>,
37        action: impl Into<String>,
38        evidence_required: bool,
39    ) -> Self {
40        Self {
41            condition: condition.into(),
42            action: action.into(),
43            evidence_required,
44        }
45    }
46}
47
48/// Context projection consumed by policy evaluators.
49pub trait PolicyContext {
50    /// Returns a classification when the context carries one.
51    fn classification(&self) -> Option<SecurityClassification>;
52
53    /// Returns an identity when the context carries one.
54    fn identity(&self) -> Option<&IdentityContext>;
55}
56
57impl PolicyContext for IdentityContext {
58    fn classification(&self) -> Option<SecurityClassification> {
59        None
60    }
61
62    fn identity(&self) -> Option<&IdentityContext> {
63        Some(self)
64    }
65}
66
67impl PolicyContext for SecurityClassification {
68    fn classification(&self) -> Option<SecurityClassification> {
69        Some(*self)
70    }
71
72    fn identity(&self) -> Option<&IdentityContext> {
73        None
74    }
75}
76
77impl<T> PolicyContext for ClassifiedData<T> {
78    fn classification(&self) -> Option<SecurityClassification> {
79        Some(self.classification)
80    }
81
82    fn identity(&self) -> Option<&IdentityContext> {
83        None
84    }
85}
86
87/// Interface implemented by local or enterprise policy evaluators.
88pub trait PolicyEvaluator {
89    /// Evaluates `action` against the supplied portable context.
90    fn evaluate(&self, context: &dyn PolicyContext, action: &str) -> PolicyDecision;
91}
92
93/// Reference evaluator that allows every action.
94#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
95pub struct AllowAll;
96
97impl PolicyEvaluator for AllowAll {
98    fn evaluate(&self, _context: &dyn PolicyContext, _action: &str) -> PolicyDecision {
99        PolicyDecision::Allow
100    }
101}
102
103/// Reference evaluator that denies every action.
104#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
105pub struct DenyAll;
106
107impl PolicyEvaluator for DenyAll {
108    fn evaluate(&self, _context: &dyn PolicyContext, _action: &str) -> PolicyDecision {
109        PolicyDecision::Deny
110    }
111}
112
113/// Deterministic policy evaluator that applies a maximum classification and
114/// optional evidence rules.
115#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
116pub struct ClassificationBased {
117    /// Highest classification allowed without a deny decision.
118    pub maximum_allowed: SecurityClassification,
119    /// Additional action/evidence rules.
120    #[serde(default)]
121    pub rules: Vec<PolicyRule>,
122}
123
124impl ClassificationBased {
125    /// Creates a classification gate with the supplied maximum level.
126    #[must_use]
127    pub fn new(maximum_allowed: SecurityClassification) -> Self {
128        Self {
129            maximum_allowed,
130            rules: Vec::new(),
131        }
132    }
133
134    /// Creates a gate with an initial rule set.
135    #[must_use]
136    pub fn from_rules(maximum_allowed: SecurityClassification, rules: Vec<PolicyRule>) -> Self {
137        Self {
138            maximum_allowed,
139            rules,
140        }
141    }
142
143    /// Adds a rule in builder style.
144    #[must_use]
145    pub fn with_rule(mut self, rule: PolicyRule) -> Self {
146        self.rules.push(rule);
147        self
148    }
149
150    /// Adds a rule to the evaluator.
151    pub fn add_rule(&mut self, rule: PolicyRule) {
152        self.rules.push(rule);
153    }
154}
155
156impl PolicyEvaluator for ClassificationBased {
157    fn evaluate(&self, context: &dyn PolicyContext, action: &str) -> PolicyDecision {
158        let Some(classification) = context.classification() else {
159            // A classification gate cannot prove safety for an unclassified
160            // context, so it requests an auditable decision.
161            return PolicyDecision::Audit;
162        };
163
164        if classification > self.maximum_allowed {
165            return PolicyDecision::Deny;
166        }
167
168        for rule in &self.rules {
169            if action_matches(&rule.action, action)
170                && condition_matches(&rule.condition, classification)
171                && rule.evidence_required
172            {
173                return PolicyDecision::Audit;
174            }
175        }
176        PolicyDecision::Allow
177    }
178}
179
180fn action_matches(pattern: &str, action: &str) -> bool {
181    let pattern = pattern.trim();
182    pattern == "*"
183        || pattern.eq_ignore_ascii_case(action.trim())
184        || pattern
185            .strip_suffix('*')
186            .is_some_and(|prefix| action.trim().starts_with(prefix))
187}
188
189fn condition_matches(condition: &str, classification: SecurityClassification) -> bool {
190    let condition = condition.trim();
191    if condition.is_empty() || condition == "*" || condition.eq_ignore_ascii_case("always") {
192        return true;
193    }
194
195    let (operator, value) = if let Some(value) = condition.strip_prefix("classification>=") {
196        (">=", value)
197    } else if let Some(value) = condition.strip_prefix("classification<=") {
198        ("<=", value)
199    } else if let Some(value) = condition.strip_prefix("classification=") {
200        ("=", value)
201    } else if let Some(value) = condition.strip_prefix("classification:") {
202        ("=", value)
203    } else {
204        ("=", condition)
205    };
206
207    let Some(required) = SecurityClassification::parse(value) else {
208        return false;
209    };
210    match operator {
211        ">=" => classification >= required,
212        "<=" => classification <= required,
213        "=" => classification == required,
214        _ => false,
215    }
216}