Skip to main content

hyprstream_rpc/auth/mac/
lattice.rs

1//! The MAC **lattice** as policy — defined once, versioned, pinned.
2//!
3//! Two things are deliberately separated here:
4//!
5//! 1. **The order algebra** (dominance ⊒, join ⊔) is *fixed* and lives on
6//!    [`SecurityLabel`] itself. It is the product order of `Level × Assurance ×
7//!    CompartmentSet`. It never depends on site policy, so the per-op monitor
8//!    (S2) can compute dominance with zero policy lookups — content truth only.
9//!
10//! 2. **The well-formedness policy** (which compartments exist + their stable
11//!    bit assignment, the lattice *version*) lives in [`Lattice`]. This is the
12//!    "defined once as policy" object (design §3). It is consulted at
13//!    *label-creation / enrollment / genesis* time to (a) **intern** compartment
14//!    *names* into the bit indices a [`SecurityLabel`] carries, and (b) reject
15//!    typo'd / unknown compartments — NOT on the hot path. Closing the
16//!    compartment vocabulary is what makes labels auditable and keeps the TCB
17//!    small.
18//!
19//! Why split them? Because the dominance check must be uncircumventable and
20//! trivially verifiable. If dominance consulted policy, a policy bug could
21//! grant access. By keeping the order intrinsic and only validating
22//! *membership* against policy, a policy bug can at worst reject a legitimate
23//! label (fail-closed), never widen access.
24//!
25//! ## S1↔S4 reconciliation: the name↔bit interner lives here (#547)
26//!
27//! Because [`SecurityLabel`] carries a packed [`CompartmentSet`] bitset (so S4's
28//! AVC can key on it directly), the *one* place that maps a compartment **name**
29//! (`"pii"`) ↔ a **bit index** is this policy object. Genesis / enrollment
30//! resolve names → bits via [`Lattice::intern`]; nothing on the per-op hot path
31//! ever touches a string.
32
33use super::label::{
34    Assurance, Compartment, CompartmentSet, Level, SecurityLabel, MAX_COMPARTMENTS,
35};
36use serde::{Deserialize, Serialize};
37use std::collections::BTreeMap;
38use std::fmt;
39
40/// Monotonic lattice policy version. Crypto-agility / policy-agility rule
41/// (design §14): the suite/lattice is *pinned and versioned*; migration is a
42/// deliberate version bump, never an in-band negotiation. Labels and the
43/// `(UCAN, bundle_hash)` approval (S5) bind this version so a label minted
44/// under v1 can't be silently reinterpreted under v2.
45///
46/// **S1↔S4 reconciliation:** this is the SAME monotonic counter that S4's
47/// `compiled::CompiledPolicy.generation` carries — a compiled TE matrix is valid
48/// only against the lattice generation that minted its bit assignments. See
49/// [`LatticeVersion::generation`].
50#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
51pub struct LatticeVersion(pub u32);
52
53impl LatticeVersion {
54    /// The lattice version as the policy **generation** (S4's `CompiledPolicy`
55    /// and AVC tag this same value). They are definitionally equal: a bump of
56    /// the compartment vocabulary IS a new policy generation.
57    #[inline]
58    pub const fn generation(self) -> u64 {
59        self.0 as u64
60    }
61}
62
63impl fmt::Display for LatticeVersion {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        write!(f, "v{}", self.0)
66    }
67}
68
69/// Reasons a label fails the well-formedness policy. All are fail-closed.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub enum LabelError {
72    /// A compartment name in the label is not in the policy's known set.
73    UnknownCompartment(Compartment),
74    /// A compartment *bit* in the label has no registered name under this policy
75    /// (an out-of-vocabulary or stale bit — fail-closed).
76    UnknownCompartmentBit(u32),
77    /// The lattice version on the label does not match the active policy.
78    VersionMismatch {
79        expected: LatticeVersion,
80        found: LatticeVersion,
81    },
82}
83
84impl fmt::Display for LabelError {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            LabelError::UnknownCompartment(c) => {
88                write!(f, "unknown compartment in label: {c}")
89            }
90            LabelError::UnknownCompartmentBit(b) => {
91                write!(f, "unknown compartment bit in label: c{b}")
92            }
93            LabelError::VersionMismatch { expected, found } => {
94                write!(
95                    f,
96                    "lattice version mismatch: expected {expected}, found {found}"
97                )
98            }
99        }
100    }
101}
102
103impl std::error::Error for LabelError {}
104
105/// Reasons a serialized [`Lattice`] is rejected on decode. All fail-closed: a
106/// malformed wire vocabulary never silently becomes a smaller/different lattice.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum LatticeDecodeError {
109    /// The wire vocabulary lists the same compartment name twice. Bit
110    /// assignment must be unambiguous, so this is rejected rather than
111    /// silently collapsed (which would shift every later bit).
112    DuplicateCompartment(Compartment),
113    /// The wire vocabulary exceeds the bitset width. Truncating would drop
114    /// compartments and desync bits from the issuer, so reject instead.
115    TooManyCompartments { got: usize, max: u32 },
116}
117
118impl fmt::Display for LatticeDecodeError {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        match self {
121            LatticeDecodeError::DuplicateCompartment(c) => {
122                write!(f, "duplicate compartment in lattice vocabulary: {c}")
123            }
124            LatticeDecodeError::TooManyCompartments { got, max } => {
125                write!(f, "lattice vocabulary has {got} compartments, max is {max}")
126            }
127        }
128    }
129}
130
131impl std::error::Error for LatticeDecodeError {}
132
133/// Failure decoding a [`Lattice`] from its canonical byte form: either the CBOR
134/// itself was malformed or the decoded vocabulary was rejected (see
135/// [`LatticeDecodeError`]). Carries a rendered message; the distinction is not
136/// load-bearing for callers, which fail closed either way.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct LatticeCodecError(String);
139
140impl fmt::Display for LatticeCodecError {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        write!(f, "lattice decode failed: {}", self.0)
143    }
144}
145
146impl std::error::Error for LatticeCodecError {}
147
148/// The active lattice policy: the *closed* compartment vocabulary (name↔bit) and
149/// the version. Levels and assurances are fixed by their enums (TCB), so only the
150/// open dimension — compartments — needs a registry.
151///
152/// Built once at startup from the schema `$scope` annotations + site policy
153/// (S3, #569) and treated as immutable thereafter (a change is a version bump).
154/// Bit assignments are stable within a version (S4's compiled TE matrix is keyed
155/// to them via the shared generation).
156///
157/// ## Canonical serialization (S1↔S4, #570)
158///
159/// A signed `CompiledPolicy` must carry the lattice so the PDP and every
160/// distributed AVC reconstruct the **identical** name↔bit map — otherwise
161/// [`CompartmentSet`] bits desync from genesis across processes. The wire form
162/// is deliberately minimal: just the [`LatticeVersion`] and the compartment
163/// names **in bit-index order**. Decoding re-interns those names in that exact
164/// order via [`Lattice::new`], so bit assignments are *derived*, never trusted
165/// from the wire — a tampered reverse map cannot exist. Use [`Lattice::to_bytes`]
166/// / [`Lattice::from_bytes`] for the deterministic (CBOR) byte form, or the
167/// `Serialize`/`Deserialize` impls to embed in a larger signed structure.
168#[derive(Debug, Clone, Serialize, Deserialize)]
169#[serde(into = "LatticeWire", try_from = "LatticeWire")]
170pub struct Lattice {
171    version: LatticeVersion,
172    /// Compartment name → stable bit index. The bit index is what a
173    /// [`SecurityLabel`] actually carries. A label bit with no entry here (or a
174    /// name not present) is ill-formed → rejected at creation.
175    name_to_bit: BTreeMap<Compartment, u32>,
176    /// Compartments in bit-index order: `by_bit[i]` is the name interned at bit
177    /// `i`. This IS the canonical construction order and the serialized form.
178    by_bit: Vec<Compartment>,
179}
180
181/// The canonical, deterministic wire form of a [`Lattice`]: version + the
182/// compartment vocabulary in bit-index order. The name↔bit map is reconstructed
183/// (not transmitted), making issuer/consumer bit desync structurally impossible.
184#[derive(Serialize, Deserialize)]
185struct LatticeWire {
186    version: LatticeVersion,
187    compartments: Vec<Compartment>,
188}
189
190impl From<Lattice> for LatticeWire {
191    fn from(l: Lattice) -> Self {
192        LatticeWire {
193            version: l.version,
194            compartments: l.by_bit,
195        }
196    }
197}
198
199impl TryFrom<LatticeWire> for Lattice {
200    type Error = LatticeDecodeError;
201
202    /// Reconstruct by interning in wire order. Rejects (fail-closed) a
203    /// vocabulary that [`Lattice::new`] would have silently altered — duplicate
204    /// names or an over-width list — since either would desync bits from the
205    /// issuer rather than reproduce them.
206    fn try_from(w: LatticeWire) -> Result<Self, Self::Error> {
207        if w.compartments.len() > MAX_COMPARTMENTS as usize {
208            return Err(LatticeDecodeError::TooManyCompartments {
209                got: w.compartments.len(),
210                max: MAX_COMPARTMENTS,
211            });
212        }
213        let mut seen = std::collections::BTreeSet::new();
214        for c in &w.compartments {
215            if !seen.insert(c) {
216                return Err(LatticeDecodeError::DuplicateCompartment(c.clone()));
217            }
218        }
219        Ok(Lattice::new(w.version, w.compartments))
220    }
221}
222
223impl Lattice {
224    /// Construct a lattice policy from a compartment vocabulary, assigning each
225    /// name a stable bit index in iteration order (0, 1, 2, …). Duplicate names
226    /// collapse to the first index. Names beyond [`MAX_COMPARTMENTS`] are
227    /// rejected by truncation (they simply never get a bit — fail-closed).
228    pub fn new(
229        version: LatticeVersion,
230        known_compartments: impl IntoIterator<Item = Compartment>,
231    ) -> Self {
232        let mut name_to_bit = BTreeMap::new();
233        let mut by_bit: Vec<Compartment> = Vec::new();
234        for c in known_compartments {
235            if name_to_bit.contains_key(&c) {
236                continue;
237            }
238            if by_bit.len() >= MAX_COMPARTMENTS as usize {
239                // Vocabulary exceeds the bitset width: refuse to assign (the
240                // name stays unknown → labels using it fail validation). This is
241                // a policy-authoring error surfaced fail-closed.
242                break;
243            }
244            name_to_bit.insert(c.clone(), by_bit.len() as u32);
245            by_bit.push(c);
246        }
247        Lattice {
248            version,
249            name_to_bit,
250            by_bit,
251        }
252    }
253
254    pub fn version(&self) -> LatticeVersion {
255        self.version
256    }
257
258    /// Number of compartments in the vocabulary.
259    pub fn compartment_count(&self) -> u32 {
260        self.by_bit.len() as u32
261    }
262
263    /// The compartment vocabulary in **canonical construction (bit-index)
264    /// order**: `compartment_names()[i]` is the name interned at bit `i`. This
265    /// is the order [`Lattice::new`] assigned and the order the wire form
266    /// preserves — S4's PDP can iterate it to align its TE matrix columns with
267    /// the exact bits a [`SecurityLabel`] carries.
268    pub fn compartment_names(&self) -> &[Compartment] {
269        &self.by_bit
270    }
271
272    /// Canonical, deterministic byte form (CBOR) — the same codec the COSE
273    /// signing path uses — so a signed `CompiledPolicy` can carry the lattice
274    /// verbatim. Round-trips through [`Lattice::from_bytes`] preserving every
275    /// name↔bit assignment exactly. Serialization of an in-memory lattice is
276    /// infallible.
277    pub fn to_bytes(&self) -> Vec<u8> {
278        let mut buf = Vec::new();
279        #[allow(clippy::expect_used)]
280        ciborium::ser::into_writer(self, &mut buf)
281            .expect("Lattice CBOR serialization into a Vec is infallible");
282        buf
283    }
284
285    /// Reconstruct a lattice from its canonical byte form. Fails closed on a
286    /// malformed encoding or a vocabulary [`TryFrom`] would have to alter
287    /// (duplicate names / over-width) — never silently yields a different
288    /// lattice than the issuer signed.
289    ///
290    /// [`TryFrom`]: Lattice::try_from
291    pub fn from_bytes(bytes: &[u8]) -> Result<Self, LatticeCodecError> {
292        ciborium::de::from_reader(bytes).map_err(|e| LatticeCodecError(e.to_string()))
293    }
294
295    /// The bit index assigned to a compartment name, if known.
296    pub fn bit_of(&self, c: &Compartment) -> Option<u32> {
297        self.name_to_bit.get(c).copied()
298    }
299
300    /// The compartment name for a bit index, if registered.
301    pub fn name_of(&self, bit: u32) -> Option<&Compartment> {
302        self.by_bit.get(bit as usize)
303    }
304
305    /// Is `c` a recognized compartment under this policy?
306    pub fn knows(&self, c: &Compartment) -> bool {
307        self.name_to_bit.contains_key(c)
308    }
309
310    /// **Intern** a set of compartment names into a [`CompartmentSet`] bitset.
311    ///
312    /// This is the genesis/enrollment seam that turns the human-facing vocabulary
313    /// into the packed representation a [`SecurityLabel`] carries. An unknown name
314    /// is an error (fail-closed) — it never silently becomes "no compartment".
315    pub fn intern<'a>(
316        &self,
317        names: impl IntoIterator<Item = &'a Compartment>,
318    ) -> Result<CompartmentSet, LabelError> {
319        let mut set = CompartmentSet::EMPTY;
320        for name in names {
321            match self.name_to_bit.get(name) {
322                Some(&bit) => set = set.union(CompartmentSet::single(bit)),
323                None => return Err(LabelError::UnknownCompartment(name.clone())),
324            }
325        }
326        Ok(set)
327    }
328
329    /// Build a [`SecurityLabel`] from names, interning compartments through this
330    /// policy. The ergonomic genesis constructor: `(level, assurance, names) →
331    /// label`. Fails closed on any unknown compartment name.
332    pub fn label(
333        &self,
334        level: Level,
335        assurance: Assurance,
336        names: impl IntoIterator<Item = Compartment>,
337    ) -> Result<SecurityLabel, LabelError> {
338        let owned: Vec<Compartment> = names.into_iter().collect();
339        let compartments = self.intern(owned.iter())?;
340        Ok(SecurityLabel::new(level, assurance, compartments))
341    }
342
343    /// Validate that a label is **well-formed** under this policy: every
344    /// compartment *bit* it carries maps to a registered name. Use at genesis /
345    /// enrollment / seal time before a label is allowed to exist. Does NOT touch
346    /// dominance.
347    pub fn validate(&self, label: &SecurityLabel) -> Result<(), LabelError> {
348        for bit in label.compartments.iter() {
349            if (bit as usize) >= self.by_bit.len() {
350                return Err(LabelError::UnknownCompartmentBit(bit));
351            }
352        }
353        Ok(())
354    }
355
356    /// The lattice top ⊤ under this policy = max level, max assurance, *all*
357    /// known compartments. The only clearance that dominates every well-formed
358    /// label. (Useful for genesis-labeling the policy authority itself, and for
359    /// tests.)
360    pub fn top(&self) -> SecurityLabel {
361        let all = (0..self.by_bit.len() as u32).fold(CompartmentSet::EMPTY, |acc, b| {
362            acc.union(CompartmentSet::single(b))
363        });
364        SecurityLabel::new(Level::TOP, Assurance::TOP, all)
365    }
366
367    /// The lattice bottom ⊥ = `(Public, Unverified, {})`. Same as
368    /// [`SecurityLabel::bottom`]; provided here for symmetry with [`top`].
369    ///
370    /// [`top`]: Lattice::top
371    pub fn bottom(&self) -> SecurityLabel {
372        SecurityLabel::bottom()
373    }
374
375    /// Dominance, re-exposed at the policy object for callers that hold a
376    /// `Lattice`. Identical to [`SecurityLabel::can_access`] — the policy does
377    /// NOT change the order; this is purely an ergonomic forwarder. Debug
378    /// builds assert both labels are well-formed (a mis-labeled object reaching
379    /// the monitor is a genesis bug).
380    #[must_use]
381    pub fn can_access(&self, subject: &SecurityLabel, object: &SecurityLabel) -> bool {
382        debug_assert!(self.validate(subject).is_ok(), "subject label ill-formed");
383        debug_assert!(self.validate(object).is_ok(), "object label ill-formed");
384        subject.can_access(object)
385    }
386
387    /// IFC join, re-exposed at the policy object. Identical algebra to
388    /// [`SecurityLabel::join`]; the result is always well-formed if both inputs
389    /// are (union of known compartments is known).
390    #[must_use]
391    pub fn join(&self, a: &SecurityLabel, b: &SecurityLabel) -> SecurityLabel {
392        a.join(b)
393    }
394}
395
396#[cfg(test)]
397#[allow(clippy::unwrap_used)]
398mod tests {
399    use super::*;
400
401    fn comp(s: &str) -> Compartment {
402        Compartment::new(s)
403    }
404
405    fn policy() -> Lattice {
406        Lattice::new(
407            LatticeVersion(1),
408            [comp("pii"), comp("finance"), comp("tenant:acme")],
409        )
410    }
411
412    #[test]
413    fn intern_assigns_stable_bits() {
414        let p = policy();
415        assert_eq!(p.bit_of(&comp("pii")), Some(0));
416        assert_eq!(p.bit_of(&comp("finance")), Some(1));
417        assert_eq!(p.bit_of(&comp("tenant:acme")), Some(2));
418        assert_eq!(p.bit_of(&comp("nope")), None);
419    }
420
421    #[test]
422    fn label_via_policy_interns_names() {
423        let p = policy();
424        let l = p
425            .label(
426                Level::Confidential,
427                Assurance::Classical,
428                [comp("pii"), comp("finance")],
429            )
430            .unwrap();
431        assert!(l.compartments.contains(0));
432        assert!(l.compartments.contains(1));
433        assert!(p.validate(&l).is_ok());
434    }
435
436    #[test]
437    fn label_via_policy_rejects_unknown_name() {
438        let p = policy();
439        assert_eq!(
440            p.label(Level::Public, Assurance::Classical, [comp("typo")]),
441            Err(LabelError::UnknownCompartment(comp("typo")))
442        );
443    }
444
445    #[test]
446    fn validate_rejects_unregistered_bit() {
447        let p = policy();
448        // Bit 9 has no registered name in a 3-compartment vocabulary.
449        let l = SecurityLabel::from_bits(Level::Public, Assurance::Classical, [9]);
450        assert_eq!(p.validate(&l), Err(LabelError::UnknownCompartmentBit(9)));
451    }
452
453    #[test]
454    fn empty_compartments_always_wellformed() {
455        let l = SecurityLabel::from_bits(Level::Secret, Assurance::PqHybrid, []);
456        assert!(policy().validate(&l).is_ok());
457    }
458
459    #[test]
460    fn top_dominates_every_wellformed_label() {
461        let p = policy();
462        let top = p.top();
463        let arbitrary = p
464            .label(
465                Level::Secret,
466                Assurance::PqHybrid,
467                [comp("pii"), comp("finance"), comp("tenant:acme")],
468            )
469            .unwrap();
470        assert!(p.can_access(&top, &arbitrary));
471    }
472
473    #[test]
474    fn bottom_dominated_by_everything() {
475        let p = policy();
476        let bottom = p.bottom();
477        let any = p
478            .label(Level::Internal, Assurance::Classical, [comp("pii")])
479            .unwrap();
480        assert!(any.can_access(&bottom));
481        // bottom only dominates bottom.
482        assert!(!bottom.can_access(&any));
483        assert!(bottom.can_access(&bottom));
484    }
485
486    #[test]
487    fn lattice_forwarders_match_intrinsic_algebra() {
488        let p = policy();
489        let a = p
490            .label(Level::Internal, Assurance::Classical, [comp("pii")])
491            .unwrap();
492        let b = p
493            .label(Level::Secret, Assurance::PqHybrid, [comp("finance")])
494            .unwrap();
495        assert_eq!(p.can_access(&a, &b), a.can_access(&b));
496        assert_eq!(p.join(&a, &b), a.join(&b));
497    }
498
499    #[test]
500    fn version_display_and_generation() {
501        assert_eq!(LatticeVersion(3).to_string(), "v3");
502        // S1↔S4: LatticeVersion ≡ CompiledPolicy.generation.
503        assert_eq!(LatticeVersion(3).generation(), 3u64);
504    }
505
506    #[test]
507    fn compartment_names_are_in_construction_order() {
508        let p = policy();
509        let names: Vec<&str> = p
510            .compartment_names()
511            .iter()
512            .map(Compartment::as_str)
513            .collect();
514        // Exactly the order passed to `new`, i.e. bit order 0,1,2.
515        assert_eq!(names, ["pii", "finance", "tenant:acme"]);
516        // And it agrees with the name↔bit map for every entry.
517        for (bit, name) in p.compartment_names().iter().enumerate() {
518            assert_eq!(p.bit_of(name), Some(bit as u32));
519            assert_eq!(p.name_of(bit as u32), Some(name));
520        }
521    }
522
523    #[test]
524    fn to_from_bytes_roundtrips_bits_exactly() {
525        let p = policy();
526        let restored = Lattice::from_bytes(&p.to_bytes()).unwrap();
527        // Same version, same vocabulary, same bit assignment for every name.
528        assert_eq!(restored.version(), p.version());
529        assert_eq!(restored.compartment_names(), p.compartment_names());
530        for name in p.compartment_names() {
531            assert_eq!(restored.bit_of(name), p.bit_of(name));
532        }
533        // A label minted under `p` validates identically under the restored
534        // lattice — the whole point: no cross-process bit desync.
535        let l = p
536            .label(Level::Secret, Assurance::PqHybrid, [comp("tenant:acme")])
537            .unwrap();
538        assert!(restored.validate(&l).is_ok());
539        assert_eq!(restored.bit_of(&comp("tenant:acme")), Some(2));
540    }
541
542    #[test]
543    fn byte_form_is_deterministic() {
544        // Two independently-built identical lattices encode byte-identically —
545        // required so a signature over the bytes is stable across processes.
546        assert_eq!(policy().to_bytes(), policy().to_bytes());
547    }
548
549    #[test]
550    fn serde_roundtrips_through_canonical_wire() {
551        let p = policy();
552        // Exercise the Serialize/Deserialize impls (the embed-in-CompiledPolicy
553        // path) via CBOR, distinct from the to_bytes helper.
554        let mut buf = Vec::new();
555        ciborium::ser::into_writer(&p, &mut buf).unwrap();
556        let restored: Lattice = ciborium::de::from_reader(&buf[..]).unwrap();
557        assert_eq!(restored.compartment_names(), p.compartment_names());
558        assert_eq!(restored.version(), p.version());
559    }
560
561    #[test]
562    fn decode_rejects_duplicate_compartment() {
563        let wire = LatticeWire {
564            version: LatticeVersion(1),
565            compartments: vec![comp("pii"), comp("finance"), comp("pii")],
566        };
567        assert_eq!(
568            Lattice::try_from(wire).unwrap_err(),
569            LatticeDecodeError::DuplicateCompartment(comp("pii"))
570        );
571    }
572
573    #[test]
574    fn decode_rejects_over_width_vocabulary() {
575        let too_many: Vec<Compartment> = (0..=MAX_COMPARTMENTS)
576            .map(|i| comp(&format!("c{i}")))
577            .collect();
578        let got = too_many.len();
579        let wire = LatticeWire {
580            version: LatticeVersion(1),
581            compartments: too_many,
582        };
583        assert_eq!(
584            Lattice::try_from(wire).unwrap_err(),
585            LatticeDecodeError::TooManyCompartments {
586                got,
587                max: MAX_COMPARTMENTS
588            }
589        );
590    }
591
592    #[test]
593    fn from_bytes_rejects_garbage() {
594        assert!(Lattice::from_bytes(&[0xde, 0xad, 0xbe, 0xef]).is_err());
595    }
596}