Skip to main content

hyprstream_core/mac/
avc.rs

1//! Access Vector Cache — the fast local decision cache the PEP consults per op (S4 / #570).
2//!
3//! SELinux-style AVC: the PEP (S2) asks the AVC for a decision on every op; on a hit it
4//! returns a cached [`Decision`] with **no Casbin, no signature verify, no lattice walk** —
5//! just a hash lookup. On a miss it calls the [`TeEvaluator`] (the PDP) once, caches the
6//! result, and returns it. Fail-closed: any ambiguity (wrong generation, poisoned lock,
7//! evaluator absent) → DENY.
8//!
9//! ## The hot path (what must be cheap)
10//!
11//! ```text
12//! PEP.check(op) → AVC.decide(key) ─hit→  return cached Decision        (sub-µs, lock-free read)
13//!                                └miss→  evaluator.evaluate(...) ; insert ; return
14//! ```
15//!
16//! The cache KEY is `(generation, subject_type, clearance, object_type, label, action)`. The
17//! TE types are interned ids and the `clearance`/`label` are S1's structured
18//! [`SecurityLabel`]s — which are `Copy + Hash` (a packed `level/assurance/u64-bitset`, S1
19//! confirmed cheap), so the whole key is `Copy` and hashes cheaply with **no dominance walk
20//! and no signature verify on a hit** (#570 requirement). We deliberately key on the
21//! *resolved context*, not on raw strings/paths: string matching (Casbin's job) is done once
22//! at compile time, never per op.
23//!
24//! ## Token = distributed AVC entry (design §2, §6)
25//!
26//! The OAuth access token IS an AVC entry, minted by the authority and carried by the
27//! subject. It encodes `{label_ceiling, op_set, ttl}` (design §11). The mapping:
28//!
29//! ```text
30//! access token T  ──(verified ONCE at bind/refresh by the PEP)──►  AvcSeed
31//!   T.cnf / sub      → subject_type + clearance (subject ctx, design §2)
32//!   T.label_ceiling  → the max object label the token authorizes (per-op floor still applies)
33//!   T.op_set         → the actions the token authorizes
34//!   T.exp            → AvcEntry.valid_until  (ttl-bounded cache lifetime)
35//! ```
36//!
37//! Verifying the token signature is a **bind/refresh-time** event (design §7: mint per-task,
38//! AVC caches for ttl), NOT per op. Once seeded, per-op decisions are local lookups. The
39//! token's `{label_ceiling, op_set}` are an *additional* deny-only gate the PEP applies via
40//! [`TokenScope`]; the mandatory lattice floor + TE matrix are still evaluated independently
41//! by the PDP (a token can only narrow — design §10).
42
43use crate::mac::lattice::SecurityLabel;
44use crate::mac::te::{
45    Action, Decision, ObjectCtx, ObjectType, SubjectCtx, SubjectType, TeEvaluator,
46};
47use dashmap::DashMap;
48use std::sync::Arc;
49use std::time::Instant;
50
51/// Cache key: the fully-resolved, interned per-op context. All `Copy` ids → cheap hash.
52/// Tagged with `generation` so a policy reload (new generation) misses every stale entry
53/// without an explicit flush walk.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55pub struct AvcKey {
56    pub generation: u64,
57    pub subject_type: SubjectType,
58    pub clearance: SecurityLabel,
59    pub object_type: ObjectType,
60    pub label: SecurityLabel,
61    pub action: Action,
62}
63
64impl AvcKey {
65    /// Assemble a key from the resolved contexts the PEP already has in hand.
66    #[inline]
67    pub fn new(generation: u64, subject: SubjectCtx, object: ObjectCtx, action: Action) -> Self {
68        Self {
69            generation,
70            subject_type: subject.subject_type,
71            clearance: subject.clearance,
72            object_type: object.object_type,
73            label: object.label,
74            action,
75        }
76    }
77}
78
79/// A cached decision. `valid_until` bounds the entry to the token/policy ttl (design §7);
80/// `None` means "valid until the generation rolls" (policy-derived decisions with no token
81/// ttl). Fail-closed: an expired entry is treated as a miss, not a stale permit.
82#[derive(Debug, Clone, Copy)]
83struct AvcEntry {
84    decision: Decision,
85    valid_until: Option<Instant>,
86}
87
88impl AvcEntry {
89    #[inline]
90    fn is_live(&self, now: Instant) -> bool {
91        match self.valid_until {
92            Some(deadline) => now < deadline,
93            None => true,
94        }
95    }
96}
97
98/// The token-derived gate the PEP applies on top of the PDP decision (design §10 / §6).
99/// Deny-only: the token can only *narrow*. The PDP (lattice floor + TE matrix) is evaluated
100/// independently; this just enforces what the access token authorized.
101#[derive(Debug, Clone)]
102pub struct TokenScope {
103    /// Max object label the token authorizes (`object.label ⊑ label_ceiling`). The PEP
104    /// supplies the lattice to compare; here we keep the ceiling and the authorized ops.
105    pub label_ceiling: SecurityLabel,
106    /// The actions the token authorizes (`op ∈ op_set`).
107    pub op_set: Arc<[Action]>,
108    /// When the token (hence this scope) expires — the cache ttl bound.
109    pub valid_until: Instant,
110}
111
112impl TokenScope {
113    /// Does this token authorize `action`? Deny-only check.
114    #[inline]
115    pub fn authorizes_action(&self, action: Action) -> bool {
116        self.op_set.contains(&action)
117    }
118}
119
120/// The Access Vector Cache interface — **what the PEP (S2) calls per op**.
121///
122/// TOTAL + fail-closed. `decide` returns a [`Decision`] for every call and never panics.
123pub trait Avc: Send + Sync {
124    /// Per-op decision. Hit → cached; miss → evaluate-and-cache. Fail-closed.
125    fn decide(&self, subject: SubjectCtx, object: ObjectCtx, action: Action) -> Decision;
126
127    /// Per-op decision additionally gated by a token scope (the distributed-AVC-entry path).
128    /// The result is `Permit` only if the PDP permits AND the token authorizes the action.
129    /// The label-ceiling comparison requires the lattice and is done by the PDP-side floor;
130    /// this method applies the op-set + ttl gate. Default-deny.
131    fn decide_with_token(
132        &self,
133        subject: SubjectCtx,
134        object: ObjectCtx,
135        action: Action,
136        token: &TokenScope,
137    ) -> Decision;
138
139    /// Drop all cached decisions (e.g. on revocation broadcast). Generation rollover already
140    /// invalidates implicitly; this is for explicit revocation (design §6 refresh path).
141    fn flush(&self);
142}
143
144/// Concrete AVC over a [`TeEvaluator`] PDP and a concurrent map. Lock-free reads via
145/// `dashmap`; the only work on a hit is a hash + ttl compare.
146pub struct CachingAvc<E: TeEvaluator> {
147    evaluator: Arc<E>,
148    cache: DashMap<AvcKey, AvcEntry>,
149}
150
151impl<E: TeEvaluator> CachingAvc<E> {
152    /// Wrap a PDP evaluator. The AVC inherits the evaluator's generation for key tagging.
153    pub fn new(evaluator: Arc<E>) -> Self {
154        Self {
155            evaluator,
156            cache: DashMap::new(),
157        }
158    }
159
160    /// Number of live-or-stale cached entries (diagnostics).
161    pub fn len(&self) -> usize {
162        self.cache.len()
163    }
164
165    /// Whether the cache is empty.
166    pub fn is_empty(&self) -> bool {
167        self.cache.is_empty()
168    }
169
170    /// Core lookup-or-evaluate. `valid_until` bounds a freshly computed entry (token ttl).
171    #[inline]
172    fn decide_inner(
173        &self,
174        subject: SubjectCtx,
175        object: ObjectCtx,
176        action: Action,
177        valid_until: Option<Instant>,
178    ) -> Decision {
179        let generation = self.evaluator.generation();
180        let key = AvcKey::new(generation, subject, object, action);
181        let now = Instant::now();
182
183        // Fast path: live hit. `dashmap` read does not block other readers.
184        if let Some(entry) = self.cache.get(&key) {
185            if entry.is_live(now) {
186                return entry.decision;
187            }
188            // Stale/expired → fall through to recompute (treated as a miss, fail-closed).
189        }
190
191        // Miss / expired: evaluate ONCE via the PDP, then cache.
192        let decision = self.evaluator.evaluate(subject, object, action);
193        self.cache.insert(
194            key,
195            AvcEntry {
196                decision,
197                valid_until,
198            },
199        );
200        decision
201    }
202}
203
204impl<E: TeEvaluator> Avc for CachingAvc<E> {
205    #[inline]
206    fn decide(&self, subject: SubjectCtx, object: ObjectCtx, action: Action) -> Decision {
207        self.decide_inner(subject, object, action, None)
208    }
209
210    #[inline]
211    fn decide_with_token(
212        &self,
213        subject: SubjectCtx,
214        object: ObjectCtx,
215        action: Action,
216        token: &TokenScope,
217    ) -> Decision {
218        // Token gate (deny-only): expired token or op not in op_set → DENY without touching
219        // the PDP. (The label_ceiling ⊒ object.label check is the PDP-side lattice floor's
220        // job — the token's ceiling is enforced by seeding subject.clearance ⊓ ceiling at
221        // bind time; see module docs. We keep the ceiling on the scope for that seeding and
222        // for audit, and do not re-walk the lattice here.)
223        if Instant::now() >= token.valid_until {
224            return Decision::Deny;
225        }
226        if !token.authorizes_action(action) {
227            return Decision::Deny;
228        }
229        // PDP decision, cached with the token ttl as the entry lifetime.
230        let decision = self.decide_inner(subject, object, action, Some(token.valid_until));
231        // Conjunction: permit only if the PDP permitted. (Token already gated above.)
232        if decision.is_permit() {
233            Decision::Permit
234        } else {
235            decision
236        }
237    }
238
239    fn flush(&self) {
240        self.cache.clear();
241    }
242}
243
244#[cfg(test)]
245#[allow(clippy::unwrap_used)]
246mod tests {
247    use super::*;
248    use crate::mac::lattice::{
249        Assurance, Compartment, CompartmentSet, Lattice, LatticeVersion, Level, SecurityLabel,
250    };
251    use crate::mac::te::{LatticeTeEvaluator, TeMatrix, TeRule};
252    use std::collections::HashSet;
253    use std::sync::atomic::{AtomicU32, Ordering};
254    use std::time::Duration;
255
256    fn rule(s: u32, o: u32, a: u32) -> TeRule {
257        TeRule {
258            subject_type: SubjectType(s),
259            object_type: ObjectType(o),
260            action: Action(a),
261        }
262    }
263
264    fn lattice() -> Lattice {
265        Lattice::new(LatticeVersion(1), [Compartment::new("pii")])
266    }
267
268    /// A high (Secret/pq-hybrid) clearance that dominates the low object label below.
269    fn high() -> SecurityLabel {
270        SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY)
271    }
272    /// A low (Public/classical) object label, dominated by `high()`.
273    fn low() -> SecurityLabel {
274        SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY)
275    }
276
277    fn subj(t: u32, clr: SecurityLabel) -> SubjectCtx {
278        SubjectCtx {
279            subject_type: SubjectType(t),
280            clearance: clr,
281        }
282    }
283    fn obj(t: u32, lbl: SecurityLabel) -> ObjectCtx {
284        ObjectCtx {
285            object_type: ObjectType(t),
286            label: lbl,
287        }
288    }
289
290    fn avc() -> CachingAvc<LatticeTeEvaluator> {
291        let mut allow = HashSet::new();
292        allow.insert(rule(1, 1, 1));
293        let e = LatticeTeEvaluator::new(TeMatrix::from_allow(allow), lattice());
294        CachingAvc::new(Arc::new(e))
295    }
296
297    #[test]
298    fn hit_returns_cached_decision() {
299        let a = avc();
300        assert_eq!(
301            a.decide(subj(1, high()), obj(1, low()), Action(1)),
302            Decision::Permit
303        );
304        assert_eq!(
305            a.decide(subj(1, high()), obj(1, low()), Action(1)),
306            Decision::Permit
307        );
308        assert_eq!(
309            a.len(),
310            1,
311            "second call must hit the cache, not add a new entry"
312        );
313    }
314
315    #[test]
316    fn default_deny_cached_too() {
317        let a = avc();
318        assert_eq!(
319            a.decide(subj(1, high()), obj(1, low()), Action(9)),
320            Decision::Deny
321        );
322        assert_eq!(
323            a.decide(subj(1, high()), obj(1, low()), Action(9)),
324            Decision::Deny
325        );
326    }
327
328    /// The evaluator must be consulted exactly ONCE per distinct key — proving the cache
329    /// actually short-circuits the PDP (the whole point of the AVC).
330    #[test]
331    fn evaluator_consulted_once_per_key() {
332        struct Counting {
333            inner: LatticeTeEvaluator,
334            calls: AtomicU32,
335        }
336        impl TeEvaluator for Counting {
337            fn evaluate(&self, s: SubjectCtx, o: ObjectCtx, a: Action) -> Decision {
338                self.calls.fetch_add(1, Ordering::SeqCst);
339                self.inner.evaluate(s, o, a)
340            }
341            fn generation(&self) -> u64 {
342                self.inner.generation()
343            }
344        }
345        let mut allow = HashSet::new();
346        allow.insert(rule(1, 1, 1));
347        let inner = LatticeTeEvaluator::new(TeMatrix::from_allow(allow), lattice());
348        let counting = Arc::new(Counting {
349            inner,
350            calls: AtomicU32::new(0),
351        });
352        let a = CachingAvc::new(counting.clone());
353
354        for _ in 0..10 {
355            a.decide(subj(1, high()), obj(1, low()), Action(1));
356        }
357        assert_eq!(
358            counting.calls.load(Ordering::SeqCst),
359            1,
360            "PDP must be hit once, then cached"
361        );
362    }
363
364    #[test]
365    fn token_gate_denies_op_outside_op_set() {
366        let a = avc();
367        let token = TokenScope {
368            label_ceiling: high(),
369            op_set: Arc::from(vec![Action(2)]), // does NOT include Action(1)
370            valid_until: Instant::now() + Duration::from_secs(60),
371        };
372        assert_eq!(
373            a.decide_with_token(subj(1, high()), obj(1, low()), Action(1), &token),
374            Decision::Deny,
375            "action not in token op_set must be denied"
376        );
377    }
378
379    #[test]
380    fn token_gate_permits_when_pdp_and_token_agree() {
381        let a = avc();
382        let token = TokenScope {
383            label_ceiling: high(),
384            op_set: Arc::from(vec![Action(1)]),
385            valid_until: Instant::now() + Duration::from_secs(60),
386        };
387        assert_eq!(
388            a.decide_with_token(subj(1, high()), obj(1, low()), Action(1), &token),
389            Decision::Permit
390        );
391    }
392
393    /// Fu1/#677: a token whose attenuated capability subset is **empty** (the
394    /// mint granted nothing — `cap` attenuated to ∅, encoded as an empty
395    /// `op_set`) MUST grant nothing at the PEP, even when the PDP (lattice
396    /// floor and TE matrix) would permit. This is the ZSP guarantee the
397    /// on-the-wire `cap` claim exists to enforce: the deny-only token gate is
398    /// the floor no minted subset can escape, so an empty-subset token cannot
399    /// authorize any action regardless of the subject's clearance.
400    #[test]
401    fn fu1_empty_subset_token_grants_nothing() {
402        let a = avc();
403        // The PDP would Permit this on its own (rule (1,1,1) + high ⊒ low)...
404        assert_eq!(
405            a.decide(subj(1, high()), obj(1, low()), Action(1)),
406            Decision::Permit,
407            "precondition: the PDP permits absent the token gate"
408        );
409        // ...but an empty-subset token (op_set = ∅) denies at the PEP.
410        let empty_subset = TokenScope {
411            label_ceiling: high(),
412            op_set: Arc::from(Vec::<Action>::new()),
413            valid_until: Instant::now() + Duration::from_secs(60),
414        };
415        assert_eq!(
416            a.decide_with_token(subj(1, high()), obj(1, low()), Action(1), &empty_subset),
417            Decision::Deny,
418            "an empty-subset (cap=∅) token MUST grant nothing (Fu1/#677)"
419        );
420    }
421
422    #[test]
423    fn expired_token_fails_closed() {
424        let a = avc();
425        let token = TokenScope {
426            label_ceiling: high(),
427            op_set: Arc::from(vec![Action(1)]),
428            valid_until: Instant::now() - Duration::from_secs(1), // already expired
429        };
430        assert_eq!(
431            a.decide_with_token(subj(1, high()), obj(1, low()), Action(1), &token),
432            Decision::Deny
433        );
434    }
435
436    #[test]
437    fn flush_clears_cache() {
438        let a = avc();
439        a.decide(subj(1, high()), obj(1, low()), Action(1));
440        assert_eq!(a.len(), 1);
441        a.flush();
442        assert!(a.is_empty());
443    }
444}