Skip to main content

hyprstream_rpc/auth/mac/
context.rs

1//! The **subject security context** — a subject's verified clearance, the
2//! `subject.ctx` side of the per-op dominance check `subject.ctx ⊒ object.label`.
3//!
4//! A subject context is the [`SecurityLabel`] a verified principal is cleared
5//! up to. Where the *object* label is content-bound (in a manifest), the
6//! *subject* context rides the verified claims/envelope (design §3, §11 data
7//! structures: `subject ctx in the verified claims/envelope`).
8//!
9//! ## Where it lives on the wire
10//!
11//! The subject context is **derived**, not self-asserted. Two inputs feed it,
12//! both already verified by the time the monitor runs:
13//! 1. The principal's **clearance** (level + compartments) — assigned by policy
14//!    / enrollment and carried in the verified [`crate::auth::Claims`] (the JWT
15//!    is signed by the issuing node, so the clearance is authority-asserted,
16//!    not subject-asserted). The wire field is added by the
17//!    [`SubjectContextClaims`] seam below; the actual `Claims`/`common.capnp`
18//!    field add is gated on S8/#574 (hybrid envelope) — see BLOCKERS.
19//! 2. The principal's **assurance** (#548) — derived from the *verified key
20//!    material*, never claimed. See [`SecurityContext::derive_assurance`].
21//!
22//! ## Fail-closed
23//!
24//! A subject with no derivable clearance has **no context** (`None`), and the
25//! monitor denies — there is no `Default` clearance. Assurance defaults to
26//! [`Assurance::Unverified`] (the floor) precisely so an un-attested key
27//! dominates nothing above the floor.
28
29use super::label::{Assurance, CompartmentSet, CredentialClearance, Level, SecurityLabel};
30use serde::{Deserialize, Serialize};
31
32/// How a principal's key material was verified, used to *derive* (never trust) an
33/// [`Assurance`]. Produced by the envelope/claims verification layer — this type
34/// is the seam between "what crypto verified" and "what the lattice sees".
35///
36/// This intentionally mirrors the existing crypto reality (`crypto/pq.rs`,
37/// `register_pq_trust`, [`crate::crypto::CryptoPolicy`]): an Ed25519 identity is
38/// `Classical` until a bound ML-DSA-65 anchor lifts it to `PqHybrid`.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
40pub enum VerifiedKeyMaterial {
41    /// Identity / signature could not be verified at all → floor.
42    Unverified,
43    /// A classical signature verified (Ed25519 / p256 / secp256k1), and no
44    /// bound post-quantum anchor is present. The federation edge.
45    Classical,
46    /// A hybrid composite verified: an Ed25519 identity with a bound ML-DSA-65
47    /// verifying key (the `register_pq_trust` binding) under
48    /// [`crate::crypto::CryptoPolicy::Hybrid`].
49    PqHybrid,
50}
51
52impl VerifiedKeyMaterial {
53    /// Map verified key material → the assurance lattice axis (#548). This is
54    /// the *only* place assurance is assigned to a subject; it is a function of
55    /// verified crypto, so it cannot be spoofed by a claim.
56    pub fn assurance(self) -> Assurance {
57        match self {
58            VerifiedKeyMaterial::Unverified => Assurance::Unverified,
59            VerifiedKeyMaterial::Classical => Assurance::Classical,
60            VerifiedKeyMaterial::PqHybrid => Assurance::PqHybrid,
61        }
62    }
63}
64
65/// A verified subject's security context = the clearance label the monitor
66/// compares against object labels.
67///
68/// Construction is deliberately gated: you build it from a *clearance* (level +
69/// compartments, authority-asserted) and *verified key material* (assurance,
70/// crypto-derived). The assurance axis of the resulting label is ALWAYS the
71/// derived one — a caller cannot pass in a higher assurance than the crypto
72/// supports.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub struct SecurityContext {
75    /// The full clearance label (level + assurance + compartments). The
76    /// assurance component is crypto-derived; see [`SecurityContext::new`].
77    clearance: SecurityLabel,
78}
79
80impl SecurityContext {
81    /// Build a subject context from an authority-asserted clearance
82    /// (`level` + `compartments`) and crypto-derived `key_material`.
83    ///
84    /// The resulting clearance's assurance axis is **clamped to** the derived
85    /// assurance — a classical key can never carry a `PqHybrid` clearance even
86    /// if policy mistakenly assigned one. This is the load-bearing invariant of
87    /// #548: assurance is a property of the verified identity, not a grant.
88    pub fn new(
89        level: Level,
90        compartments: CompartmentSet,
91        key_material: VerifiedKeyMaterial,
92    ) -> Self {
93        SecurityContext {
94            clearance: SecurityLabel::new(level, key_material.assurance(), compartments),
95        }
96    }
97
98    /// Build from a pre-assembled clearance label and verified key material,
99    /// clamping the assurance axis down to what the crypto supports.
100    ///
101    /// `min(clearance.assurance, derived)` — clamp DOWN only, never up. If
102    /// policy assigned `PqHybrid` but the key is `Classical`, the effective
103    /// assurance is `Classical` (fail-closed/least-privilege).
104    pub fn from_clearance(clearance: SecurityLabel, key_material: VerifiedKeyMaterial) -> Self {
105        let derived = key_material.assurance();
106        SecurityContext {
107            clearance: SecurityLabel {
108                assurance: clearance.assurance.min(derived),
109                ..clearance
110            },
111        }
112    }
113
114    /// Derive assurance directly from verified key material (#548).
115    /// Thin forwarder kept as a named entry-point so the enforcement/PDP layers
116    /// (S2/S4) have one obvious call site.
117    pub fn derive_assurance(key_material: VerifiedKeyMaterial) -> Assurance {
118        key_material.assurance()
119    }
120
121    /// The clearance label. This is the `subject.ctx` the monitor feeds into
122    /// `can_access(object_label)`.
123    pub fn clearance(&self) -> &SecurityLabel {
124        &self.clearance
125    }
126
127    /// `self ⊒ object` — does this subject context dominate the object's
128    /// content-bound label? The per-op MAC floor (design §10). Pure forward to
129    /// the intrinsic lattice order.
130    #[must_use]
131    pub fn can_access(&self, object_label: &SecurityLabel) -> bool {
132        self.clearance.can_access(object_label)
133    }
134
135    /// `object ⊒ self` — Bell–LaPadula *-property (no-write-down): may this
136    /// subject **write** to the object? Write-direction IFC floor (#1269).
137    /// Forward to [`SecurityLabel::can_write_to`].
138    #[must_use]
139    pub fn can_write_to(&self, object_label: &SecurityLabel) -> bool {
140        self.clearance.can_write_to(object_label)
141    }
142
143    pub fn level(&self) -> Level {
144        self.clearance.level
145    }
146    pub fn assurance(&self) -> Assurance {
147        self.clearance.assurance
148    }
149    pub fn compartments(&self) -> CompartmentSet {
150        self.clearance.compartments
151    }
152
153    /// **#681 two-principal composition for a delegated call.** THE single shared
154    /// derivation — both the S6 token-exchange gate (#680) and the downstream PDP
155    /// call this; it is never re-implemented (a parallel impl would drift into
156    /// the exact escalation hole this closes).
157    ///
158    /// - **Level + compartments = meet(delegator, actor)** (`min` level,
159    ///   compartment intersection). The effective clearance dominates an object
160    ///   only if *both* the authority source (`delegator` = UCAN chain root) and
161    ///   the acting receiver (`actor` = the presenter/MCP that signs the
162    ///   downstream envelope and receives the bytes) dominate it. Never either
163    ///   alone.
164    /// - **Assurance = the actor's** (the *signer's* verified key material,
165    ///   already clamped into `actor`'s context per #548). The actor signs the
166    ///   downstream envelope and receives the object bytes, so the crypto floor
167    ///   that governs the read is the actor's — not the delegator's (who
168    ///   authorizes but never receives). A `Classical` actor thus cannot reach a
169    ///   `PqHybrid`-labeled object even if the delegated clearance claims
170    ///   `PqHybrid`.
171    ///
172    /// meet(root, actor) is *sufficient*: intermediate delegation hops carry
173    /// authority, not data (bounded by UCAN capability attenuation), and never
174    /// receive the object bytes — so their clearances do not enter the read floor.
175    #[must_use]
176    pub fn delegated_meet(delegator: &SecurityContext, actor: &SecurityContext) -> SecurityContext {
177        SecurityContext {
178            clearance: SecurityLabel::new(
179                delegator.level().min(actor.level()),
180                actor.assurance(), // signer-derived; NOT met with the delegator
181                delegator.compartments().intersect(actor.compartments()),
182            ),
183        }
184    }
185
186    /// Fail-closed wrapper over [`Self::delegated_meet`]: `None` (→ deny) if
187    /// *either* principal's clearance is unresolved (#681 AC — no default
188    /// clearance for a missing principal). This is the entry point the exchange
189    /// gate and the PDP both call.
190    #[must_use]
191    pub fn delegated(
192        delegator: Option<&SecurityContext>,
193        actor: Option<&SecurityContext>,
194    ) -> Option<SecurityContext> {
195        Some(Self::delegated_meet(delegator?, actor?))
196    }
197}
198
199/// **Seam** for carrying a subject clearance on the verified claims/envelope.
200///
201/// S1 defines the *shape* of the clearance the claims must carry; the concrete
202/// wire field on [`crate::auth::Claims`] / `common.capnp` is added under S8
203/// (#574, hybrid envelope) so the new authz field ships on the hybrid-signed
204/// envelope rather than the classical one. Until then this trait is the typed
205/// contract S2/S4 program against, and a node assembles a [`SecurityContext`]
206/// by:
207///   1. reading the (future) `clearance` field off verified `Claims`, and
208///   2. deriving assurance from the envelope's verified key material.
209///
210/// Implementing this on `Claims` is a one-liner once the field lands; defining
211/// it now lets S2/S4 compile and test against a stable interface.
212pub trait SubjectContextClaims {
213    /// The authority-asserted clearance carried in the verified claims, if any,
214    /// as its two-axis wire projection (level + compartments only; assurance is
215    /// structurally absent from the credential wire — v16 §11). `None` ⇒
216    /// unlabeled subject ⇒ the monitor MUST deny (no default clearance).
217    fn credential_clearance(&self) -> Option<CredentialClearance>;
218
219    /// Assemble the full subject context, deriving the assurance axis PURELY
220    /// from the verified key material (never from the wire — the wire cannot
221    /// carry assurance). Returns `None` (→ deny) if the subject carries no
222    /// clearance. Implementors normally only need to provide
223    /// [`credential_clearance`].
224    ///
225    /// [`credential_clearance`]: SubjectContextClaims::credential_clearance
226    fn security_context(&self, key_material: VerifiedKeyMaterial) -> Option<SecurityContext> {
227        self.credential_clearance()
228            .map(|cc| SecurityContext::new(cc.level, cc.compartments, key_material))
229    }
230}
231
232#[cfg(test)]
233#[allow(clippy::unwrap_used)]
234mod tests {
235    use super::*;
236
237    /// A compartment bitset from bit indices (the policy interns names → bits;
238    /// these tests work directly in bits).
239    fn comps(bits: &[u32]) -> CompartmentSet {
240        bits.iter().copied().collect()
241    }
242
243    // ── #681 two-principal delegated meet ──────────────────────────────────
244
245    #[test]
246    fn delegated_meet_is_min_level_and_compartment_intersection_neither_alone() {
247        // delegator: Secret / {0,1} ; actor: Confidential / {1,2}. Both PqHybrid.
248        let delegator =
249            SecurityContext::new(Level::Secret, comps(&[0, 1]), VerifiedKeyMaterial::PqHybrid);
250        let actor = SecurityContext::new(
251            Level::Confidential,
252            comps(&[1, 2]),
253            VerifiedKeyMaterial::PqHybrid,
254        );
255        let meet = SecurityContext::delegated_meet(&delegator, &actor);
256
257        assert_eq!(meet.level(), Level::Confidential, "min level");
258        assert_eq!(meet.compartments(), comps(&[1]), "compartment intersection");
259        // Neither principal alone equals the meet — the composition is strictly
260        // bounded by both (this is the escalation the single-principal path had).
261        assert_ne!(meet.level(), delegator.level());
262        assert_ne!(meet.compartments(), actor.compartments());
263    }
264
265    #[test]
266    fn delegated_assurance_is_the_signer_actor_classical_actor_cannot_reach_pqhybrid() {
267        // Delegated clearance would like PqHybrid (delegator is PqHybrid), but the
268        // ACTOR signs the downstream envelope with a Classical key. Assurance must
269        // follow the actor → the delegated context cannot reach a PqHybrid object.
270        let delegator =
271            SecurityContext::new(Level::Secret, comps(&[]), VerifiedKeyMaterial::PqHybrid);
272        let actor = SecurityContext::new(Level::Secret, comps(&[]), VerifiedKeyMaterial::Classical);
273        let meet = SecurityContext::delegated_meet(&delegator, &actor);
274
275        assert_eq!(
276            meet.assurance(),
277            Assurance::Classical,
278            "assurance is the actor's (signer)"
279        );
280        let pqhybrid_object = SecurityLabel::new(Level::Secret, Assurance::PqHybrid, comps(&[]));
281        assert!(
282            !meet.can_access(&pqhybrid_object),
283            "Classical actor must NOT reach a PqHybrid object even with a PqHybrid delegator"
284        );
285    }
286
287    #[test]
288    fn delegated_fails_closed_if_either_principal_unresolved() {
289        let ctx = SecurityContext::new(Level::Secret, comps(&[0]), VerifiedKeyMaterial::PqHybrid);
290        assert!(
291            SecurityContext::delegated(None, Some(&ctx)).is_none(),
292            "missing delegator ⇒ deny"
293        );
294        assert!(
295            SecurityContext::delegated(Some(&ctx), None).is_none(),
296            "missing actor ⇒ deny"
297        );
298        assert!(SecurityContext::delegated(None, None).is_none());
299        assert!(SecurityContext::delegated(Some(&ctx), Some(&ctx)).is_some());
300    }
301
302    #[test]
303    fn assurance_derived_from_key_material() {
304        assert_eq!(
305            VerifiedKeyMaterial::Unverified.assurance(),
306            Assurance::Unverified
307        );
308        assert_eq!(
309            VerifiedKeyMaterial::Classical.assurance(),
310            Assurance::Classical
311        );
312        assert_eq!(
313            VerifiedKeyMaterial::PqHybrid.assurance(),
314            Assurance::PqHybrid
315        );
316    }
317
318    #[test]
319    fn new_clamps_assurance_to_key_material() {
320        // Even at Secret level, a classical key yields a classical-assurance ctx.
321        let ctx = SecurityContext::new(Level::Secret, comps(&[0]), VerifiedKeyMaterial::Classical);
322        assert_eq!(ctx.assurance(), Assurance::Classical);
323        assert_eq!(ctx.level(), Level::Secret);
324    }
325
326    #[test]
327    fn from_clearance_clamps_down_never_up() {
328        // policy mistakenly assigned PqHybrid, but key is only Classical.
329        let claimed = SecurityLabel::new(Level::Secret, Assurance::PqHybrid, comps(&[0]));
330        let ctx = SecurityContext::from_clearance(claimed, VerifiedKeyMaterial::Classical);
331        assert_eq!(ctx.assurance(), Assurance::Classical); // clamped down
332    }
333
334    #[test]
335    fn from_clearance_does_not_raise_assurance() {
336        // policy assigned Classical, key is PqHybrid → stays Classical (no raise).
337        let claimed =
338            SecurityLabel::new(Level::Internal, Assurance::Classical, CompartmentSet::EMPTY);
339        let ctx = SecurityContext::from_clearance(claimed, VerifiedKeyMaterial::PqHybrid);
340        assert_eq!(ctx.assurance(), Assurance::Classical);
341    }
342
343    #[test]
344    fn classical_context_cannot_dominate_pqc_object() {
345        let ctx = SecurityContext::new(Level::Secret, comps(&[0]), VerifiedKeyMaterial::Classical);
346        let pqc_object =
347            SecurityLabel::new(Level::Public, Assurance::PqHybrid, CompartmentSet::EMPTY);
348        assert!(!ctx.can_access(&pqc_object));
349    }
350
351    struct FakeClaims(Option<CredentialClearance>);
352    impl SubjectContextClaims for FakeClaims {
353        fn credential_clearance(&self) -> Option<CredentialClearance> {
354            self.0
355        }
356    }
357
358    #[test]
359    fn unlabeled_subject_has_no_context() {
360        let claims = FakeClaims(None);
361        assert!(claims
362            .security_context(VerifiedKeyMaterial::PqHybrid)
363            .is_none());
364    }
365
366    /// The wire clearance carries only level + compartments; the assurance axis
367    /// is derived PURELY from the verified key material. The same wire
368    /// clearance therefore yields `Classical` under a classical key and
369    /// `PqHybrid` under a hybrid key — no synthetic assurance rides the wire.
370    #[test]
371    fn assurance_is_derived_from_key_material_not_the_wire() {
372        let clearance = CredentialClearance {
373            level: Level::Confidential,
374            compartments: comps(&[0]),
375        };
376        let classical = FakeClaims(Some(clearance))
377            .security_context(VerifiedKeyMaterial::Classical)
378            .unwrap();
379        assert_eq!(classical.level(), Level::Confidential);
380        assert_eq!(classical.assurance(), Assurance::Classical);
381
382        let hybrid = FakeClaims(Some(clearance))
383            .security_context(VerifiedKeyMaterial::PqHybrid)
384            .unwrap();
385        assert_eq!(hybrid.assurance(), Assurance::PqHybrid);
386    }
387}