hyprstream_core/mac/te.rs
1//! Type-Enforcement evaluator — the **Policy Decision Point** hot-path core (S4 / #570).
2//!
3//! A TOTAL, default-deny function `(subject_ctx, object_label, action) → Decision` over the
4//! compiled TE matrix AND the independent MAC lattice floor. This is intentionally tiny and
5//! verifiable — it is the data-plane evaluator that runs per op. It is **NOT** Casbin's
6//! general string matcher (that stays control-plane; see [`crate::mac`] module docs).
7//!
8//! ## Two independent checks, conjoined (design §3, §10)
9//!
10//! ```text
11//! PERMIT(subject, object, action) ⟺
12//! te_matrix.permits(subject.type, object.type, action) ← compiled TE (authority gate)
13//! ∧ subject.clearance ⊒ object.label ← MAC floor (content-truth, IFC)
14//! ```
15//!
16//! The lattice floor is the **intrinsic** dominance on S1's [`SecurityLabel`]
17//! ([`SecurityLabel::can_access`]) — it takes no policy argument and no `Lattice` lookup, so it
18//! is uncircumventable: no TE entry, grant, or token can relax it (design §1 invariant 3).
19//! Default is DENY: an unknown subject type, object type, action, or a non-dominating /
20//! unlabeled clearance → DENY. There is no permissive mode.
21//!
22//! ## S1 reconciliation (#567 landed)
23//!
24//! - The floor is S1's intrinsic [`SecurityLabel::can_access`], not a `Lattice::can_access`
25//! trait method. The evaluator still holds the S1 [`Lattice`] policy object, but only for
26//! *well-formedness* concerns (column alignment / validation / version binding), never for
27//! the per-op order.
28//! - The subject's `clearance` carried in [`SubjectCtx`] is the clearance label the PEP
29//! already produced from a verified [`SecurityContext`] (assurance clamped to the verified
30//! key material — #548). The PEP, not this evaluator, applies that clamp.
31//! - "Unlabeled ⇒ deny" lives at the PEP boundary: a subject/object with no S1 label is
32//! `Option::None` and never reaches `evaluate`. There is deliberately no `Default`
33//! [`SecurityLabel`].
34//!
35//! ## Relationship to the AVC and to Casbin
36//!
37//! - The AVC ([`crate::mac::avc`]) caches the *output* of this function so the PEP (S2) never
38//! re-runs it per op once warm. This evaluator is what fills the cache on a miss, and is
39//! itself cheap enough to be the miss path.
40//! - Casbin authors the policy; S5's compiler lowers it into the [`TeMatrix`] entries this
41//! evaluator reads. Casbin's `Enforcer::enforce` is NEVER on this path.
42
43use crate::mac::lattice::{Compartment, Lattice, SecurityLabel};
44pub use hyprstream_rpc::annotations_capnp::ScopeAction;
45use serde::{Deserialize, Serialize};
46use std::collections::HashSet;
47
48/// Interned id of a TE *subject type* (SELinux "domain"). One per subject security context
49/// class in the compiled policy. Stable within a policy generation.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
51#[serde(transparent)]
52pub struct SubjectType(pub u32);
53
54/// Interned id of a TE *object type*. One per object class in the compiled policy.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
56#[serde(transparent)]
57pub struct ObjectType(pub u32);
58
59/// Interned id of an *action* / op. One per distinct op in the compiled policy. Maps from
60/// S3's action vocabulary at compile time — see [`Action::from_scope_action`] for the
61/// canonical [`ScopeAction`]→id assignment so a compiled matrix and a PEP agree on ids.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
63#[serde(transparent)]
64pub struct Action(pub u32);
65
66impl Action {
67 /// Intern a canonical S3 [`ScopeAction`] to its stable [`Action`] id. The id IS the
68 /// schema discriminant, so the assignment is fixed across the compiler and every PEP
69 /// (no per-process numbering drift).
70 #[inline]
71 pub const fn from_scope_action(a: ScopeAction) -> Self {
72 Action(a as u16 as u32)
73 }
74
75 /// Recover the generated schema action represented by this interned id.
76 /// Values outside the schema enum fail closed.
77 #[inline]
78 pub fn scope_action(self) -> Option<ScopeAction> {
79 u16::try_from(self.0)
80 .ok()
81 .and_then(|ordinal| ScopeAction::try_from(ordinal).ok())
82 }
83}
84
85impl From<ScopeAction> for Action {
86 #[inline]
87 fn from(a: ScopeAction) -> Self {
88 Action::from_scope_action(a)
89 }
90}
91
92/// The decision a PDP returns. Three-valued per design §8 — `Escalate` is a
93/// *deny-on-the-data-plane* that the control plane may turn into a ceiling-amendment flow,
94/// but for the per-op monitor it is NOT a permit.
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
96pub enum Decision {
97 /// Access permitted: TE matrix grants it AND the lattice floor holds.
98 Permit,
99 /// Access denied (default; TE miss, floor failure, or explicit deny).
100 Deny,
101 /// Statically denied here, but eligible for an escalation-tier ceiling amendment
102 /// (design §8). The monitor treats this as DENY for the op; the control plane may act.
103 Escalate,
104}
105
106impl Decision {
107 /// Is this a permit? The only value the PEP may treat as "allow".
108 #[inline]
109 pub fn is_permit(self) -> bool {
110 matches!(self, Decision::Permit)
111 }
112}
113
114/// The subject's security context as the evaluator sees it: a TE type (domain) plus the
115/// lattice clearance. Built by the PEP from the Ed25519-verified token/claims (design §2
116/// "subject ctx from Ed25519 claims") via S1's [`SecurityContext`] — the clearance carried
117/// here is `SecurityContext::clearance()`, with assurance already clamped to the verified
118/// key material (#548). The TE type is an interned id; the clearance is S1's `Copy`
119/// structured label — both cheap to pass per op.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121pub struct SubjectCtx {
122 /// TE subject type (SELinux domain).
123 pub subject_type: SubjectType,
124 /// Lattice clearance (S1 structured label) — checked against the object label by the
125 /// MAC floor via intrinsic dominance.
126 pub clearance: SecurityLabel,
127}
128
129/// The object's security context: a TE object type plus its content-bound label. The label
130/// comes ONLY from the content-addressed manifest (design §3, §14 "labels ONLY from
131/// manifests"), never from a token. The PEP resolves it (S1 `LabeledObject::security_label`,
132/// `None` ⇒ deny before this point) before calling the evaluator.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
134pub struct ObjectCtx {
135 /// TE object type.
136 pub object_type: ObjectType,
137 /// Content-bound label (S1 structured label) from the manifest.
138 pub label: SecurityLabel,
139}
140
141/// A single permitted TE triple `(subject_type, object_type, action)`. The compiled matrix
142/// is the *allow-set* of these triples (default-deny: absence = deny). Produced by S5's
143/// UCAN→TE compiler.
144#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
145pub struct TeRule {
146 pub subject_type: SubjectType,
147 pub object_type: ObjectType,
148 pub action: Action,
149}
150
151/// Sentinel ids (B2, #674) for auditing a decision that is NOT a per-op TE
152/// evaluation — today, the S6 grant path (`mac::exchange::evaluate_grant`),
153/// which decides against a UCAN grant's capabilities, not a compiled TE
154/// matrix. `AuditRecord` has one shape (it predates the grant path); rather
155/// than fork the schema, a grant record uses these reserved ids so it is
156/// self-describing and can never collide with a real interned TE id (which
157/// starts from 0 and is bounded by the compiled registry). `subject_type`/
158/// `object_type` reuse `u32::MAX`; `action` uses `ScopeAction`'s id space
159/// directly when the requested ability parses, or `ACTION_UNRECOGNIZED`
160/// otherwise (still recorded — an audit record for an unparseable ability is
161/// exactly the diagnosable case, not a reason to drop the record).
162pub const GRANT_PATH_SUBJECT: SubjectType = SubjectType(u32::MAX);
163pub const GRANT_PATH_OBJECT: ObjectType = ObjectType(u32::MAX);
164pub const ACTION_UNRECOGNIZED: Action = Action(u32::MAX);
165
166/// The compiled type-enforcement matrix: a flat allow-set of [`TeRule`]s. Default-deny —
167/// any triple not present is denied. This is the data-plane artifact loaded from signed
168/// compiled policy (see [`crate::mac::compiled`]). Kept as a `HashSet` so the hot-path
169/// lookup is O(1); it is also the unit S5 produces and `compiled` signs.
170///
171/// Optionally carries an *escalation-set*: triples that, while not permitted, are eligible
172/// for a ceiling-amendment (design §8). A triple in neither set is a hard `Deny`.
173#[derive(Debug, Clone, Default, Serialize, Deserialize)]
174pub struct TeMatrix {
175 allow: HashSet<TeRule>,
176 escalate: HashSet<TeRule>,
177}
178
179impl TeMatrix {
180 /// Build from explicit allow/escalate rule sets (the shape S5's compiler emits).
181 pub fn new(allow: HashSet<TeRule>, escalate: HashSet<TeRule>) -> Self {
182 Self { allow, escalate }
183 }
184
185 /// Build an allow-only matrix (no escalation band).
186 pub fn from_allow(allow: impl IntoIterator<Item = TeRule>) -> Self {
187 Self {
188 allow: allow.into_iter().collect(),
189 escalate: HashSet::new(),
190 }
191 }
192
193 /// Number of allow rules (for diagnostics / matrix hashing sanity).
194 pub fn allow_len(&self) -> usize {
195 self.allow.len()
196 }
197
198 /// Sorted-vec projection of the allow/escalate sets, for canonical (order-stable)
199 /// encoding/hashing in [`crate::mac::compiled`]. Returns `(allow, escalate)`; the caller
200 /// sorts. The hot path never calls this.
201 pub fn sorted_rules(&self) -> (Vec<TeRule>, Vec<TeRule>) {
202 (
203 self.allow.iter().copied().collect(),
204 self.escalate.iter().copied().collect(),
205 )
206 }
207
208 /// Raw TE decision for a triple, *without* the lattice floor. Total + default-deny.
209 /// Pure on the matrix contents — this is the part S5 produces policy for.
210 #[inline]
211 pub fn te_decision(&self, rule: TeRule) -> Decision {
212 if self.allow.contains(&rule) {
213 Decision::Permit
214 } else if self.escalate.contains(&rule) {
215 Decision::Escalate
216 } else {
217 Decision::Deny
218 }
219 }
220}
221
222/// The Policy Decision Point evaluator interface — **what S2 (the PEP) calls per op**.
223///
224/// Implementations are TOTAL and default-deny: every well-formed call returns a [`Decision`]
225/// and never panics. This is the clean contract the AVC wraps and S5/S6 produce policy for.
226pub trait TeEvaluator: Send + Sync {
227 /// Evaluate one operation. TOTAL, default-deny. Conjoins the compiled TE decision with
228 /// the independent lattice floor: a `Permit` requires BOTH; the floor can only deny.
229 fn evaluate(&self, subject: SubjectCtx, object: ObjectCtx, action: Action) -> Decision;
230
231 /// The policy generation this evaluator answers for. The AVC tags cached entries with
232 /// it so a policy reload invalidates stale decisions (no per-op staleness check beyond
233 /// a generation-counter compare). Equals the embedded lattice's
234 /// [`LatticeVersion::generation`].
235 fn generation(&self) -> u64;
236}
237
238/// Concrete PDP: a compiled [`TeMatrix`] + the S1 [`Lattice`] policy object. Small, total,
239/// allocation-free on the hot path. This is the verifiable TCB core.
240///
241/// The [`Lattice`] is held for *well-formedness* and *column alignment*, NOT for the per-op
242/// order: the floor uses S1's intrinsic [`SecurityLabel::can_access`]. The PDP's `generation`
243/// is bound to `lattice.version().generation()` at construction — the desync-proof binding
244/// (#570): the same lattice bytes that minted a label's compartment bits also tag the
245/// compiled policy that evaluates it.
246pub struct LatticeTeEvaluator {
247 matrix: TeMatrix,
248 lattice: Lattice,
249 generation: u64,
250}
251
252impl LatticeTeEvaluator {
253 /// Construct from a compiled matrix and the S1 lattice policy. The policy generation is
254 /// taken from the lattice version — they are definitionally equal (#570 reconciliation):
255 /// a compiled TE matrix is only valid against the lattice generation that minted its
256 /// compartment bit assignments.
257 pub fn new(matrix: TeMatrix, lattice: Lattice) -> Self {
258 let generation = lattice.version().generation();
259 Self {
260 matrix,
261 lattice,
262 generation,
263 }
264 }
265
266 /// Borrow the matrix (diagnostics / re-signing).
267 pub fn matrix(&self) -> &TeMatrix {
268 &self.matrix
269 }
270
271 /// Borrow the lattice policy (column alignment / validation / re-serialization into the
272 /// signed `CompiledPolicy`).
273 pub fn lattice(&self) -> &Lattice {
274 &self.lattice
275 }
276
277 /// The compartment vocabulary in **canonical bit-index order** (`names()[i]` is the
278 /// compartment interned at bit `i`). A TE-matrix builder / compiler aligns its
279 /// compartment columns to label bits by iterating this — NEVER by hardcoding compartment
280 /// names — so a column index always equals the [`CompartmentSet`](crate::mac::lattice::CompartmentSet)
281 /// bit a [`SecurityLabel`] carries.
282 pub fn compartment_columns(&self) -> &[Compartment] {
283 self.lattice.compartment_names()
284 }
285}
286
287impl TeEvaluator for LatticeTeEvaluator {
288 #[inline]
289 fn evaluate(&self, subject: SubjectCtx, object: ObjectCtx, action: Action) -> Decision {
290 // 1. MAC floor FIRST and independently — S1 intrinsic dominance, content-bound and
291 // uncircumventable. Fail-closed: a non-dominating clearance → DENY, regardless of
292 // what the TE matrix says (design §1 inv.3, §10). Unlabeled subject/object never
293 // reach here (the PEP denies on `None` before constructing the contexts).
294 if !subject.clearance.can_access(&object.label) {
295 return Decision::Deny;
296 }
297 // 2. Compiled TE decision (the authority gate). Default-deny by construction.
298 self.matrix.te_decision(TeRule {
299 subject_type: subject.subject_type,
300 object_type: object.object_type,
301 action,
302 })
303 }
304
305 #[inline]
306 fn generation(&self) -> u64 {
307 self.generation
308 }
309}
310
311#[cfg(test)]
312#[allow(clippy::unwrap_used)]
313mod tests {
314 use super::*;
315 use crate::mac::lattice::{Assurance, Compartment, LatticeVersion, Level};
316
317 fn rule(s: u32, o: u32, a: u32) -> TeRule {
318 TeRule {
319 subject_type: SubjectType(s),
320 object_type: ObjectType(o),
321 action: Action(a),
322 }
323 }
324
325 fn lattice() -> Lattice {
326 Lattice::new(
327 LatticeVersion(7),
328 [Compartment::new("pii"), Compartment::new("finance")],
329 )
330 }
331
332 /// A clearance label at (level, assurance, compartment names).
333 fn clearance(level: Level, assurance: Assurance, names: &[&str]) -> SecurityLabel {
334 lattice()
335 .label(level, assurance, names.iter().map(|n| Compartment::new(*n)))
336 .unwrap()
337 }
338
339 fn subj(t: u32, clr: SecurityLabel) -> SubjectCtx {
340 SubjectCtx {
341 subject_type: SubjectType(t),
342 clearance: clr,
343 }
344 }
345
346 fn obj(t: u32, lbl: SecurityLabel) -> ObjectCtx {
347 ObjectCtx {
348 object_type: ObjectType(t),
349 label: lbl,
350 }
351 }
352
353 fn eval() -> LatticeTeEvaluator {
354 // Allow (subj=1, obj=1, act=1). Escalate (subj=1, obj=1, act=2).
355 let mut allow = HashSet::new();
356 allow.insert(rule(1, 1, 1));
357 let mut escalate = HashSet::new();
358 escalate.insert(rule(1, 1, 2));
359 LatticeTeEvaluator::new(TeMatrix::new(allow, escalate), lattice())
360 }
361
362 #[test]
363 fn generation_bound_to_lattice_version() {
364 // #570 reconciliation: generation == LatticeVersion::generation.
365 assert_eq!(eval().generation(), 7);
366 }
367
368 #[test]
369 fn permit_requires_te_and_floor() {
370 let e = eval();
371 let high = clearance(Level::Secret, Assurance::PqHybrid, &["pii"]);
372 let low = clearance(Level::Confidential, Assurance::Classical, &[]);
373 // TE allows AND clearance ⊒ label: permit.
374 assert_eq!(
375 e.evaluate(subj(1, high), obj(1, low), Action(1)),
376 Decision::Permit
377 );
378 }
379
380 #[test]
381 fn floor_denies_even_when_te_allows() {
382 let e = eval();
383 // TE allows but a Public clearance does NOT dominate a Secret label: floor denies.
384 let clr = clearance(Level::Public, Assurance::Classical, &[]);
385 let lbl = clearance(Level::Secret, Assurance::Classical, &[]);
386 assert_eq!(
387 e.evaluate(subj(1, clr), obj(1, lbl), Action(1)),
388 Decision::Deny
389 );
390 }
391
392 #[test]
393 fn floor_denies_on_missing_compartment() {
394 let e = eval();
395 // High level/assurance but NOT cleared into the object's "finance" compartment.
396 let clr = clearance(Level::Secret, Assurance::PqHybrid, &["pii"]);
397 let lbl = clearance(Level::Public, Assurance::Unverified, &["finance"]);
398 assert_eq!(
399 e.evaluate(subj(1, clr), obj(1, lbl), Action(1)),
400 Decision::Deny
401 );
402 }
403
404 #[test]
405 fn assurance_floor_denies_classical_on_pqc_object() {
406 // #548 via the SAME dominance check: a classical clearance can't read a pq-hybrid label.
407 let e = eval();
408 let clr = clearance(Level::Secret, Assurance::Classical, &["pii"]);
409 let lbl = clearance(Level::Public, Assurance::PqHybrid, &[]);
410 assert_eq!(
411 e.evaluate(subj(1, clr), obj(1, lbl), Action(1)),
412 Decision::Deny
413 );
414 }
415
416 #[test]
417 fn default_deny_on_te_miss() {
418 let e = eval();
419 let high = clearance(Level::Secret, Assurance::PqHybrid, &["pii"]);
420 let low = clearance(Level::Public, Assurance::Classical, &[]);
421 // Floor holds but no TE rule for action 9: deny.
422 assert_eq!(
423 e.evaluate(subj(1, high), obj(1, low), Action(9)),
424 Decision::Deny
425 );
426 // Unknown subject type: deny.
427 assert_eq!(
428 e.evaluate(subj(5, high), obj(1, low), Action(1)),
429 Decision::Deny
430 );
431 }
432
433 #[test]
434 fn escalate_is_not_a_permit_but_floor_still_first() {
435 let e = eval();
436 let high = clearance(Level::Secret, Assurance::PqHybrid, &["pii"]);
437 let low = clearance(Level::Public, Assurance::Classical, &[]);
438 // Floor holds, TE says escalate.
439 assert_eq!(
440 e.evaluate(subj(1, high), obj(1, low), Action(2)),
441 Decision::Escalate
442 );
443 assert!(!Decision::Escalate.is_permit());
444 // But if the floor fails, escalate downgrades to a hard deny (floor is independent).
445 let pub_clr = clearance(Level::Public, Assurance::Classical, &[]);
446 let sec_lbl = clearance(Level::Secret, Assurance::Classical, &[]);
447 assert_eq!(
448 e.evaluate(subj(1, pub_clr), obj(1, sec_lbl), Action(2)),
449 Decision::Deny
450 );
451 }
452
453 #[test]
454 fn scope_action_interns_to_schema_discriminant() {
455 // The generated capnp enum is the source of the ids used by compiler and PEP.
456 for scope_action in crate::auth::SCHEMA_SCOPE_ACTIONS {
457 let action = Action::from(scope_action);
458 assert_eq!(action.scope_action(), Some(scope_action));
459 assert_eq!(action.0, u16::from(scope_action) as u32);
460 }
461 assert_eq!(Action::from(ScopeAction::Subscribe), Action(1));
462 assert_eq!(Action::from(ScopeAction::Manage), Action(10));
463 assert_eq!(Action::from(ScopeAction::MeshDelta), Action(13));
464 assert_eq!(Action(u32::MAX).scope_action(), None);
465 }
466
467 #[test]
468 fn compartment_columns_align_to_bits() {
469 let e = eval();
470 let cols = e.compartment_columns();
471 // Column index == the bit a SecurityLabel carries for that compartment name.
472 assert_eq!(cols[0], Compartment::new("pii"));
473 assert_eq!(cols[1], Compartment::new("finance"));
474 assert_eq!(e.lattice().bit_of(&Compartment::new("finance")), Some(1));
475 }
476}