Skip to main content

hyprstream_rpc/auth/mac/
label.rs

1//! The security **label** — the content-bound classification carried by every
2//! object, and the verified **clearance** carried by every subject.
3//!
4//! This is S1 (#567), the foundation of the native-MAC authz model (epic #547).
5//! It is **TCB**: keep it small and verifiable. The whole lattice is three
6//! orthogonal axes, each a *small total/partial order*, combined into one
7//! product lattice (see [`super::lattice`]).
8//!
9//! Design invariants (epic #547 §1, design doc §1):
10//! - **No unlabeled state.** There is no `Default` that means "public/allow".
11//!   The absence of a label is represented by `Option::None` at call sites and
12//!   is treated as **denied** by the monitor — never by a permissive default
13//!   here. (We deliberately do NOT derive `Default` for [`SecurityLabel`].)
14//! - **Labels are content-truth.** A label is meant to be bound to content (a
15//!   manifest hash) so it cannot be relabeled without rehashing. This module
16//!   defines the *type*; the binding seam lives in [`super::manifest`].
17//! - **Assurance is a lattice axis, not a flag** (#548). A classical-DID peer
18//!   is bounded LOW; a PQC-bound peer may reach HIGH. The dominance check then
19//!   *automatically* prevents PQC-required data from flowing to a classical
20//!   peer — no separate enforcement path.
21//!
22//! ## Representation (S1↔S4 reconciliation, epic #547)
23//!
24//! [`SecurityLabel`] is a **fixed-size, `Copy + Ord + Hash` value**:
25//! ```text
26//!     level: Level (u8)  ×  assurance: Assurance (u8)  ×  compartments: CompartmentSet (u64 bitset)
27//! ```
28//! Compartments are a **fixed bitset**, not a heap set. Each compartment name
29//! (`"pii"`, `"tenant:acme"`, …) is interned to a bit index by the policy
30//! ([`super::lattice::Lattice`]); the label carries only the bitset. This is what
31//! lets S4's Access Vector Cache (#570) key on a [`SecurityLabel`] *directly* —
32//! no interning layer, no allocation, sub-µs hashing on the hot path. The
33//! string↔bit mapping lives in the `Lattice` policy (the one place the
34//! compartment vocabulary is closed and audited).
35
36use serde::{Deserialize, Serialize};
37use std::fmt;
38
39/// Number of distinct compartments representable in a label.
40///
41/// A fixed bitset width keeps [`SecurityLabel`] `Copy` and pointer-free so it can
42/// be an AVC key (S4, #570). 64 is ample headroom for the closed, audited
43/// compartment vocabulary; widening it is a deliberate (versioned) TCB change,
44/// the same class of change as adding a [`Level`].
45pub const MAX_COMPARTMENTS: u32 = 64;
46
47/// Multi-Level-Security sensitivity level — a **total order** (the MLS axis).
48///
49/// Small and fixed on purpose (TCB). Higher discriminant ⇒ more sensitive.
50/// Ordering is derived from declaration order, so `Public < Internal <
51/// Confidential < Secret`. This is the classic Bell–LaPadula level.
52///
53/// Adding a level is a deliberate policy change (a new lattice version), not a
54/// runtime/config knob.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "lowercase")]
57#[repr(u8)]
58pub enum Level {
59    /// World-readable. The *floor* of the level axis. NOTE: floor ≠ unlabeled.
60    /// An object explicitly labeled `Public` is labeled; an object with no
61    /// label at all is denied (see module docs).
62    Public = 0,
63    /// Internal / org-only.
64    Internal = 1,
65    /// Confidential.
66    Confidential = 2,
67    /// Secret — the top of the level axis.
68    Secret = 3,
69}
70
71impl Level {
72    /// The bottom of the level axis (used as the join identity element).
73    pub const BOTTOM: Level = Level::Public;
74    /// The top of the level axis.
75    pub const TOP: Level = Level::Secret;
76}
77
78impl fmt::Display for Level {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        let s = match self {
81            Level::Public => "public",
82            Level::Internal => "internal",
83            Level::Confidential => "confidential",
84            Level::Secret => "secret",
85        };
86        f.write_str(s)
87    }
88}
89
90/// Crypto-**assurance** axis (#548) — a **total order** derived from *verified*
91/// key material, never claimed.
92///
93/// This is the dimension that lets a classical (ATProto/p256/secp256k1)
94/// federation perimeter coexist with the mandatory PQC interior without a hole:
95/// PQC-required data is labeled at an assurance only a PQC-bound principal
96/// dominates, and the ordinary dominance check does the rest.
97///
98/// Derivation (a property of the *verified* identity — see
99/// [`super::context::SecurityContext::derive_assurance`]):
100/// - `Unverified` — assurance could not be established (fail-closed; the floor).
101/// - `Classical` — authenticated by a classical DID only (Ed25519/p256/
102///   secp256k1); no bound PQC anchor.
103/// - `PqHybrid`  — has a verified hybrid-PQC anchor (Ed25519 ↔ ML-DSA-65 bound
104///   via `register_pq_trust`), i.e. the [`crate::crypto::CryptoPolicy::Hybrid`]
105///   composite verified.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
107#[serde(rename_all = "kebab-case")]
108#[repr(u8)]
109pub enum Assurance {
110    /// Assurance could not be verified. Floor of the axis. A *subject* at
111    /// `Unverified` dominates nothing above it; an *object* requiring more than
112    /// `Unverified` is therefore unreachable by such a subject — fail-closed.
113    Unverified = 0,
114    /// Classical DID, no post-quantum binding (the federation edge).
115    Classical = 1,
116    /// Verified hybrid post-quantum anchor (EdDSA + ML-DSA-65).
117    PqHybrid = 2,
118}
119
120impl Assurance {
121    /// Floor of the assurance axis (fail-closed for unknown provenance).
122    pub const BOTTOM: Assurance = Assurance::Unverified;
123    /// Top of the assurance axis and identity for its `min` join.
124    pub const TOP: Assurance = Assurance::PqHybrid;
125}
126
127impl fmt::Display for Assurance {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        let s = match self {
130            Assurance::Unverified => "unverified",
131            Assurance::Classical => "classical",
132            Assurance::PqHybrid => "pq-hybrid",
133        };
134        f.write_str(s)
135    }
136}
137
138/// A need-to-know **compartment** *name* (the categories axis vocabulary).
139///
140/// Compartments form a powerset lattice under ⊆. This type is the *human-facing
141/// name* (e.g. `"tenant:acme"`, `"pii"`, `"model:qwen-7b"`); inside a
142/// [`SecurityLabel`] a compartment is stored as a **bit** in a [`CompartmentSet`]
143/// bitset. The name↔bit mapping is owned by the policy
144/// ([`super::lattice::Lattice`], built from the schema `$scope` annotations —
145/// S3, #569). This type does not constrain the vocabulary.
146#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
147pub struct Compartment(pub String);
148
149impl Compartment {
150    pub fn new(s: impl Into<String>) -> Self {
151        Compartment(s.into())
152    }
153    pub fn as_str(&self) -> &str {
154        &self.0
155    }
156}
157
158impl fmt::Debug for Compartment {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        write!(f, "Compartment({:?})", self.0)
161    }
162}
163
164impl fmt::Display for Compartment {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.write_str(&self.0)
167    }
168}
169
170/// A **fixed bitset** of compartment bits — the powerset-lattice axis, packed so
171/// [`SecurityLabel`] stays `Copy + Ord + Hash`.
172///
173/// Bit `i` set ⟺ the label is in the compartment interned at index `i` by the
174/// policy. Subset/union are bitwise `AND`/`OR`. The empty set (`0`) is the
175/// compartment-axis bottom. This is the representation that lets S4's AVC (#570)
176/// key on a label with no interning indirection.
177#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
178#[serde(transparent)]
179pub struct CompartmentSet(pub u64);
180
181impl CompartmentSet {
182    /// The empty compartment set — the axis bottom.
183    pub const EMPTY: CompartmentSet = CompartmentSet(0);
184
185    /// A set containing exactly the single bit `index` (`0 ≤ index < `
186    /// [`MAX_COMPARTMENTS`]). Out-of-range indices are ignored (empty) —
187    /// fail-closed: an un-representable compartment grants nothing.
188    #[inline]
189    pub const fn single(index: u32) -> Self {
190        if index >= MAX_COMPARTMENTS {
191            CompartmentSet(0)
192        } else {
193            CompartmentSet(1u64 << index)
194        }
195    }
196
197    /// Is this the empty set?
198    #[inline]
199    pub const fn is_empty(self) -> bool {
200        self.0 == 0
201    }
202
203    /// `self ⊆ other` — is every compartment of `self` also in `other`?
204    #[inline]
205    pub const fn is_subset(self, other: CompartmentSet) -> bool {
206        self.0 & other.0 == self.0
207    }
208
209    /// Set **union** (the IFC join on this axis).
210    #[inline]
211    pub const fn union(self, other: CompartmentSet) -> CompartmentSet {
212        CompartmentSet(self.0 | other.0)
213    }
214
215    /// Set **intersection** (the lattice *meet* on this axis) — the dual of
216    /// [`Self::union`]. Used to compose the need-to-know of two principals
217    /// (#681 delegated meet): the result is cleared into a compartment only if
218    /// *both* inputs are, so a delegated call never widens need-to-know past
219    /// either principal.
220    #[inline]
221    pub const fn intersect(self, other: CompartmentSet) -> CompartmentSet {
222        CompartmentSet(self.0 & other.0)
223    }
224
225    /// Does this set contain compartment bit `index`?
226    #[inline]
227    pub const fn contains(self, index: u32) -> bool {
228        index < MAX_COMPARTMENTS && (self.0 & (1u64 << index)) != 0
229    }
230
231    /// Iterate the set bit indices, ascending. (Off the hot path: diagnostics /
232    /// rendering / policy validation.)
233    pub fn iter(self) -> impl Iterator<Item = u32> {
234        (0..MAX_COMPARTMENTS).filter(move |&i| self.contains(i))
235    }
236
237    /// Number of compartments in the set.
238    #[inline]
239    pub const fn len(self) -> u32 {
240        self.0.count_ones()
241    }
242}
243
244impl FromIterator<u32> for CompartmentSet {
245    fn from_iter<I: IntoIterator<Item = u32>>(iter: I) -> Self {
246        iter.into_iter().fold(CompartmentSet::EMPTY, |acc, i| {
247            acc.union(CompartmentSet::single(i))
248        })
249    }
250}
251
252impl fmt::Debug for CompartmentSet {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        write!(f, "CompartmentSet({:#x})", self.0)
255    }
256}
257
258/// A complete security label: a point in the product lattice
259/// `Level × Assurance × CompartmentSet`.
260///
261/// The same type is used for an **object's** classification and a **subject's**
262/// clearance (a clearance is just a label the subject is allowed to read up
263/// to). Dominance and join are defined on the inherent
264/// [`SecurityLabel::can_access`] / [`SecurityLabel::join`] helpers below — note
265/// those helpers encode the *fixed* product-lattice algebra and are independent
266/// of any site policy (the policy in [`super::lattice::Lattice`] only constrains
267/// which labels are *well-formed/known*, never how they compare).
268///
269/// **`Copy + Ord + Hash`** (compartments are a packed [`CompartmentSet`] bitset,
270/// not a heap set) so S4's AVC (#570) can key on a label directly — and so two
271/// equal labels serialize identically, which content-binding (manifest hash) and
272/// the `(UCAN, bundle_hash)` approval (S5) require.
273#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
274pub struct SecurityLabel {
275    /// MLS sensitivity level (total order).
276    pub level: Level,
277    /// Crypto-assurance required to handle this label (total order, #548).
278    pub assurance: Assurance,
279    /// Need-to-know compartments as a fixed bitset (powerset lattice under ⊆).
280    #[serde(default)]
281    pub compartments: CompartmentSet,
282}
283
284impl fmt::Debug for SecurityLabel {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        // Render in the SELinux-ish `level:assurance:{bits}` form for logs/audit.
287        write!(f, "{self}")
288    }
289}
290
291impl fmt::Display for SecurityLabel {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        // Note: the label carries compartment *bits*, not names — name resolution
294        // needs the policy. We render bit indices here; a name-aware renderer
295        // lives on `Lattice`.
296        write!(f, "{}:{}", self.level, self.assurance)?;
297        if !self.compartments.is_empty() {
298            let joined = self
299                .compartments
300                .iter()
301                .map(|i| i.to_string())
302                .collect::<Vec<_>>()
303                .join(",");
304            write!(f, ":{{c{joined}}}")?;
305        }
306        Ok(())
307    }
308}
309
310/// The **credential-clearance wire projection** of a [`SecurityLabel`] (v16
311/// §11, operator Gate-2 value 11). A credential's `clearance` claim is the
312/// semantic two-element array `[level, [compartments]]` and NOTHING else — the
313/// assurance axis is **structurally absent from the wire** and is derived only
314/// from verified key material at credential admission (see
315/// [`super::SecurityContext::new`]). The authority-asserted clearance claim
316/// therefore carries THIS type, never a full [`SecurityLabel`], so a synthetic
317/// assurance can never ride in on the wire.
318///
319/// Wire grammar (identical for the JWT JSON value and the CWT CBOR value):
320/// - element 0 `level`: a uint with the frozen mapping `0=Public, 1=Internal,
321///   2=Confidential, 3=Secret`;
322/// - element 1 `compartments`: an array of compartment **bit indices**, each a
323///   uint `0..=63`, strictly ascending and unique (empty allowed) — the
324///   credential projection of the versioned compartment vocabulary, never a
325///   bitmask integer and never names;
326/// - the outer array has **exactly two** elements.
327///
328/// Unknown levels, out-of-range/duplicate/descending compartments, a bitmask
329/// integer, names, extra elements, or any assurance field all fail
330/// deserialization (fail-closed).
331#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
332pub struct CredentialClearance {
333    /// MLS sensitivity level (element 0 of the wire array).
334    pub level: Level,
335    /// Need-to-know compartments (bitset; the wire form is the ascending index
336    /// list of element 1).
337    pub compartments: CompartmentSet,
338}
339
340impl CredentialClearance {
341    /// The wire projection of a full label: level + compartments, dropping the
342    /// crypto-derived assurance axis (which is never issuer-asserted).
343    pub fn from_label(label: SecurityLabel) -> Self {
344        Self {
345            level: label.level,
346            compartments: label.compartments,
347        }
348    }
349}
350
351impl From<SecurityLabel> for CredentialClearance {
352    fn from(label: SecurityLabel) -> Self {
353        Self::from_label(label)
354    }
355}
356
357impl fmt::Debug for CredentialClearance {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        // Assurance is deliberately absent — this is the wire projection.
360        write!(f, "{}", self.level)?;
361        if !self.compartments.is_empty() {
362            let joined = self
363                .compartments
364                .iter()
365                .map(|i| i.to_string())
366                .collect::<Vec<_>>()
367                .join(",");
368            write!(f, ":{{c{joined}}}")?;
369        }
370        Ok(())
371    }
372}
373
374impl serde::Serialize for CredentialClearance {
375    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
376        use serde::ser::SerializeSeq as _;
377        let indices: Vec<u8> = self.compartments.iter().map(|i| i as u8).collect();
378        let mut seq = serializer.serialize_seq(Some(2))?;
379        seq.serialize_element(&(self.level as u8))?;
380        seq.serialize_element(&indices)?;
381        seq.end()
382    }
383}
384
385impl<'de> serde::Deserialize<'de> for CredentialClearance {
386    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
387        struct WireVisitor;
388        impl<'de> serde::de::Visitor<'de> for WireVisitor {
389            type Value = CredentialClearance;
390            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391                f.write_str(
392                    "a two-element credential-clearance array [level, [compartment indices]]",
393                )
394            }
395            fn visit_seq<A: serde::de::SeqAccess<'de>>(
396                self,
397                mut seq: A,
398            ) -> Result<CredentialClearance, A::Error> {
399                use serde::de::Error as _;
400                let level_raw: u8 = seq
401                    .next_element()?
402                    .ok_or_else(|| A::Error::custom("clearance: missing level element"))?;
403                let level = match level_raw {
404                    0 => Level::Public,
405                    1 => Level::Internal,
406                    2 => Level::Confidential,
407                    3 => Level::Secret,
408                    other => {
409                        return Err(A::Error::custom(format!(
410                            "clearance: unknown level {other} (0..=3)"
411                        )));
412                    }
413                };
414                let indices: Vec<u8> = seq
415                    .next_element()?
416                    .ok_or_else(|| A::Error::custom("clearance: missing compartments array"))?;
417                // Exactly two elements: any third element (e.g. an appended
418                // assurance) is a malformed, assurance-bearing wire value.
419                if seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
420                    return Err(A::Error::custom(
421                        "clearance: array must have exactly two elements",
422                    ));
423                }
424                let mut bits: u64 = 0;
425                let mut prev: Option<u8> = None;
426                for idx in indices {
427                    if u32::from(idx) >= MAX_COMPARTMENTS {
428                        return Err(A::Error::custom(format!(
429                            "clearance: compartment index {idx} out of range 0..={}",
430                            MAX_COMPARTMENTS - 1
431                        )));
432                    }
433                    if prev.is_some_and(|p| idx <= p) {
434                        return Err(A::Error::custom(
435                            "clearance: compartment indices must be strictly ascending and unique",
436                        ));
437                    }
438                    prev = Some(idx);
439                    bits |= 1u64 << idx;
440                }
441                Ok(CredentialClearance {
442                    level,
443                    compartments: CompartmentSet(bits),
444                })
445            }
446        }
447        deserializer.deserialize_seq(WireVisitor)
448    }
449}
450
451impl SecurityLabel {
452    /// Construct a label from its axes. There is intentionally **no `Default`** —
453    /// every label must be chosen explicitly so "unlabeled" can never silently
454    /// mean "public".
455    pub fn new(level: Level, assurance: Assurance, compartments: CompartmentSet) -> Self {
456        SecurityLabel {
457            level,
458            assurance,
459            compartments,
460        }
461    }
462
463    /// Construct a label from compartment **bit indices** (e.g. resolved from
464    /// names by the policy). Out-of-range indices are dropped (fail-closed).
465    pub fn from_bits(
466        level: Level,
467        assurance: Assurance,
468        bits: impl IntoIterator<Item = u32>,
469    ) -> Self {
470        SecurityLabel {
471            level,
472            assurance,
473            compartments: bits.into_iter().collect(),
474        }
475    }
476
477    /// The fail-closed label `(Public, Unverified, {})`.
478    ///
479    /// This is deliberately distinct from the identity for provenance joins:
480    /// the Biba assurance axis joins with `min`, whose identity is `PqHybrid`.
481    /// In particular, an empty provenance set must remain unverified rather
482    /// than acquire the join identity's top assurance.
483    pub const fn bottom() -> Self {
484        SecurityLabel {
485            level: Level::BOTTOM,
486            assurance: Assurance::BOTTOM,
487            compartments: CompartmentSet::EMPTY,
488        }
489    }
490
491    /// Per-axis identity for a non-empty provenance join.
492    const fn join_identity() -> Self {
493        SecurityLabel {
494            level: Level::BOTTOM,
495            assurance: Assurance::TOP,
496            compartments: CompartmentSet::EMPTY,
497        }
498    }
499
500    /// Whether this label is the lattice bottom.
501    pub fn is_bottom(&self) -> bool {
502        self.level == Level::BOTTOM
503            && self.assurance == Assurance::BOTTOM
504            && self.compartments.is_empty()
505    }
506
507    /// May a subject with this clearance access an object labelled `object`?
508    ///
509    /// This is the **Bell–LaPadula dominance** relation — clearance `self`
510    /// *dominates* the object label (`self ⊒ object`) iff, on *every* axis, the
511    /// subject is at least the object:
512    /// - `self.level     >= object.level`            (no read-up)
513    /// - `self.assurance >= object.assurance`        (#548 crypto-assurance axis)
514    /// - `object.compartments ⊆ self.compartments`   (cleared into all categories)
515    ///
516    /// The assurance field is currently overloaded: here it is an authentication-
517    /// strength gate, while provenance joining treats it as Biba integrity. Keep
518    /// this gate unchanged pending the field-separation/proof follow-up in #1232.
519    ///
520    /// The per-op MAC floor (design §3, §10): the *fixed* product-lattice order,
521    /// content truth, never overridable by a token/UCAN/grant.
522    #[inline]
523    #[must_use]
524    pub fn can_access(&self, object: &SecurityLabel) -> bool {
525        self.level >= object.level
526            && self.assurance >= object.assurance
527            && object.compartments.is_subset(self.compartments)
528    }
529
530    /// Bell–LaPadula *-property (confinement / no-write-down): may a subject
531    /// with clearance `self` **write** to an object labelled `object`?
532    ///
533    /// The write-direction dual of [`can_access`]. A subject may write only to
534    /// objects at least as restrictive as its own clearance — preventing a
535    /// high-level subject from leaking secrets to a lower-level object:
536    /// - `object.level >= self.level`              (no-write-down)
537    /// - `self.assurance >= object.assurance`       (crypto floor is NOT flipped —
538    ///   you cannot write to a higher-assurance object than your key proves)
539    /// - `self.compartments.is_subset(object.compartments)` (no compartment
540    ///   write-down: the target must be at least as compartmented as the writer)
541    ///
542    /// The assurance axis intentionally does **not** flip: it is a
543    /// crypto-authentication floor on both read and write, not a confidentiality
544    /// axis. This is conservative — it tightens rather than relaxes the gate.
545    /// See the assurance-axis overload note on [`can_access`] and #1232.
546    ///
547    /// [`can_access`]: SecurityLabel::can_access
548    #[inline]
549    #[must_use]
550    pub fn can_write_to(&self, object: &SecurityLabel) -> bool {
551        object.level >= self.level
552            && self.assurance >= object.assurance
553            && self.compartments.is_subset(object.compartments)
554    }
555
556    /// IFC provenance join over confidentiality, integrity, and compartments.
557    ///
558    /// `a ⊔ b` = `(max(level), min(assurance), union(compartments))`: secrecy
559    /// rises to the most restrictive input, while provenance integrity degrades
560    /// to its weakest link. Associative, commutative, and idempotent.
561    #[inline]
562    #[must_use]
563    pub fn join(&self, other: &SecurityLabel) -> SecurityLabel {
564        SecurityLabel {
565            level: if self.level >= other.level {
566                self.level
567            } else {
568                other.level
569            },
570            assurance: if self.assurance <= other.assurance {
571                self.assurance
572            } else {
573                other.assurance
574            },
575            compartments: self.compartments.union(other.compartments),
576        }
577    }
578
579    /// Fold the IFC join over a set of input labels (provenance-DAG join).
580    ///
581    /// Non-empty inputs fold from the per-axis identity `(Public, PqHybrid, {})`.
582    /// Empty provenance instead returns the fail-closed `bottom()` label, never
583    /// the top-assurance identity.
584    #[must_use]
585    pub fn join_all<'a>(labels: impl IntoIterator<Item = &'a SecurityLabel>) -> SecurityLabel {
586        let mut labels = labels.into_iter();
587        let Some(first) = labels.next() else {
588            return SecurityLabel::bottom();
589        };
590
591        labels.fold(SecurityLabel::join_identity().join(first), |acc, label| {
592            acc.join(label)
593        })
594    }
595}
596
597#[cfg(test)]
598#[allow(clippy::unwrap_used)]
599mod tests {
600    use super::*;
601
602    fn label(l: Level, a: Assurance, bits: &[u32]) -> SecurityLabel {
603        SecurityLabel::from_bits(l, a, bits.iter().copied())
604    }
605
606    #[test]
607    fn level_is_totally_ordered() {
608        assert!(Level::Public < Level::Internal);
609        assert!(Level::Internal < Level::Confidential);
610        assert!(Level::Confidential < Level::Secret);
611        assert_eq!(Level::BOTTOM, Level::Public);
612        assert_eq!(Level::TOP, Level::Secret);
613    }
614
615    #[test]
616    fn assurance_is_totally_ordered_unverified_floor() {
617        assert!(Assurance::Unverified < Assurance::Classical);
618        assert!(Assurance::Classical < Assurance::PqHybrid);
619        assert_eq!(Assurance::BOTTOM, Assurance::Unverified);
620    }
621
622    #[test]
623    fn compartment_set_subset_and_union() {
624        let a = CompartmentSet::single(0).union(CompartmentSet::single(2));
625        let b = CompartmentSet::single(0);
626        assert!(b.is_subset(a));
627        assert!(!a.is_subset(b));
628        assert_eq!(a.union(b), a);
629        assert_eq!(a.len(), 2);
630        assert!(a.contains(0));
631        assert!(a.contains(2));
632        assert!(!a.contains(1));
633    }
634
635    #[test]
636    fn label_is_copy_and_hashable() {
637        // The reconciliation requirement: a label is a cheap Copy+Hash+Ord AVC key.
638        fn assert_avc_key<T: Copy + std::hash::Hash + Ord>() {}
639        assert_avc_key::<SecurityLabel>();
640        let x = label(Level::Secret, Assurance::PqHybrid, &[1, 3]);
641        let y = x; // Copy, not move
642        assert_eq!(x, y);
643    }
644
645    #[test]
646    fn dominance_reflexive() {
647        let x = label(Level::Confidential, Assurance::Classical, &[0, 1]);
648        assert!(x.can_access(&x));
649    }
650
651    #[test]
652    fn dominance_level_read_down() {
653        let secret = label(Level::Secret, Assurance::PqHybrid, &[]);
654        let public = label(Level::Public, Assurance::PqHybrid, &[]);
655        assert!(secret.can_access(&public));
656        assert!(!public.can_access(&secret));
657    }
658
659    #[test]
660    fn dominance_requires_compartment_superset() {
661        let cleared = label(Level::Secret, Assurance::PqHybrid, &[0, 1]); // pii, tenant:acme
662        let needs_pii = label(Level::Public, Assurance::Unverified, &[0]);
663        let needs_other = label(Level::Public, Assurance::Unverified, &[5]); // finance
664        assert!(cleared.can_access(&needs_pii));
665        assert!(!cleared.can_access(&needs_other)); // not cleared into "finance"
666    }
667
668    #[test]
669    fn assurance_classical_cannot_dominate_pqc_label() {
670        // #548 acceptance: a classical-DID peer cannot dominate a PQC-required label.
671        let classical_subject = label(Level::Secret, Assurance::Classical, &[0]);
672        let pqc_object = label(Level::Public, Assurance::PqHybrid, &[]);
673        assert!(!classical_subject.can_access(&pqc_object));
674
675        // a PQC-bound peer can (level/compartments permitting).
676        let pqc_subject = label(Level::Secret, Assurance::PqHybrid, &[0]);
677        assert!(pqc_subject.can_access(&pqc_object));
678    }
679
680    #[test]
681    fn unverified_subject_dominates_nothing_above_floor() {
682        let unverified = label(Level::Secret, Assurance::Unverified, &[0]);
683        let needs_classical = label(Level::Public, Assurance::Classical, &[]);
684        assert!(!unverified.can_access(&needs_classical));
685    }
686
687    #[test]
688    fn write_direction_no_write_down() {
689        // A Secret subject may write to a Secret object (same level).
690        let secret = label(Level::Secret, Assurance::Classical, &[]);
691        assert!(secret.can_write_to(&secret));
692
693        // A Secret subject may NOT write to a Public object (no-write-down).
694        let public = label(Level::Public, Assurance::Classical, &[]);
695        assert!(!secret.can_write_to(&public));
696
697        // A Public subject MAY write to a Secret object (writing up is allowed).
698        assert!(public.can_write_to(&secret));
699    }
700
701    #[test]
702    fn write_direction_compartments_no_write_out() {
703        // A subject in {0,1} may write to an object in {0,1} or a superset.
704        let subj = label(Level::Secret, Assurance::Classical, &[0, 1]);
705        let same = label(Level::Secret, Assurance::Classical, &[0, 1]);
706        let superset = label(Level::Secret, Assurance::Classical, &[0, 1, 2]);
707        assert!(subj.can_write_to(&same));
708        assert!(subj.can_write_to(&superset));
709
710        // Writing to a subset (e.g. {0}) leaks compartment-1 data — denied.
711        let subset = label(Level::Secret, Assurance::Classical, &[0]);
712        assert!(!subj.can_write_to(&subset));
713    }
714
715    #[test]
716    fn write_direction_assurance_floor_not_flipped() {
717        // Assurance is a crypto floor on both axes: a Classical subject cannot
718        // write to a PqHybrid-required object even though the *-property level
719        // direction is satisfied (Public→Public or Public→Secret is "write up").
720        let classical_subj = label(Level::Public, Assurance::Classical, &[]);
721        let pqc_object = label(Level::Secret, Assurance::PqHybrid, &[]);
722        assert!(!classical_subj.can_write_to(&pqc_object));
723
724        // A PqHybrid subject writing to a Classical object at ≥ level: allowed.
725        let pqc_subj = label(Level::Public, Assurance::PqHybrid, &[]);
726        let classical_obj = label(Level::Secret, Assurance::Classical, &[]);
727        assert!(pqc_subj.can_write_to(&classical_obj));
728    }
729
730    #[test]
731    fn join_takes_confidentiality_max_integrity_min_and_union() {
732        let a = label(Level::Internal, Assurance::Classical, &[0]); // pii
733        let b = label(Level::Secret, Assurance::PqHybrid, &[5]); // finance
734        let j = a.join(&b);
735        assert_eq!(j.level, Level::Secret);
736        assert_eq!(j.assurance, Assurance::Classical);
737        assert!(j.compartments.contains(0));
738        assert!(j.compartments.contains(5));
739    }
740
741    #[test]
742    fn join_preserves_each_axis_bound() {
743        let a = label(Level::Internal, Assurance::Classical, &[0]);
744        let b = label(Level::Confidential, Assurance::Unverified, &[5]);
745        let j = a.join(&b);
746        assert!(j.level >= a.level && j.level >= b.level);
747        assert!(j.assurance <= a.assurance && j.assurance <= b.assurance);
748        assert!(a.compartments.is_subset(j.compartments));
749        assert!(b.compartments.is_subset(j.compartments));
750    }
751
752    #[test]
753    fn join_laws() {
754        let a = label(Level::Internal, Assurance::Classical, &[0]);
755        let b = label(Level::Secret, Assurance::Unverified, &[1]);
756        let c = label(Level::Public, Assurance::PqHybrid, &[2]);
757        // commutative
758        assert_eq!(a.join(&b), b.join(&a));
759        // associative
760        assert_eq!(a.join(&b).join(&c), a.join(&b.join(&c)));
761        // idempotent
762        assert_eq!(a.join(&a), a);
763        // per-axis identity
764        assert_eq!(a.join(&SecurityLabel::join_identity()), a);
765    }
766
767    #[test]
768    fn join_all_secret_input_propagates() {
769        // Confidentiality rises, integrity falls, and compartments accumulate.
770        let inputs = vec![
771            label(Level::Public, Assurance::Classical, &[0]),
772            label(Level::Secret, Assurance::PqHybrid, &[1]),
773            label(Level::Internal, Assurance::Classical, &[2]),
774        ];
775        let j = SecurityLabel::join_all(&inputs);
776        assert_eq!(j.level, Level::Secret);
777        assert_eq!(j.assurance, Assurance::Classical);
778        assert_eq!(j.compartments.len(), 3);
779    }
780
781    #[test]
782    fn join_all_mixed_classical_and_pq_hybrid_yields_classical() {
783        let inputs = vec![
784            label(Level::Public, Assurance::PqHybrid, &[]),
785            label(Level::Public, Assurance::Classical, &[]),
786        ];
787
788        assert_eq!(
789            SecurityLabel::join_all(&inputs).assurance,
790            Assurance::Classical
791        );
792    }
793
794    #[test]
795    fn join_all_empty_is_fail_closed_unverified() {
796        let none: Vec<&SecurityLabel> = vec![];
797        let joined = SecurityLabel::join_all(none);
798        assert_eq!(joined.assurance, Assurance::Unverified);
799        assert!(joined.is_bottom());
800        assert_ne!(joined, SecurityLabel::join_identity());
801    }
802
803    #[test]
804    fn serde_roundtrip_is_canonical() {
805        let l = label(Level::Secret, Assurance::PqHybrid, &[1, 0]);
806        let json = serde_json::to_string(&l).unwrap();
807        let back: SecurityLabel = serde_json::from_str(&json).unwrap();
808        assert_eq!(l, back);
809        // canonical: re-serializing yields identical bytes (content-binding needs this)
810        assert_eq!(json, serde_json::to_string(&back).unwrap());
811    }
812
813    // ── CredentialClearance two-axis wire grammar (v16 §11, H2) ─────────────
814
815    /// The canonical fixture `[2,[5,7]]` is Confidential with compartments
816    /// {5,7}; serialization is exactly that two-element array and round-trips,
817    /// and every frozen level maps.
818    #[test]
819    fn credential_clearance_wire_is_canonical_two_axis() {
820        let value = CredentialClearance::from_label(label(
821            Level::Confidential,
822            Assurance::Classical,
823            &[5, 7],
824        ));
825        let json = serde_json::to_string(&value).unwrap();
826        assert_eq!(json, "[2,[5,7]]", "exact two-axis wire form");
827        let back: CredentialClearance = serde_json::from_str(&json).unwrap();
828        assert_eq!(value, back);
829
830        let parsed: CredentialClearance = serde_json::from_str("[2,[5,7]]").unwrap();
831        assert_eq!(parsed.level, Level::Confidential);
832        assert!(parsed.compartments.contains(5) && parsed.compartments.contains(7));
833        assert_eq!(parsed.compartments.len(), 2);
834
835        // Empty compartments are allowed.
836        let empty: CredentialClearance = serde_json::from_str("[0,[]]").unwrap();
837        assert_eq!(empty.level, Level::Public);
838        assert!(empty.compartments.is_empty());
839
840        // The frozen level domain 0..=3 maps exactly.
841        for (raw, lvl) in [
842            (0, Level::Public),
843            (1, Level::Internal),
844            (2, Level::Confidential),
845            (3, Level::Secret),
846        ] {
847            let v: CredentialClearance = serde_json::from_str(&format!("[{raw},[]]")).unwrap();
848            assert_eq!(v.level, lvl);
849        }
850    }
851
852    /// Every malformed / noncanonical / assurance-bearing wire value denies.
853    #[test]
854    fn credential_clearance_wire_rejects_malformed() {
855        let reject = |s: &str| {
856            assert!(
857                serde_json::from_str::<CredentialClearance>(s).is_err(),
858                "must reject {s}"
859            );
860        };
861        reject("[4,[]]"); // unknown level (domain 0..=3)
862        reject("[1,[64]]"); // compartment index out of range (0..=63)
863        reject("[1,[5,5]]"); // duplicate index
864        reject("[1,[7,5]]"); // descending / non-ascending order
865        reject("[1,[],1]"); // three elements (an appended assurance axis)
866        reject("[1]"); // one element (missing compartments)
867        reject("[]"); // empty array
868        reject("[1,160]"); // compartments as a bitmask integer, not an index array
869        reject(r#"[1,["pii"]]"#); // compartment NAMES instead of indices
870        reject(r#"["confidential",[]]"#); // level as a name string
871                                          // The struct/object form (assurance-bearing) never parses as clearance.
872        reject(r#"{"level":1,"assurance":"classical","compartments":0}"#);
873    }
874
875    /// The wire projection is assurance-free: two labels differing ONLY in the
876    /// assurance axis project to the identical wire value and bytes.
877    #[test]
878    fn credential_clearance_wire_drops_assurance() {
879        let classical =
880            CredentialClearance::from_label(label(Level::Internal, Assurance::Classical, &[3]));
881        let hybrid =
882            CredentialClearance::from_label(label(Level::Internal, Assurance::PqHybrid, &[3]));
883        assert_eq!(
884            classical, hybrid,
885            "assurance is not part of the wire identity"
886        );
887        let json = serde_json::to_string(&hybrid).unwrap();
888        assert_eq!(json, serde_json::to_string(&classical).unwrap());
889        assert_eq!(json, "[1,[3]]");
890        assert!(
891            !json.contains("assurance") && !json.contains("classical") && !json.contains("pq"),
892            "no assurance token on the wire: {json}"
893        );
894    }
895}