Skip to main content

lean_ctx_ext/core/trust/
classification.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Data classification and residency metadata.
3
4use serde::{Deserialize, Serialize};
5
6use super::identity::TenantId;
7use super::tenant_isolation::TenantBoundary;
8
9/// Ordered sensitivity levels. Higher levels must not flow to lower-trust
10/// destinations without an explicit policy decision.
11#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
12#[repr(u8)]
13pub enum SecurityClassification {
14    /// Intended for unrestricted disclosure.
15    #[default]
16    Public = 0,
17    /// Non-public operational information.
18    Internal = 1,
19    /// Information requiring an authorized recipient.
20    Confidential = 2,
21    /// Information requiring explicit need-to-know controls.
22    Restricted = 3,
23    /// Highest sensitivity; enterprise controls must explicitly authorize use.
24    TopSecret = 4,
25}
26
27impl SecurityClassification {
28    /// Returns the stable numeric ordering used by policy evaluators.
29    #[must_use]
30    pub const fn rank(self) -> u8 {
31        self as u8
32    }
33
34    /// Returns whether data at this level may flow to `destination`.
35    #[must_use]
36    pub const fn may_flow_to(self, destination: Self) -> bool {
37        self.rank() <= destination.rank()
38    }
39
40    /// Parses the stable case-insensitive name used in policy conditions.
41    #[must_use]
42    pub fn parse(value: &str) -> Option<Self> {
43        match value.trim().to_ascii_lowercase().as_str() {
44            "public" => Some(Self::Public),
45            "internal" => Some(Self::Internal),
46            "confidential" => Some(Self::Confidential),
47            "restricted" => Some(Self::Restricted),
48            "topsecret" | "top_secret" | "top-secret" => Some(Self::TopSecret),
49            _ => None,
50        }
51    }
52}
53
54/// Region constraints attached to classified data.
55#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
56pub struct ResidencyRequirement {
57    /// Regions in which the data may be stored or processed. Empty means
58    /// unrestricted unless `data_sovereign` is true.
59    #[serde(default)]
60    pub allowed_regions: Vec<String>,
61    /// Regions that are forbidden even when they appear in the allow list.
62    #[serde(default)]
63    pub prohibited_regions: Vec<String>,
64    /// Requires a sovereign deployment and therefore a non-empty allow list.
65    #[serde(default)]
66    pub data_sovereign: bool,
67}
68
69impl ResidencyRequirement {
70    /// Creates an unconstrained residency requirement.
71    #[must_use]
72    pub fn unrestricted() -> Self {
73        Self::default()
74    }
75
76    /// Creates a requirement allowing only the supplied regions.
77    #[must_use]
78    pub fn allowed_in<I, S>(regions: I) -> Self
79    where
80        I: IntoIterator<Item = S>,
81        S: Into<String>,
82    {
83        Self {
84            allowed_regions: regions.into_iter().map(Into::into).collect(),
85            ..Self::default()
86        }
87    }
88
89    /// Creates a sovereign requirement for the supplied regions.
90    #[must_use]
91    pub fn sovereign<I, S>(regions: I) -> Self
92    where
93        I: IntoIterator<Item = S>,
94        S: Into<String>,
95    {
96        Self {
97            allowed_regions: regions.into_iter().map(Into::into).collect(),
98            data_sovereign: true,
99            ..Self::default()
100        }
101    }
102
103    /// Adds one allowed region.
104    #[must_use]
105    pub fn with_allowed_region(mut self, region: impl Into<String>) -> Self {
106        self.allowed_regions.push(region.into());
107        self
108    }
109
110    /// Adds one prohibited region.
111    #[must_use]
112    pub fn with_prohibited_region(mut self, region: impl Into<String>) -> Self {
113        self.prohibited_regions.push(region.into());
114        self
115    }
116
117    /// Marks the requirement as sovereign.
118    #[must_use]
119    pub const fn with_sovereignty(mut self, sovereign: bool) -> Self {
120        self.data_sovereign = sovereign;
121        self
122    }
123
124    /// Checks whether processing in `region` is permitted.
125    #[must_use]
126    pub fn allows_region(&self, region: &str) -> bool {
127        let region = region.trim();
128        if region.is_empty() || (self.data_sovereign && self.allowed_regions.is_empty()) {
129            return false;
130        }
131
132        let prohibited = self
133            .prohibited_regions
134            .iter()
135            .any(|candidate| region_matches(candidate, region));
136        if prohibited {
137            return false;
138        }
139
140        self.allowed_regions.is_empty()
141            || self
142                .allowed_regions
143                .iter()
144                .any(|candidate| region_matches(candidate, region))
145    }
146
147    /// Returns a validation error for an internally contradictory requirement.
148    pub fn validate(&self) -> Result<(), String> {
149        if self.data_sovereign && self.allowed_regions.is_empty() {
150            return Err("sovereign residency requires at least one allowed region".to_owned());
151        }
152        Ok(())
153    }
154}
155
156/// A value carrying its sensitivity and residency requirements together.
157#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
158pub struct ClassifiedData<T> {
159    /// The protected value.
160    pub data: T,
161    /// Sensitivity classification for the value.
162    pub classification: SecurityClassification,
163    /// Storage and processing constraints for the value.
164    pub residency: ResidencyRequirement,
165}
166
167impl<T> ClassifiedData<T> {
168    /// Wraps `data` with classification and residency metadata.
169    #[must_use]
170    pub fn new(
171        data: T,
172        classification: SecurityClassification,
173        residency: ResidencyRequirement,
174    ) -> Self {
175        Self {
176            data,
177            classification,
178            residency,
179        }
180    }
181
182    /// Borrows the wrapped value.
183    #[must_use]
184    pub const fn as_ref(&self) -> &T {
185        &self.data
186    }
187
188    /// Maps the wrapped value while preserving the security metadata.
189    #[must_use]
190    pub fn map<U>(self, map: impl FnOnce(T) -> U) -> ClassifiedData<U> {
191        ClassifiedData {
192            data: map(self.data),
193            classification: self.classification,
194            residency: self.residency,
195        }
196    }
197
198    /// Unwraps the protected value.
199    #[must_use]
200    pub fn into_inner(self) -> T {
201        self.data
202    }
203
204    /// Checks whether the value may be processed in `region`.
205    #[must_use]
206    pub fn is_allowed_in(&self, region: &str) -> bool {
207        self.residency.allows_region(region)
208    }
209}
210
211impl<T: TenantBoundary> TenantBoundary for ClassifiedData<T> {
212    fn tenant_id(&self) -> &TenantId {
213        self.data.tenant_id()
214    }
215}
216
217/// One content-type-to-classification rule.
218#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
219pub struct ClassificationRule {
220    /// Exact content type or a prefix pattern ending in `*`.
221    pub content_type: String,
222    /// Classification assigned when the rule matches.
223    pub classification: SecurityClassification,
224}
225
226/// Deterministic reference policy for automatic classification by content type.
227#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
228pub struct ClassificationPolicy {
229    /// Classification used when no rule matches.
230    pub default: SecurityClassification,
231    /// Rules evaluated as a set; the highest matching classification wins.
232    #[serde(default)]
233    pub rules: Vec<ClassificationRule>,
234}
235
236impl Default for ClassificationPolicy {
237    fn default() -> Self {
238        Self {
239            default: SecurityClassification::Public,
240            rules: Vec::new(),
241        }
242    }
243}
244
245impl ClassificationPolicy {
246    /// Creates a policy with the supplied fallback classification.
247    #[must_use]
248    pub fn new(default: SecurityClassification) -> Self {
249        Self {
250            default,
251            rules: Vec::new(),
252        }
253    }
254
255    /// Adds a content-type rule in builder style.
256    #[must_use]
257    pub fn with_rule(
258        mut self,
259        content_type: impl Into<String>,
260        classification: SecurityClassification,
261    ) -> Self {
262        self.add_rule(content_type, classification);
263        self
264    }
265
266    /// Adds a content-type rule.
267    pub fn add_rule(
268        &mut self,
269        content_type: impl Into<String>,
270        classification: SecurityClassification,
271    ) {
272        self.rules.push(ClassificationRule {
273            content_type: content_type.into(),
274            classification,
275        });
276    }
277
278    /// Classifies a content type using the most restrictive matching rule.
279    #[must_use]
280    pub fn classify(&self, content_type: &str) -> SecurityClassification {
281        self.rules
282            .iter()
283            .filter(|rule| content_type_matches(&rule.content_type, content_type))
284            .map(|rule| rule.classification)
285            .max()
286            .unwrap_or(self.default)
287    }
288
289    /// Alias emphasizing that this is an automatic classification decision.
290    #[must_use]
291    pub fn auto_classify(&self, content_type: &str) -> SecurityClassification {
292        self.classify(content_type)
293    }
294}
295
296fn region_matches(pattern: &str, value: &str) -> bool {
297    let pattern = pattern.trim();
298    pattern == "*" || pattern.eq_ignore_ascii_case(value)
299}
300
301fn content_type_matches(pattern: &str, value: &str) -> bool {
302    let pattern = pattern.trim();
303    if pattern == "*" || pattern.eq_ignore_ascii_case(value.trim()) {
304        return true;
305    }
306    pattern
307        .strip_suffix('*')
308        .is_some_and(|prefix| value.trim().starts_with(prefix.trim_end_matches('/')))
309}