Skip to main content

hyprstream_core/mac/
compiled.rs

1//! Compiled-policy distribution + signing (S4 / #570).
2//!
3//! The PolicyService (PDP authority) compiles policy into a [`CompiledPolicy`] (the TE
4//! matrix plus the lattice generation it is valid for), serializes it canonically, hashes
5//! it, and signs `(generation, policy_hash)` with the hybrid COSE composite (EdDSA +
6//! ML-DSA-65; design §13a, §14). Nodes (PEPs) load the signed artifact and the
7//! [`PolicyLoader`] **rejects any policy whose signature does not verify** and (per design
8//! §14 / S5 containment backstop) whose hash does not match an approval.
9//!
10//! This module is the *transport/verification* boundary; the per-op hot path (`te` + `avc`)
11//! never touches it. Signature verification happens **once at load**, never per op (design §7,
12//! §13a "never verify-per-op").
13//!
14//! ## What S5 owns vs what this owns
15//! - S5: the UCAN→TE compiler that *produces* the [`TeMatrix`] and the approval signature over
16//!   `(canonical_UCAN_CID, bundle_hash)`.
17//! - S4 (here): wrapping the matrix as a versioned, hashed, signed distributable; and the
18//!   loader that rejects anything unsigned/mismatched before it can feed an evaluator.
19//!
20//! The actual COSE composite sign/verify lives in `hyprstream_rpc::crypto::cose_sign`; this
21//! module abstracts it behind [`PolicySigner`] / [`PolicyVerifier`] so the hot-path crate has
22//! no crypto dependency and so tests can use a trivial signer. The production wiring (using
23//! `MlDsaSigningKeyStore` + Ed25519) is in [`cose`].
24
25use crate::mac::lattice::{Lattice, LatticeCodecError, SecurityLabel};
26use crate::mac::te::TeMatrix;
27use serde::{Deserialize, Serialize};
28use std::collections::BTreeMap;
29use thiserror::Error;
30
31/// A compiled, distributable policy artifact: the TE matrix, **the S1 lattice it was
32/// compiled against (embedded verbatim)**, and the generation that binds them. `generation`
33/// ties the matrix to a specific lattice generation (S1) AND is the AVC's cache-invalidation
34/// key — bumping it invalidates every cached decision.
35///
36/// ## S1 reconciliation (#570): embed the lattice, bind the version (desync-proof)
37///
38/// The signed policy carries the lattice's **canonical CBOR bytes** ([`Lattice::to_bytes`] —
39/// the same codec the COSE signing path uses). Because those bytes are the closed
40/// compartment vocabulary in bit-index order, every process that loads this policy
41/// reconstructs the **identical** name↔bit map: same bytes in → identical bits out, so a
42/// [`SecurityLabel`](crate::mac::lattice::SecurityLabel)'s compartment bits mean the same
43/// thing in the compiler, the PDP, and every distributed AVC. The loader additionally
44/// enforces `lattice.version().generation() == generation` — a compiled matrix is valid
45/// ONLY against the lattice generation that minted its bit assignments.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct CompiledPolicy {
48    /// Monotonic policy generation. Equals the embedded lattice's
49    /// [`LatticeVersion::generation`](crate::mac::lattice::LatticeVersion::generation)
50    /// (enforced at construction and re-checked on load).
51    pub generation: u64,
52    /// The compiled TE allow/escalate matrix (produced by S5's compiler).
53    pub matrix: TeMatrix,
54    /// The S1 lattice policy, serialized to its canonical CBOR byte form. Embedded so the
55    /// PDP and every distributed AVC reconstruct an identical name↔bit vocabulary (no
56    /// cross-process compartment-bit desync). Reconstruct via [`CompiledPolicy::lattice`].
57    pub lattice_bytes: Vec<u8>,
58    /// Subject clearance provenance (#698, epic #547 activation prerequisite): the
59    /// authority-owned exact-subject→clearance assignment, distributed inside this same
60    /// signed artifact rather than resolved live (D1, ratified 2026-07-03 — "no principal
61    /// authors the function that grants its own request", so this map is populated
62    /// only by whoever compiles+signs the policy, never by the subject itself).
63    ///
64    /// The UCAN grant path resolves DID strings (`Ucan::audience` / `Ucan::root_issuer`);
65    /// Policy token issuance instead resolves the exact `IssueToken.subject` supplied by
66    /// its authorized caller (including non-DID OAuth subjects). No DID/username aliasing
67    /// occurs here. `BTreeMap` keeps canonical serialization deterministic.
68    ///
69    /// Empty by default (`CompiledPolicy::new`) — a node that never calls
70    /// [`Self::with_enrollment`] compiles a policy with no enrolled subjects, and
71    /// [`Self::clearance_for`] returns `None` for every subject until enrollment.
72    pub enrollment: BTreeMap<String, SecurityLabel>,
73}
74
75impl CompiledPolicy {
76    /// Compile a policy against an S1 [`Lattice`]. The generation is taken from the lattice
77    /// version — they are definitionally equal (#570): the lattice that minted the
78    /// compartment bits IS the policy generation. The lattice is embedded verbatim (its
79    /// canonical CBOR bytes) so it travels inside the signature. Enrollment starts empty;
80    /// attach it with [`Self::with_enrollment`].
81    pub fn new(matrix: TeMatrix, lattice: &Lattice) -> Self {
82        Self {
83            generation: lattice.version().generation(),
84            matrix,
85            lattice_bytes: lattice.to_bytes(),
86            enrollment: BTreeMap::new(),
87        }
88    }
89
90    /// Attach the authority-owned exact-subject→clearance enrollment table (#698). Replaces any
91    /// previously attached table. The caller is the policy-compiling authority — this is
92    /// where an admin/UCAN-authored assignment becomes part of the signed artifact; the
93    /// grant path never constructs or mutates this map itself.
94    #[must_use]
95    pub fn with_enrollment(mut self, enrollment: BTreeMap<String, SecurityLabel>) -> Self {
96        self.enrollment = enrollment;
97        self
98    }
99
100    /// Look up a subject's authority-assigned clearance by exact string. `None` ⇒ the subject
101    /// is not enrolled ⇒ the caller MUST deny (no default clearance) — mirrors every other
102    /// S1 "unlabeled = denied" rule in this module tree.
103    #[must_use]
104    pub fn clearance_for(&self, subject: &str) -> Option<SecurityLabel> {
105        self.enrollment.get(subject).copied()
106    }
107
108    /// Reconstruct the embedded S1 [`Lattice`] from its canonical bytes. Fail-closed: a
109    /// malformed / tampered vocabulary (duplicate names, over-width) is rejected rather than
110    /// silently yielding a different lattice (the desync-proof property).
111    pub fn lattice(&self) -> Result<Lattice, LatticeCodecError> {
112        Lattice::from_bytes(&self.lattice_bytes)
113    }
114
115    /// Canonical bytes for hashing/signing. Deterministic: same policy → identical bytes
116    /// (design §13a determinism). We sort the rule sets into a stable vec form first so the
117    /// `HashSet` iteration order never leaks into the hash.
118    pub fn canonical_bytes(&self) -> Result<Vec<u8>, PolicyDistError> {
119        // Re-serialize via a canonical, order-stable representation.
120        let canonical = CanonicalPolicy::from(self);
121        serde_json::to_vec(&canonical).map_err(|e| PolicyDistError::Encode(e.to_string()))
122    }
123
124    /// BLAKE3 content hash of the canonical bytes — the `policy_hash` the approval binds to.
125    pub fn policy_hash(&self) -> Result<[u8; 32], PolicyDistError> {
126        let bytes = self.canonical_bytes()?;
127        Ok(*blake3::hash(&bytes).as_bytes())
128    }
129
130    /// Decode canonical policy bytes back into a [`CompiledPolicy`] — the
131    /// decode + lattice-generation steps of [`PolicyLoader::load`] with NO
132    /// signature/approval check. Crate-internal: callers must anchor trust
133    /// another way (the enrollment reconciler uses the OS-owned
134    /// generation/hash config pin; the loader verifies the signature and
135    /// approval on top of this).
136    pub(crate) fn decode_canonical(bytes: &[u8]) -> Result<Self, PolicyDistError> {
137        let canonical: CanonicalPolicy =
138            serde_json::from_slice(bytes).map_err(|e| PolicyDistError::Decode(e.to_string()))?;
139        let matrix = TeMatrix::new(
140            canonical.allow.iter().copied().collect(),
141            canonical.escalate.iter().copied().collect(),
142        );
143        // Reassemble preserving the embedded lattice bytes verbatim (do NOT re-derive the
144        // generation here — we must round-trip the exact transmitted bytes to recompute the
145        // same hash; the generation/version binding is checked explicitly below).
146        let policy = CompiledPolicy {
147            generation: canonical.generation,
148            matrix,
149            lattice_bytes: canonical.lattice_bytes,
150            enrollment: canonical.enrollment,
151        };
152        // S1 reconciliation (#570): the embedded lattice must reconstruct (fail-closed on a
153        // tampered/over-width vocabulary) AND its version must equal the policy generation —
154        // a matrix is only valid against the lattice generation that minted its bits.
155        let lattice = policy
156            .lattice()
157            .map_err(|e| PolicyDistError::Decode(e.to_string()))?;
158        let lattice_gen = lattice.version().generation();
159        if lattice_gen != policy.generation {
160            return Err(PolicyDistError::LatticeGenerationMismatch {
161                policy: policy.generation,
162                lattice: lattice_gen,
163            });
164        }
165        Ok(policy)
166    }
167}
168
169/// Order-stable view of a [`CompiledPolicy`] for canonical encoding. The `TeMatrix` stores
170/// rules in `HashSet`s (O(1) hot-path lookup); for hashing we project to sorted vecs so the
171/// hash is deterministic regardless of set iteration order. The embedded `lattice_bytes` are
172/// already canonical (S1's deterministic CBOR), so the policy hash binds the exact lattice
173/// vocabulary too — a tampered compartment map changes the hash and fails the signature.
174#[derive(Serialize, Deserialize)]
175struct CanonicalPolicy {
176    generation: u64,
177    allow: Vec<crate::mac::te::TeRule>,
178    escalate: Vec<crate::mac::te::TeRule>,
179    lattice_bytes: Vec<u8>,
180    /// #698: always present (never `skip_serializing_if`) — unlike `AuditRecord`'s
181    /// append-only hash chain, a `CompiledPolicy` is recompiled and re-signed whole
182    /// each generation, so there is no existing-artifact hash to preserve across the
183    /// schema's introduction. `BTreeMap` already serializes in sorted-key order, so
184    /// this needs no extra sort step (unlike `allow`/`escalate`, which come off a
185    /// `HashSet` and must be explicitly sorted for determinism).
186    #[serde(default)]
187    enrollment: BTreeMap<String, SecurityLabel>,
188}
189
190impl From<&CompiledPolicy> for CanonicalPolicy {
191    fn from(p: &CompiledPolicy) -> Self {
192        // Reconstruct sorted rule vecs from the matrix. We can't read the private sets
193        // directly, so we expose a sorted projection via TeMatrix below.
194        let (mut allow, mut escalate) = p.matrix.sorted_rules();
195        allow.sort();
196        escalate.sort();
197        Self {
198            generation: p.generation,
199            allow,
200            escalate,
201            lattice_bytes: p.lattice_bytes.clone(),
202            enrollment: p.enrollment.clone(),
203        }
204    }
205}
206
207/// A signed, distributable policy: the canonical policy bytes + a detached composite
208/// signature over `(generation || policy_hash)`. This is the wire artifact PolicyService
209/// publishes and PEPs fetch.
210#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct SignedPolicy {
212    /// Canonical bytes of the [`CompiledPolicy`] (re-hashable at the loader; the loader does
213    /// NOT trust a transmitted hash — it recomputes).
214    pub policy_bytes: Vec<u8>,
215    /// Detached COSE composite signature over the signing input (see [`signing_input`]).
216    pub signature: Vec<u8>,
217    /// Generation, duplicated out-of-band for quick routing; authoritative value is inside
218    /// `policy_bytes` and is what gets signed.
219    pub generation: u64,
220}
221
222/// The exact bytes that get signed: domain-separated `(generation, policy_hash)`. Binding the
223/// generation prevents a rollback/replay of an older signed matrix under a new generation.
224pub fn signing_input(generation: u64, policy_hash: &[u8; 32]) -> Vec<u8> {
225    let mut v = Vec::with_capacity(8 + 8 + 32);
226    v.extend_from_slice(b"hs-mac-te"); // domain separation tag
227    v.extend_from_slice(&generation.to_be_bytes());
228    v.extend_from_slice(policy_hash);
229    v
230}
231
232/// Abstraction over the authority's signing key (production = hybrid EdDSA+ML-DSA-65 COSE
233/// composite). Implemented in [`cose`] over the existing crypto stack.
234pub trait PolicySigner {
235    /// Sign the signing-input bytes, returning a detached signature.
236    fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, PolicyDistError>;
237}
238
239/// Abstraction over signature verification at the loader (production = composite verify with
240/// `require_pq = true`, fail-closed).
241pub trait PolicyVerifier {
242    /// Verify `signature` over `signing_input`. Returns `Ok(())` on success, error otherwise.
243    fn verify(&self, signing_input: &[u8], signature: &[u8]) -> Result<(), PolicyDistError>;
244}
245
246/// PolicyService side: compile → hash → sign → distributable artifact.
247pub fn sign_policy<S: PolicySigner>(
248    policy: &CompiledPolicy,
249    signer: &S,
250) -> Result<SignedPolicy, PolicyDistError> {
251    let policy_bytes = policy.canonical_bytes()?;
252    let hash = policy.policy_hash()?;
253    let input = signing_input(policy.generation, &hash);
254    let signature = signer.sign(&input)?;
255    Ok(SignedPolicy {
256        policy_bytes,
257        signature,
258        generation: policy.generation,
259    })
260}
261
262/// An approval record (design §14 containment backstop): the human-approved binding of a
263/// policy generation to its expected hash. The loader accepts ONLY a policy whose recomputed
264/// hash matches an approval for its generation. Even an undetected compiler bug then can't
265/// smuggle authority past review. S5 produces these (signed `(UCAN_CID, bundle_hash)`); here
266/// we model the hash-match the loader enforces.
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub struct PolicyApproval {
269    pub generation: u64,
270    pub approved_hash: [u8; 32],
271}
272
273impl PolicyApproval {
274    /// **S5 → S4 keystone (#571 M2, additive).** Convert a *verified* UCAN approval
275    /// binding into the [`PolicyApproval`] this loader requires. This is the one
276    /// wire that lets the S5 compiler's output reach the S4 loader: the reviewer
277    /// signs a UCAN approval whose `bundle_hash` is exactly
278    /// [`CompiledPolicy::policy_hash`]; once the signature is verified
279    /// (`SignedApproval::verify` / `verify_binds`, hybrid COSE) the resulting
280    /// [`ApprovalBinding`](hyprstream_rpc::auth::ucan::approval::ApprovalBinding)'s
281    /// `(generation, bundle_hash)` ARE the `(generation, approved_hash)` the loader
282    /// matches against — with the loader RECOMPUTING the hash itself (it never
283    /// trusts a transmitted hash; see [`PolicyLoader::load`]).
284    ///
285    /// Pass only a binding you have already verified — borrowing the
286    /// `&ApprovalBinding` returned by `SignedApproval::verify`/`verify_binds` makes
287    /// that the natural call shape. No `did:key`/crypto happens here: this is a pure
288    /// field projection of an already-trusted binding.
289    pub fn from_verified(binding: &hyprstream_rpc::auth::ucan::approval::ApprovalBinding) -> Self {
290        Self {
291            generation: binding.generation,
292            approved_hash: binding.bundle_hash,
293        }
294    }
295}
296
297/// PEP side: verify signature + match against an approval, then yield the
298/// [`CompiledPolicy`] ready to feed a [`crate::mac::te::LatticeTeEvaluator`]. Fail-closed:
299/// any failure returns an error and NO policy is loaded (the PEP keeps denying).
300pub struct PolicyLoader<V: PolicyVerifier> {
301    verifier: V,
302    /// Verified approvals indexed by generation. An empty set rejects every policy: a
303    /// signature proves who produced an artifact, while the approval is the independent
304    /// containment binding that authorizes its exact hash (S5).
305    approvals: Vec<PolicyApproval>,
306}
307
308impl<V: PolicyVerifier> PolicyLoader<V> {
309    pub fn new(verifier: V) -> Self {
310        Self {
311            verifier,
312            approvals: Vec::new(),
313        }
314    }
315
316    /// Register an approval the loader will require a hash-match against.
317    pub fn with_approval(mut self, approval: PolicyApproval) -> Self {
318        self.approvals.push(approval);
319        self
320    }
321
322    /// Verify + load. Steps (all fail-closed):
323    /// 1. Decode the canonical policy bytes.
324    /// 2. Recompute the hash from the bytes (never trust a transmitted hash).
325    /// 3. Verify the composite signature over `(generation, hash)`.
326    /// 4. Require a matching `(generation, hash)` approval. No approvals means no policy
327    ///    can load — there is deliberately no signature-only mode.
328    pub fn load(&self, signed: &SignedPolicy) -> Result<CompiledPolicy, PolicyDistError> {
329        // 1. Decode (incl. the embedded-lattice generation binding).
330        let policy = CompiledPolicy::decode_canonical(&signed.policy_bytes)?;
331
332        // The out-of-band generation must match the signed-in generation (no mismatch routing).
333        if policy.generation != signed.generation {
334            return Err(PolicyDistError::GenerationMismatch {
335                outer: signed.generation,
336                inner: policy.generation,
337            });
338        }
339
340        // 2. Recompute hash from the decoded policy's OWN canonical bytes. If the transmitted
341        //    bytes were canonical, this round-trips; if they were tampered into a non-canonical
342        //    form, the recomputed hash diverges and signature/approval checks fail closed.
343        let hash = policy.policy_hash()?;
344        let input = signing_input(policy.generation, &hash);
345
346        // 3. Signature verify (ONCE, at load — never per op).
347        self.verifier.verify(&input, &signed.signature)?;
348
349        // 4. Approval hash-match (containment backstop). Empty approvals reject too:
350        //    accepting a signature alone would let the compiler/signing authority bypass
351        //    the independent approval that #570 requires.
352        let matched = self
353            .approvals
354            .iter()
355            .any(|a| a.generation == policy.generation && a.approved_hash == hash);
356        if !matched {
357            return Err(PolicyDistError::NoMatchingApproval {
358                generation: policy.generation,
359            });
360        }
361
362        Ok(policy)
363    }
364}
365
366/// Errors in compiled-policy distribution. All are load-time; the hot path never sees them.
367#[derive(Error, Debug)]
368pub enum PolicyDistError {
369    #[error("policy encode failed: {0}")]
370    Encode(String),
371    #[error("policy decode failed: {0}")]
372    Decode(String),
373    #[error("signature verification failed: {0}")]
374    BadSignature(String),
375    #[error("no approval matches policy generation {generation} (hash mismatch — possible compiler tampering)")]
376    NoMatchingApproval { generation: u64 },
377    #[error("generation mismatch: outer={outer} inner={inner}")]
378    GenerationMismatch { outer: u64, inner: u64 },
379    #[error(
380        "embedded lattice version {lattice} != policy generation {policy} (S1↔S4 bit-desync guard)"
381    )]
382    LatticeGenerationMismatch { policy: u64, lattice: u64 },
383}
384
385// ---------------------------------------------------------------------------------------
386// Production crypto wiring over the existing hybrid COSE composite stack.
387// Kept behind these adapters so `te`/`avc` stay crypto-free and tests can use a stub signer.
388// ---------------------------------------------------------------------------------------
389
390/// Production signer/verifier adapters over `hyprstream_rpc::crypto::cose_sign`.
391pub mod cose {
392    use super::{PolicyDistError, PolicySigner, PolicyVerifier};
393    use ed25519_dalek::{SigningKey, VerifyingKey};
394    use hyprstream_rpc::crypto::cose_sign::{sign_composite, verify_composite};
395    use hyprstream_rpc::crypto::pq::{MlDsaSigningKey, MlDsaVerifyingKey};
396
397    /// Domain-separation AAD for compiled-policy signatures (distinct from envelope/token
398    /// AADs so a policy signature can never be confused for another message type).
399    const POLICY_AAD: &[u8] = b"hs-mac-compiled-policy-v1";
400
401    /// Hybrid (EdDSA + ML-DSA-65) signer for compiled policy. `pq` is `None` only when the
402    /// crypto policy is Classical; production MUST be `Some` (design §14: not Ed25519-only).
403    pub struct HybridPolicySigner<'a> {
404        pub ed_sk: &'a SigningKey,
405        pub pq_sk: Option<&'a MlDsaSigningKey>,
406    }
407
408    impl PolicySigner for HybridPolicySigner<'_> {
409        fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, PolicyDistError> {
410            sign_composite(self.ed_sk, self.pq_sk, signing_input, POLICY_AAD)
411                .map_err(|e| PolicyDistError::Encode(e.to_string()))
412        }
413    }
414
415    /// Hybrid verifier. `require_pq = true` enforces the ML-DSA outer layer (fail-closed if a
416    /// classical-only signature is presented under a hybrid policy — design §13a).
417    pub struct HybridPolicyVerifier<'a> {
418        pub ed_vk: &'a VerifyingKey,
419        pub pq_vk: Option<&'a MlDsaVerifyingKey>,
420        pub require_pq: bool,
421    }
422
423    impl PolicyVerifier for HybridPolicyVerifier<'_> {
424        fn verify(&self, signing_input: &[u8], signature: &[u8]) -> Result<(), PolicyDistError> {
425            verify_composite(
426                signature,
427                self.ed_vk,
428                self.pq_vk,
429                signing_input,
430                POLICY_AAD,
431                self.require_pq,
432            )
433            .map(|_verified| ())
434            .map_err(|e| PolicyDistError::BadSignature(e.to_string()))
435        }
436    }
437}
438
439#[cfg(test)]
440#[allow(clippy::unwrap_used)]
441mod tests {
442    use super::*;
443    use crate::mac::lattice::{Compartment, LatticeVersion};
444    use crate::mac::te::{Action, ObjectType, SubjectType, TeRule};
445    use std::collections::HashSet;
446
447    fn rule(s: u32, o: u32, a: u32) -> TeRule {
448        TeRule {
449            subject_type: SubjectType(s),
450            object_type: ObjectType(o),
451            action: Action(a),
452        }
453    }
454
455    /// A lattice at the given generation/version (the bit-vocabulary the policy binds).
456    fn lattice(gen: u32) -> Lattice {
457        Lattice::new(
458            LatticeVersion(gen),
459            [Compartment::new("pii"), Compartment::new("finance")],
460        )
461    }
462
463    fn policy(gen: u64) -> CompiledPolicy {
464        let mut allow = HashSet::new();
465        allow.insert(rule(1, 1, 1));
466        allow.insert(rule(1, 2, 1));
467        // Generation is taken from the lattice version (they are definitionally equal).
468        CompiledPolicy::new(TeMatrix::from_allow(allow), &lattice(gen as u32))
469    }
470
471    /// A trivial HMAC-free stub signer for unit tests: signature = blake3(key || input).
472    struct StubSigner {
473        key: [u8; 32],
474    }
475    impl PolicySigner for StubSigner {
476        fn sign(&self, input: &[u8]) -> Result<Vec<u8>, PolicyDistError> {
477            let mut h = blake3::Hasher::new();
478            h.update(&self.key);
479            h.update(input);
480            Ok(h.finalize().as_bytes().to_vec())
481        }
482    }
483    struct StubVerifier {
484        key: [u8; 32],
485    }
486    impl PolicyVerifier for StubVerifier {
487        fn verify(&self, input: &[u8], sig: &[u8]) -> Result<(), PolicyDistError> {
488            let mut h = blake3::Hasher::new();
489            h.update(&self.key);
490            h.update(input);
491            if h.finalize().as_bytes().as_slice() == sig {
492                Ok(())
493            } else {
494                Err(PolicyDistError::BadSignature("stub mismatch".into()))
495            }
496        }
497    }
498
499    #[test]
500    fn canonical_hash_is_deterministic_across_set_order() {
501        // Two matrices with the same rules inserted in different order must hash equal.
502        let mut a = HashSet::new();
503        a.insert(rule(1, 1, 1));
504        a.insert(rule(2, 3, 4));
505        let mut b = HashSet::new();
506        b.insert(rule(2, 3, 4));
507        b.insert(rule(1, 1, 1));
508        let pa = CompiledPolicy::new(TeMatrix::from_allow(a), &lattice(5));
509        let pb = CompiledPolicy::new(TeMatrix::from_allow(b), &lattice(5));
510        assert_eq!(pa.policy_hash().unwrap(), pb.policy_hash().unwrap());
511    }
512
513    #[test]
514    fn embedded_lattice_roundtrips_and_binds_generation() {
515        // #570 desync-proof: the policy carries the lattice; reconstruction yields the same
516        // bit vocabulary, and the version equals the generation.
517        let p = policy(4);
518        assert_eq!(p.generation, 4);
519        let l = p.lattice().unwrap();
520        assert_eq!(l.version().generation(), 4);
521        assert_eq!(l.bit_of(&Compartment::new("finance")), Some(1));
522    }
523
524    #[test]
525    fn loader_rejects_lattice_generation_mismatch() {
526        // Hand-craft a policy whose embedded lattice version disagrees with the generation:
527        // the loader must reject it (bit-desync guard), even with a valid signature.
528        let key = [7u8; 32];
529        let mut allow = HashSet::new();
530        allow.insert(rule(1, 1, 1));
531        let mut p = CompiledPolicy::new(TeMatrix::from_allow(allow), &lattice(2));
532        // Force a mismatch: claim generation 9 but the embedded lattice is version 2.
533        p.generation = 9;
534        let signed = sign_policy(&p, &StubSigner { key }).unwrap();
535        let loader = PolicyLoader::new(StubVerifier { key });
536        assert!(matches!(
537            loader.load(&signed),
538            Err(PolicyDistError::LatticeGenerationMismatch {
539                policy: 9,
540                lattice: 2
541            })
542        ));
543    }
544
545    #[test]
546    fn sign_then_load_roundtrips() {
547        let key = [7u8; 32];
548        let policy = policy(3);
549        let approval = PolicyApproval {
550            generation: policy.generation,
551            approved_hash: policy.policy_hash().unwrap(),
552        };
553        let signed = sign_policy(&policy, &StubSigner { key }).unwrap();
554        let loader = PolicyLoader::new(StubVerifier { key }).with_approval(approval);
555        let loaded = loader.load(&signed).unwrap();
556        assert_eq!(loaded.generation, 3);
557        assert_eq!(loaded.matrix.allow_len(), 2);
558    }
559
560    #[test]
561    fn loader_without_approval_rejects_valid_signature() {
562        let key = [7u8; 32];
563        let signed = sign_policy(&policy(3), &StubSigner { key }).unwrap();
564        let loader = PolicyLoader::new(StubVerifier { key });
565        assert!(matches!(
566            loader.load(&signed),
567            Err(PolicyDistError::NoMatchingApproval { generation: 3 })
568        ));
569    }
570
571    #[test]
572    fn tampered_policy_bytes_rejected() {
573        let key = [7u8; 32];
574        let mut signed = sign_policy(&policy(3), &StubSigner { key }).unwrap();
575        // Flip a byte in the policy body — recomputed hash diverges → signature fails.
576        signed.policy_bytes[0] ^= 0xFF;
577        let loader = PolicyLoader::new(StubVerifier { key });
578        assert!(
579            loader.load(&signed).is_err(),
580            "tampered policy must be rejected"
581        );
582    }
583
584    #[test]
585    fn wrong_key_signature_rejected() {
586        let signed = sign_policy(&policy(3), &StubSigner { key: [1u8; 32] }).unwrap();
587        let loader = PolicyLoader::new(StubVerifier { key: [2u8; 32] });
588        assert!(matches!(
589            loader.load(&signed),
590            Err(PolicyDistError::BadSignature(_))
591        ));
592    }
593
594    #[test]
595    fn approval_hash_match_enforced() {
596        let key = [7u8; 32];
597        let p = policy(9);
598        let hash = p.policy_hash().unwrap();
599        let signed = sign_policy(&p, &StubSigner { key }).unwrap();
600
601        // Loader with the CORRECT approval loads.
602        let good = PolicyLoader::new(StubVerifier { key }).with_approval(PolicyApproval {
603            generation: 9,
604            approved_hash: hash,
605        });
606        assert!(good.load(&signed).is_ok());
607
608        // Loader with a WRONG approval hash rejects, even though the signature verifies.
609        let bad = PolicyLoader::new(StubVerifier { key }).with_approval(PolicyApproval {
610            generation: 9,
611            approved_hash: [0u8; 32],
612        });
613        assert!(matches!(
614            bad.load(&signed),
615            Err(PolicyDistError::NoMatchingApproval { generation: 9 })
616        ));
617    }
618
619    #[test]
620    fn generation_mismatch_rejected() {
621        let key = [7u8; 32];
622        let mut signed = sign_policy(&policy(3), &StubSigner { key }).unwrap();
623        signed.generation = 4; // outer disagrees with the signed-in inner generation
624        let loader = PolicyLoader::new(StubVerifier { key });
625        assert!(matches!(
626            loader.load(&signed),
627            Err(PolicyDistError::GenerationMismatch { outer: 4, inner: 3 })
628        ));
629    }
630
631    // ── #698: enrollment (subject clearance provenance) ─────────────────────
632
633    use crate::mac::lattice::{Assurance, CompartmentSet, Level};
634
635    fn label(level: Level) -> SecurityLabel {
636        SecurityLabel::new(level, Assurance::PqHybrid, CompartmentSet::EMPTY)
637    }
638
639    /// A policy with no attached enrollment denies (returns `None`) for every DID —
640    /// the fail-closed default until an authority actually populates the table.
641    #[test]
642    fn empty_policy_enrolls_nobody() {
643        let p = policy(1);
644        assert!(p.clearance_for("did:key:zAlice").is_none());
645    }
646
647    /// `with_enrollment` attaches the table; `clearance_for` looks up an enrolled DID
648    /// and denies (`None`) an unenrolled one.
649    #[test]
650    fn enrolled_did_resolves_unenrolled_denies() {
651        let enrollment = BTreeMap::from([("did:key:zAlice".to_owned(), label(Level::Secret))]);
652        let p = policy(1).with_enrollment(enrollment);
653        assert_eq!(
654            p.clearance_for("did:key:zAlice"),
655            Some(label(Level::Secret))
656        );
657        assert!(
658            p.clearance_for("did:key:zMallory").is_none(),
659            "an unenrolled DID must deny, not fall back to a default clearance"
660        );
661    }
662
663    /// The enrollment table round-trips through sign → wire bytes → verify → load,
664    /// exactly like the TE matrix and lattice it travels alongside — a node loading
665    /// the signed artifact gets the SAME enrollment the authority compiled, not a
666    /// live side-channel lookup.
667    #[test]
668    fn enrollment_round_trips_through_sign_and_load() {
669        let key = [11u8; 32];
670        let enrollment = BTreeMap::from([
671            ("did:key:zAlice".to_owned(), label(Level::Secret)),
672            ("did:key:zBob".to_owned(), label(Level::Confidential)),
673        ]);
674        let policy = policy(2).with_enrollment(enrollment.clone());
675        let approval = PolicyApproval {
676            generation: policy.generation,
677            approved_hash: policy.policy_hash().unwrap(),
678        };
679        let signed = sign_policy(&policy, &StubSigner { key }).unwrap();
680        let loaded = PolicyLoader::new(StubVerifier { key })
681            .with_approval(approval)
682            .load(&signed)
683            .unwrap();
684        assert_eq!(loaded.enrollment, enrollment);
685        assert_eq!(
686            loaded.clearance_for("did:key:zBob"),
687            Some(label(Level::Confidential))
688        );
689    }
690
691    #[test]
692    fn bare_oauth_subject_resolves_exact_signed_enrollment_not_did_alias() {
693        let key = [12u8; 32];
694        let enrollment = BTreeMap::from([("e2e-0d9d641e".to_owned(), label(Level::Internal))]);
695        let policy = policy(2).with_enrollment(enrollment);
696        let signed = sign_policy(&policy, &StubSigner { key }).unwrap();
697        let loaded = PolicyLoader::new(StubVerifier { key })
698            .with_approval(PolicyApproval {
699                generation: policy.generation,
700                approved_hash: policy.policy_hash().unwrap(),
701            })
702            .load(&signed)
703            .unwrap();
704        assert_eq!(
705            loaded.clearance_for("e2e-0d9d641e"),
706            Some(label(Level::Internal))
707        );
708        assert_eq!(loaded.clearance_for("did:web:e2e-0d9d641e.example"), None);
709        assert_eq!(loaded.clearance_for("e2e-0d9d641f"), None);
710    }
711
712    /// The enrollment table is covered content: tampering with it (without re-signing)
713    /// must fail signature verification at load, exactly like tampering with the TE
714    /// matrix or the lattice bytes — an attacker cannot smuggle a widened clearance in
715    /// by editing the wire bytes after signing.
716    #[test]
717    fn tampered_enrollment_fails_signature_verification() {
718        let key = [13u8; 32];
719        let enrollment = BTreeMap::from([("did:key:zAlice".to_owned(), label(Level::Internal))]);
720        let signed =
721            sign_policy(&policy(4).with_enrollment(enrollment), &StubSigner { key }).unwrap();
722
723        // Tamper: decode, widen Alice's clearance, re-encode — but keep the OLD signature.
724        let mut canonical: CanonicalPolicy = serde_json::from_slice(&signed.policy_bytes).unwrap();
725        canonical
726            .enrollment
727            .insert("did:key:zAlice".to_owned(), label(Level::Secret));
728        let tampered_bytes = serde_json::to_vec(&canonical).unwrap();
729        let tampered = SignedPolicy {
730            policy_bytes: tampered_bytes,
731            ..signed
732        };
733
734        let loader = PolicyLoader::new(StubVerifier { key });
735        assert!(
736            matches!(loader.load(&tampered), Err(PolicyDistError::BadSignature(_))),
737            "an enrollment tampered post-signing must fail verification, not silently widen clearance"
738        );
739    }
740
741    /// The enrollment field must not break hash determinism under reordering: the same
742    /// entries inserted in different orders (into a `BTreeMap`, so insertion order is
743    /// moot, but this guards the canonical-encoding path explicitly) produce the same
744    /// policy hash.
745    #[test]
746    fn enrollment_hash_is_order_independent() {
747        let a = BTreeMap::from([
748            ("did:key:zAlice".to_owned(), label(Level::Secret)),
749            ("did:key:zBob".to_owned(), label(Level::Confidential)),
750        ]);
751        let b = BTreeMap::from([
752            ("did:key:zBob".to_owned(), label(Level::Confidential)),
753            ("did:key:zAlice".to_owned(), label(Level::Secret)),
754        ]);
755        let pa = policy(6).with_enrollment(a);
756        let pb = policy(6).with_enrollment(b);
757        assert_eq!(pa.policy_hash().unwrap(), pb.policy_hash().unwrap());
758    }
759}