hyprstream_rpc/auth/mac/mod.rs
1//! Native MAC — security labels, the lattice, subject contexts, and genesis
2//! labeling. **S1 (#567), the foundation of epic #547.**
3//!
4//! This module is the **TCB seam** the rest of the security epic consumes. It
5//! defines *what a label is*, *how labels compare* (dominance ⊒ and IFC join ⊔),
6//! *where a subject's clearance comes from*, *where an object's label comes
7//! from*, and *how everything gets an initial label* (genesis). It deliberately
8//! contains no enforcement, no policy distribution, and no token logic — those
9//! are S2/S4/S6.
10//!
11//! ## The lattice (small + verifiable, by design)
12//!
13//! A label is a point in the product lattice
14//! ```text
15//! Level × Assurance × P(Compartment)
16//! (MLS) (#548) (need-to-know)
17//! ```
18//! - **Level** — total order `public < internal < confidential < secret`.
19//! - **Assurance** — total order `unverified < classical < pq-hybrid`, *derived
20//! from verified key material* (#548), never claimed.
21//! - **Compartments** — powerset lattice under ⊆ (a closed vocabulary, policy).
22//!
23//! Dominance is the product order (≥ on each total axis, ⊇ on the compartment
24//! set); join is component-wise (max / max / ∪). Both are pure functions on
25//! [`SecurityLabel`] with **no policy argument** — content truth, uncircumventable.
26//!
27//! ## Interface contract for S2 (enforcement) and S4 (PDP)
28//!
29//! S1 hands the downstream tickets exactly these stable entry-points:
30//!
31//! - **S2 — reference-monitor per-op check (#568).** For each op the monitor:
32//! 1. obtains the **object label** via [`manifest::LabeledObject::security_label`]
33//! — `None` ⇒ DENY (unlabeled object);
34//! 2. obtains the **subject context** via
35//! [`context::SubjectContextClaims::security_context`] (clearance from
36//! verified claims, assurance derived from verified key material) — `None`
37//! ⇒ DENY (unlabeled subject);
38//! 3. evaluates the MAC floor [`context::SecurityContext::can_access`]
39//! (≡ [`SecurityLabel::can_access`]) — `false` ⇒ DENY.
40//! The monitor takes object labels ONLY from `LabeledObject`, never from a
41//! token/UCAN/caveat (design §3, §14). It needs no `Lattice` on the hot path:
42//! dominance is intrinsic.
43//!
44//! - **S2 — IFC at seal/rollup (#568).** A derived object's label =
45//! [`SecurityLabel::join_all`] over its provenance inputs' labels. Aggregation
46//! cannot launder classification.
47//!
48//! - **S4 — PDP / lattice engine (#570).** The PDP owns the [`lattice::Lattice`]
49//! policy object: it [`validate`](lattice::Lattice::validate)s labels at
50//! enrollment/seal, exposes the pinned [`lattice::LatticeVersion`] for the
51//! `(UCAN, bundle_hash)` approval binding (S5), and computes the
52//! **label-ceiling clamp** (§5a) as `min`/dominance over the lattice. The PDP
53//! never re-implements the order — it reuses the intrinsic [`SecurityLabel`]
54//! algebra, so the PDP's clamp and the monitor's floor are provably the same
55//! relation.
56//!
57//! - **Both — derived value:** `effective = approved-ceiling ∩ MAC clearance ∩
58//! self-attenuation` (design §5). The "∩ MAC clearance" factor is exactly the
59//! dominance/clamp defined here; S5/S6 compose it, they do not redefine it.
60//!
61//! ## BLOCKERS (what S1 cannot finish, and why)
62//!
63//! S1 ships everything that is genuinely unblocked (the label + lattice + ops +
64//! subject context + genesis mechanism + static-node labels, all tested). The
65//! following are **defined as seams** here but gated on other work:
66//!
67//! 1. **Content-bound manifest labels** ← the data-plane CAS manifest store.
68//! The content-addressed manifest with a `security_label` field *does not
69//! exist yet* (today's "manifests" are OCI image / release / context
70//! manifests, none data-plane CAS). S1 defines the
71//! [`manifest::ContentBoundLabel`] contract + [`manifest::LabeledObject`]
72//! seam; the implementation (label-in-CID binding + `verify_binding`) lands
73//! with the CAS manifest layer. **Static-node labels are NOT blocked** and
74//! are implemented here.
75//!
76//! 2. **Subject clearance wire field on `Claims`/envelope** ← S8 (#574, hybrid
77//! envelope). S1 defines the [`context::SubjectContextClaims`] trait that the
78//! verified claims will implement; the concrete `clearance` field is added to
79//! `Claims` / `common.capnp` under S8 so the new authz field ships on the
80//! hybrid-signed (EdDSA + ML-DSA-65) envelope, not the classical one. Until
81//! then S2/S4 program against the trait and test with a stub.
82//!
83//! 3. **Assurance derivation source** ← #441 / #280 (authoritative key binding)
84//! + `register_pq_trust`. [`context::VerifiedKeyMaterial`] is the seam; the
85//! *production* of it (was the ML-DSA-65 anchor actually bound + verified for
86//! this identity?) is the envelope-verification + key-binding layer's job.
87//! Until a binding is authoritative, an identity is `Classical` at best and
88//! `Unverified` if even the classical signature can't be checked — both
89//! fail-closed.
90//!
91//! 4. **Compartment vocabulary / genesis content** ← S3 (#569, `$scope`/TE
92//! annotations). S1 defines [`lattice::Lattice`] (the closed vocabulary
93//! holder) and [`genesis::GenesisMap`] (the path→label mechanism + the
94//! completeness gate); the *actual* compartment names and the per-node label
95//! table come from the schema annotations + site policy that S3 produces.
96//!
97//! 5. **PQ-confidentiality labels are unsatisfiable today** ← #153 (streaming
98//! DH → ML-KEM-768 hybrid KEM). The assurance axis covers *signature*
99//! assurance, which is shippable. A future *confidentiality* requirement
100//! (data that must travel a PQ-KEM path) has no satisfying transport until
101//! #153 wires `pq_kem_ciphertext`; such a label is simply undominated →
102//! fail-closed, which is correct. No type change needed when #153 lands —
103//! it's a new compartment/level value, not a new axis.
104
105#[cfg(not(target_arch = "wasm32"))]
106pub mod activation;
107pub mod bind;
108pub mod context;
109// #1268: the mandatory RPC dispatch PEP — fail-closed gate between
110// verify_claims and handle_request in process_request.
111//
112// Native-only: the PEP consumes `crate::service::EnvelopeContext`, and the
113// `service` module is compiled out on wasm32 — the browser client does no
114// server-side dispatch MAC enforcement (same gate pattern as #1307).
115#[cfg(not(target_arch = "wasm32"))]
116pub mod dispatch_pep;
117pub mod genesis;
118pub mod label;
119pub mod lattice;
120pub mod manifest;
121pub mod moq_resolve;
122pub mod pep;
123
124#[cfg(not(target_arch = "wasm32"))]
125pub use activation::{
126 anonymous_floor, block_identity_widening_for_unverified_attach_transport,
127 flush_verified_subject_cache_generation, global_mac_activation_control,
128 remember_verified_claims, remember_verified_claims_with_credential, remember_verified_subject,
129 revoke_verified_subject_credential, subject_context, subject_context_with,
130 MacActivationControl, MacActivationError, MacActivationEvidence, MacActivationMode,
131};
132pub use bind::{clamp_descendant, BindLabel, BindLabelMap};
133pub use context::{SecurityContext, SubjectContextClaims, VerifiedKeyMaterial};
134#[cfg(not(target_arch = "wasm32"))]
135pub use dispatch_pep::{
136 check_dispatch_mac, global_mac_dispatch_pep, install_mac_dispatch_pep, DefaultMacDispatchPep,
137 DenyAllMacPep, DenyAllObjectResolver, MacDecision, MacDenyReason, MacDispatchPep,
138 RpcObjectLabelResolver,
139};
140pub use genesis::{GenesisMap, GenesisReport};
141pub use label::{
142 Assurance, Compartment, CompartmentSet, CredentialClearance, Level, SecurityLabel,
143 MAX_COMPARTMENTS,
144};
145pub use lattice::{LabelError, Lattice, LatticeCodecError, LatticeDecodeError, LatticeVersion};
146pub use manifest::{
147 bind_time_label, import_label, ContentBoundLabel, LabeledObject, ObjectLabelResolver,
148 ObjectRef, StaticNodeLabel,
149};
150pub use moq_resolve::{
151 DeclaredTrackPolicyResolver, DenyAllMoqEventResolver, MoqEventLabelResolver, MoqEventObjectRef,
152 MoqEventPlane, MoqEventPolicyRow, MoqEventPolicyTable, TrackPolicyError, MAX_TRACK_SEGMENTS,
153 MAX_TRACK_SEGMENT_BYTES, SUPPORTED_TRACK_POLICY_REVISION,
154};
155pub use pep::{
156 bounded_audit_coordinate, ClearanceSource, DenyAllClearanceSource, MoqEventAction, MoqEventPep,
157 MoqMacAuditReason, MoqMacAuditRecord, MoqMacAuditSink, BOUNDED_AUDIT_COORDINATE_MAX_BYTES,
158 MAX_AUDIT_COORDINATE_PREFIX_BYTES,
159};
160// `RpcObjectLabelResolver` stays exported for the RPC/VFS/9P planes. The
161// MoQ/event plane deliberately consumes only `MoqEventLabelResolver`
162// (v16 §10: coordinates cannot cross resolver types), so it is not
163// re-exported from `pep`.
164
165#[cfg(test)]
166#[allow(clippy::unwrap_used)]
167mod integration_tests {
168 //! End-to-end shape of the per-op check S2 will perform, exercised against
169 //! the S1 seams only (object via `LabeledObject`, subject via
170 //! `SubjectContextClaims`, floor via `can_access`).
171 use super::*;
172
173 struct StubClaims(Option<CredentialClearance>);
174 impl SubjectContextClaims for StubClaims {
175 fn credential_clearance(&self) -> Option<CredentialClearance> {
176 self.0
177 }
178 }
179
180 /// The exact ALLOW predicate the monitor (S2) computes for the MAC floor,
181 /// using only S1 seams. Returns true ⇒ floor permits; both unlabeled cases
182 /// return false (deny).
183 fn mac_floor(
184 object: &dyn LabeledObject,
185 claims: &dyn SubjectContextClaims,
186 key_material: VerifiedKeyMaterial,
187 ) -> bool {
188 let Some(object_label) = object.security_label() else {
189 return false; // unlabeled object → deny
190 };
191 let Some(ctx) = claims.security_context(key_material) else {
192 return false; // unlabeled subject → deny
193 };
194 ctx.can_access(&object_label)
195 }
196
197 /// A compartment bitset from bit indices (bit 0 = "pii", 1 = "finance", … in
198 /// these tests). The policy interns names→bits; here we work in bits.
199 fn comps(bits: &[u32]) -> CompartmentSet {
200 bits.iter().copied().collect()
201 }
202
203 #[test]
204 fn allow_when_cleared() {
205 let object = StaticNodeLabel::labeled(SecurityLabel::new(
206 Level::Confidential,
207 Assurance::Classical,
208 comps(&[0]), // pii
209 ));
210 // The wire clearance carries level + compartments only; assurance is
211 // derived from the verified key material at admission.
212 let claims = StubClaims(Some(
213 SecurityLabel::new(
214 Level::Secret,
215 Assurance::PqHybrid,
216 comps(&[0, 1]), // pii, finance
217 )
218 .into(),
219 ));
220 assert!(mac_floor(&object, &claims, VerifiedKeyMaterial::PqHybrid));
221 }
222
223 #[test]
224 fn deny_unlabeled_object() {
225 let object = StaticNodeLabel::unlabeled();
226 let claims = StubClaims(Some(Lattice::new(LatticeVersion(1), []).top().into()));
227 assert!(!mac_floor(&object, &claims, VerifiedKeyMaterial::PqHybrid));
228 }
229
230 #[test]
231 fn deny_unlabeled_subject() {
232 let object = StaticNodeLabel::labeled(SecurityLabel::new(
233 Level::Public,
234 Assurance::Classical,
235 CompartmentSet::EMPTY,
236 ));
237 let claims = StubClaims(None);
238 assert!(!mac_floor(&object, &claims, VerifiedKeyMaterial::PqHybrid));
239 }
240
241 #[test]
242 fn deny_classical_subject_on_pqc_object_no_special_path() {
243 // #548 end-to-end: the assurance axis denies via the SAME dominance
244 // check — no separate code path.
245 let object = StaticNodeLabel::labeled(SecurityLabel::new(
246 Level::Public,
247 Assurance::PqHybrid,
248 CompartmentSet::EMPTY,
249 ));
250 let claims = StubClaims(Some(
251 SecurityLabel::new(
252 Level::Secret,
253 Assurance::PqHybrid, // dropped on the wire; assurance is key-derived
254 CompartmentSet::EMPTY,
255 )
256 .into(),
257 ));
258 // ...the verified key material is only Classical → derived → denied.
259 assert!(!mac_floor(&object, &claims, VerifiedKeyMaterial::Classical));
260 // a PQC-bound key passes.
261 assert!(mac_floor(&object, &claims, VerifiedKeyMaterial::PqHybrid));
262 }
263
264 #[test]
265 fn ifc_join_propagates_to_derived_object() {
266 // A derived object sealed from a secret + a classical input is
267 // secret/pq-hybrid — and a merely-classical subject can't read it.
268 let secret_in = SecurityLabel::new(Level::Secret, Assurance::PqHybrid, comps(&[0]));
269 let public_in =
270 SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY);
271 let derived = SecurityLabel::join_all([&secret_in, &public_in]);
272 let object = StaticNodeLabel::labeled(derived);
273
274 let low = StubClaims(Some(
275 SecurityLabel::new(Level::Internal, Assurance::Classical, CompartmentSet::EMPTY).into(),
276 ));
277 assert!(!mac_floor(&object, &low, VerifiedKeyMaterial::Classical));
278 }
279}