Skip to main content

hyprstream_core/mac/
compiler.rs

1//! UCAN → Type Enforcement policy compiler (S5 / #571).
2//!
3//! Compiles a validated UCAN grant into a TE [`CompiledPolicy`], then verifies the
4//! compiled policy grants no permission the grant does not authorize (no privilege
5//! escalation) before it is signed. Deny-by-default, fail-closed.
6//!
7//! Three steps: [`compile`] (grant → TE allow-rules), [`check_no_escalation`]
8//! (compiled policy ⊆ grant), and [`compile_policy`] (compile, check, sign — signs
9//! only if the check passes).
10//!
11//! The capability → rule mapping is the [`PermissionMap`] seam; the concrete S3
12//! action vocabulary (#582) plugs in here.
13// TODO(#571): an SMT proof that the compiled policy ⊆ grant over all requests is
14// owed; deferred — no SMT solver is vendored. The differential property tests plus
15// `check_no_escalation` are the current guarantees.
16
17use std::collections::{BTreeSet, HashSet};
18
19use ed25519_dalek::SigningKey;
20use hyprstream_rpc::auth::ucan::approval::{ApprovalBinding, ApprovalError, SignedApproval};
21use hyprstream_rpc::auth::ucan::capability::{Ability, Capability, Caveats, Resource};
22use hyprstream_rpc::auth::ucan::token::Ucan;
23use hyprstream_rpc::crypto::pq::MlDsaSigningKey;
24
25use crate::mac::compiled::{CompiledPolicy, PolicyDistError};
26use crate::mac::lattice::Lattice;
27use crate::mac::te::{Decision, TeMatrix, TeRule};
28
29/// Maps a UCAN capability to the TE rules it grants. The injection point for the
30/// concrete action vocabulary — the production impl is
31/// [`crate::mac::permission_map::ScopePermissionMap`] (#676).
32pub trait PermissionMap {
33    /// The TE rules a single capability grants. Empty for an unrecognized
34    /// capability — it grants nothing (fail-closed; never a wildcard rule).
35    fn permissions_for(&self, cap: &Capability) -> BTreeSet<TeRule>;
36
37    /// The most-permissive concrete access a rule grants at runtime, used to check
38    /// the rule against the grant. `None` for an unrecognized rule (treated as an
39    /// escalation). Must be deterministic and independent of `permissions_for`.
40    fn granted_access(&self, rule: &TeRule) -> Option<AccessRequest>;
41}
42
43/// A concrete access request: the (resource, ability, caveats) a subject presents.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct AccessRequest {
46    pub resource: Resource,
47    pub ability: Ability,
48    pub caveats: Caveats,
49}
50
51impl AccessRequest {
52    fn as_capability(&self) -> Capability {
53        Capability::with_caveats(
54            self.resource.clone(),
55            self.ability.clone(),
56            self.caveats.clone(),
57        )
58    }
59}
60
61/// Compile a validated UCAN grant into a TE policy: the union of every capability's
62/// rules over the given lattice generation. Deterministic (order-independent), and
63/// emits no rule not granted by some capability.
64pub fn compile(ucan: &Ucan, lattice: &Lattice, permissions: &impl PermissionMap) -> CompiledPolicy {
65    let mut allow: BTreeSet<TeRule> = BTreeSet::new();
66    for cap in ucan.capabilities() {
67        allow.extend(permissions.permissions_for(cap));
68    }
69    let matrix = TeMatrix::from_allow(allow.into_iter().collect::<HashSet<_>>());
70    CompiledPolicy::new(matrix, lattice)
71}
72
73/// A rule the compiled policy grants that the UCAN grant does not authorize — a
74/// privilege escalation. A policy with one of these must never be signed.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct PrivilegeEscalation {
77    /// The offending rule.
78    pub rule: TeRule,
79    /// The access the rule grants (its `granted_access`); `None` if the rule has no
80    /// recognized meaning (also an escalation).
81    pub access: Option<AccessRequest>,
82}
83
84/// Verify the compiled policy grants no permission beyond the UCAN grant.
85///
86/// For each rule the matrix permits, this projects the rule back to the access it
87/// grants (`granted_access`) and requires some capability in the grant to authorize
88/// that access. It checks the emitted matrix against the independent `authorizes`
89/// test — it does NOT re-run `permissions_for`. That matters: re-running the forward
90/// map would let a `PermissionMap` that lowers a narrow capability to a broad rule
91/// pass itself; checking each rule's access against the grant instead catches it.
92pub fn check_no_escalation(
93    ucan: &Ucan,
94    policy: &CompiledPolicy,
95    permissions: &impl PermissionMap,
96) -> Result<(), PrivilegeEscalation> {
97    let grant = ucan.capabilities();
98    let (allow, _escalate) = policy.matrix.sorted_rules();
99    for rule in allow {
100        if policy.matrix.te_decision(rule) != Decision::Permit {
101            continue;
102        }
103        let access = permissions.granted_access(&rule);
104        let authorized = match &access {
105            Some(req) => {
106                let claimed = req.as_capability();
107                grant.iter().any(|c| c.authorizes(&claimed))
108            }
109            None => false,
110        };
111        if !authorized {
112            return Err(PrivilegeEscalation { rule, access });
113        }
114    }
115    Ok(())
116}
117
118/// The first rule the grant's capabilities map to that the compiled policy omits, if
119/// any — a completeness gap. Non-security (a narrower policy never over-grants) and
120/// NOT part of the signing gate; for diagnostics only.
121pub fn missing_permission(
122    ucan: &Ucan,
123    policy: &CompiledPolicy,
124    permissions: &impl PermissionMap,
125) -> Option<TeRule> {
126    let present: BTreeSet<TeRule> = policy.matrix.sorted_rules().0.into_iter().collect();
127    for cap in ucan.capabilities() {
128        for rule in permissions.permissions_for(cap) {
129            if !present.contains(&rule) {
130                return Some(rule);
131            }
132        }
133    }
134    None
135}
136
137/// Decide a request against a UCAN grant directly, independent of any compiled
138/// policy: permit iff some capability in the grant authorizes it, else deny. This is
139/// the reference used to check the compiled policy.
140pub fn authorize(grant: &[Capability], request: &AccessRequest) -> Decision {
141    let claimed = request.as_capability();
142    if grant.iter().any(|c| c.authorizes(&claimed)) {
143        Decision::Permit
144    } else {
145        Decision::Deny
146    }
147}
148
149/// As [`authorize`], but also deny if `now` is outside the grant's validity window
150/// `[not_before, expiration]` (inclusive) — matching the chain validator's temporal
151/// gate.
152pub fn authorize_at(
153    grant: &[Capability],
154    not_before: Option<u64>,
155    expiration: Option<u64>,
156    request: &AccessRequest,
157    now: u64,
158) -> Decision {
159    if let Some(nbf) = not_before {
160        if now < nbf {
161            return Decision::Deny;
162        }
163    }
164    if let Some(exp) = expiration {
165        if now > exp {
166            return Decision::Deny;
167        }
168    }
169    authorize(grant, request)
170}
171
172/// Errors from [`compile_policy`].
173#[derive(Debug, thiserror::Error)]
174pub enum CompileError {
175    /// The compiled policy grants more than the grant authorizes; not signed.
176    #[error("compiled policy escalates privilege beyond the grant: {0:?}")]
177    Escalation(PrivilegeEscalation),
178    /// Hashing the policy failed.
179    #[error("policy hash failed: {0}")]
180    Hash(#[from] PolicyDistError),
181    /// Signing the approval failed.
182    #[error("approval signing failed: {0}")]
183    Approval(#[from] ApprovalError),
184}
185
186/// Compile a policy from a validated UCAN grant, verify it does not escalate, and
187/// sign the approval — signing ONLY if the check passes (fail-closed). The caller
188/// must have already validated the UCAN chain. Returns the compiled policy (for
189/// distribution) and the signed approval (for the loader).
190pub fn compile_policy(
191    ucan: &Ucan,
192    lattice: &Lattice,
193    permissions: &impl PermissionMap,
194    ed_sk: &SigningKey,
195    pq_sk: &MlDsaSigningKey,
196) -> Result<(CompiledPolicy, SignedApproval), CompileError> {
197    let policy = compile(ucan, lattice, permissions);
198    if let Err(e) = check_no_escalation(ucan, &policy, permissions) {
199        return Err(CompileError::Escalation(e));
200    }
201    let hash = policy.policy_hash()?;
202    let binding = ApprovalBinding::new(ucan, policy.generation, hash)?;
203    let signed = SignedApproval::sign(binding, ed_sk, pq_sk)?;
204    Ok((policy, signed))
205}
206
207#[cfg(test)]
208#[allow(clippy::unwrap_used)]
209mod tests {
210    use super::*;
211    use crate::mac::compiled::{
212        sign_policy, PolicyApproval, PolicyLoader, PolicySigner, PolicyVerifier,
213    };
214    use crate::mac::lattice::{Compartment, LatticeVersion};
215    use crate::mac::te::{Action as TeAction, ObjectType, SubjectType};
216    use hyprstream_rpc::auth::ucan::capability::{CaveatValue, Caveats};
217    use hyprstream_rpc::auth::ucan::token::{Did, UcanPayload};
218    use proptest::prelude::*;
219    use std::collections::BTreeMap;
220
221    // A concrete, deterministic test PermissionMap over a closed alphabet:
222    // resources `mac://model/<name>` (+ wildcard `mac://model/*`) → ObjectType;
223    // abilities `model/read` → Action(0), `model/write` → Action(1). A wildcard
224    // resource fans out to every concrete object (so the compiler enumerates, never
225    // emits a wildcard rule). Unknown verbs/resources → empty (fail-closed).
226
227    const OBJECTS: &[&str] = &["qwen", "llama", "mistral"];
228
229    fn object_id(name: &str) -> Option<ObjectType> {
230        OBJECTS
231            .iter()
232            .position(|o| *o == name)
233            .map(|i| ObjectType(i as u32))
234    }
235
236    fn action_id(verb: &str) -> Option<TeAction> {
237        match verb {
238            "model/read" => Some(TeAction(0)),
239            "model/write" => Some(TeAction(1)),
240            _ => None,
241        }
242    }
243
244    // Inverses for granted_access (id → concrete name/verb), independent of
245    // permissions_for.
246    fn object_name(id: ObjectType) -> Option<&'static str> {
247        OBJECTS.get(id.0 as usize).copied()
248    }
249    fn action_verb(a: TeAction) -> Option<&'static str> {
250        match a.0 {
251            0 => Some("model/read"),
252            1 => Some("model/write"),
253            _ => None,
254        }
255    }
256
257    /// The allow rules of a compiled policy, as an order-stable set.
258    fn allow_set(p: &CompiledPolicy) -> BTreeSet<TeRule> {
259        p.matrix.sorted_rules().0.into_iter().collect()
260    }
261
262    struct TestPermissions {
263        subject: SubjectType,
264    }
265
266    impl PermissionMap for TestPermissions {
267        fn permissions_for(&self, cap: &Capability) -> BTreeSet<TeRule> {
268            let mut out = BTreeSet::new();
269            let Some(action) = action_id(cap.ability.as_str()) else {
270                return out;
271            };
272            let res = cap.resource.as_str();
273            let concrete: Vec<&str> = if let Some(rest) = res.strip_prefix("mac://model/") {
274                if rest == "*" {
275                    OBJECTS.to_vec()
276                } else if OBJECTS.contains(&rest) {
277                    vec![rest]
278                } else {
279                    vec![]
280                }
281            } else {
282                vec![]
283            };
284            for name in concrete {
285                if let Some(object_type) = object_id(name) {
286                    out.insert(TeRule {
287                        subject_type: self.subject,
288                        object_type,
289                        action,
290                    });
291                }
292            }
293            out
294        }
295
296        fn granted_access(&self, rule: &TeRule) -> Option<AccessRequest> {
297            if rule.subject_type != self.subject {
298                return None;
299            }
300            let name = object_name(rule.object_type)?;
301            let verb = action_verb(rule.action)?;
302            Some(AccessRequest {
303                resource: Resource::new(format!("mac://model/{name}")),
304                ability: Ability::new(verb),
305                caveats: Caveats::empty(),
306            })
307        }
308    }
309
310    fn permissions() -> TestPermissions {
311        TestPermissions {
312            subject: SubjectType(1),
313        }
314    }
315
316    fn lattice(gen: u32) -> Lattice {
317        Lattice::new(
318            LatticeVersion(gen),
319            [Compartment::new("pii"), Compartment::new("finance")],
320        )
321    }
322
323    fn cap(res: &str, ab: &str) -> Capability {
324        Capability::new(Resource::new(res), Ability::new(ab))
325    }
326
327    // A real hybrid identity, so the signing-gate tests can sign.
328    struct Identity {
329        ed_sk: SigningKey,
330        pq_sk: MlDsaSigningKey,
331        pq_vk: hyprstream_rpc::crypto::pq::MlDsaVerifyingKey,
332        did: Did,
333    }
334
335    fn identity() -> Identity {
336        use ed25519_dalek::SigningKey as Sk;
337        use hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair;
338        use rand::rngs::OsRng;
339        let ed_sk = Sk::generate(&mut OsRng);
340        let did = Did::from_ed25519(&ed_sk.verifying_key().to_bytes());
341        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
342        Identity {
343            ed_sk,
344            pq_sk,
345            pq_vk,
346            did,
347        }
348    }
349
350    fn ucan_with(caps: Vec<Capability>) -> Ucan {
351        let did = Did::from_ed25519(&[0u8; 32]);
352        Ucan {
353            payload: UcanPayload {
354                issuer: did.clone(),
355                audience: did,
356                capabilities: caps,
357                not_before: None,
358                expiration: Some(9_999_999_999),
359                nonce: vec![],
360            },
361            proofs: vec![],
362            signature: vec![],
363        }
364    }
365
366    fn ucan_signed_by(id: &Identity, caps: Vec<Capability>) -> Ucan {
367        use hyprstream_rpc::crypto::cose_sign::sign_composite;
368        let payload = UcanPayload {
369            issuer: id.did.clone(),
370            audience: id.did.clone(),
371            capabilities: caps,
372            not_before: None,
373            expiration: Some(9_999_999_999),
374            nonce: vec![],
375        };
376        let bytes = payload.signing_bytes().unwrap();
377        let signature = sign_composite(
378            &id.ed_sk,
379            Some(&id.pq_sk),
380            &bytes,
381            hyprstream_rpc::auth::ucan::APPROVAL_AAD,
382        )
383        .unwrap();
384        Ucan {
385            payload,
386            proofs: vec![],
387            signature,
388        }
389    }
390
391    // ---- compile: no escalation (policy ⊆ grant) ----------------------------
392
393    #[test]
394    fn compile_is_subset_of_grant() {
395        let p = permissions();
396        let l = lattice(3);
397        let u = ucan_with(vec![cap("mac://model/qwen", "model/read")]);
398        let policy = compile(&u, &l, &p);
399        assert_eq!(check_no_escalation(&u, &policy, &p), Ok(()));
400        assert_eq!(
401            allow_set(&policy),
402            BTreeSet::from([TeRule {
403                subject_type: SubjectType(1),
404                object_type: ObjectType(0),
405                action: TeAction(0),
406            }])
407        );
408    }
409
410    #[test]
411    fn check_detects_injected_escalation() {
412        // Inject a rule the grant does NOT authorize, whose honest granted_access
413        // (model/llama, model/write) the single-capability grant can't cover.
414        let p = permissions();
415        let l = lattice(3);
416        let u = ucan_with(vec![cap("mac://model/qwen", "model/read")]);
417        let mut policy = compile(&u, &l, &p);
418        let rogue = TeRule {
419            subject_type: SubjectType(1),
420            object_type: ObjectType(1), // llama
421            action: TeAction(1),        // write
422        };
423        let mut allow: HashSet<TeRule> = policy.matrix.sorted_rules().0.into_iter().collect();
424        allow.insert(rogue);
425        policy.matrix = TeMatrix::from_allow(allow);
426        match check_no_escalation(&u, &policy, &p) {
427            Err(PrivilegeEscalation { rule, access }) => {
428                assert_eq!(rule, rogue);
429                assert_eq!(
430                    access,
431                    Some(AccessRequest {
432                        resource: Resource::new("mac://model/llama"),
433                        ability: Ability::new("model/write"),
434                        caveats: Caveats::empty(),
435                    })
436                );
437            }
438            other => panic!("expected escalation, got {other:?}"),
439        }
440    }
441
442    #[test]
443    fn missing_permission_reports_dropped_rule() {
444        // Completeness is separate and non-security.
445        let p = permissions();
446        let l = lattice(3);
447        let u = ucan_with(vec![cap("mac://model/qwen", "model/read")]);
448        let mut policy = compile(&u, &l, &p);
449        // Drop the only rule.
450        policy.matrix = TeMatrix::from_allow(HashSet::new());
451        // The security check (no escalation) is trivially OK on an empty matrix...
452        assert_eq!(check_no_escalation(&u, &policy, &p), Ok(()));
453        // ...but the completeness check reports the dropped rule.
454        assert!(missing_permission(&u, &policy, &p).is_some());
455    }
456
457    #[test]
458    fn wildcard_grant_fans_out_no_wildcard_rule() {
459        // A `mac://model/*` grant enumerates every concrete object — the matrix has
460        // interned ids, never a wildcard, so it cannot widen to a future object the
461        // grant never reviewed.
462        let p = permissions();
463        let l = lattice(3);
464        let u = ucan_with(vec![cap("mac://model/*", "model/read")]);
465        let policy = compile(&u, &l, &p);
466        assert_eq!(allow_set(&policy).len(), OBJECTS.len());
467        assert_eq!(check_no_escalation(&u, &policy, &p), Ok(()));
468    }
469
470    // ---- default-deny on unmapped capabilities / requests -------------------
471
472    #[test]
473    fn unmapped_capability_grants_nothing() {
474        let p = permissions();
475        let l = lattice(3);
476        let u = ucan_with(vec![
477            cap("mac://model/qwen", "admin/superuser"),
478            cap("mac://other/x", "model/read"),
479        ]);
480        let policy = compile(&u, &l, &p);
481        assert!(
482            allow_set(&policy).is_empty(),
483            "unmapped grants emit no rules"
484        );
485        assert_eq!(check_no_escalation(&u, &policy, &p), Ok(()));
486    }
487
488    #[test]
489    fn default_deny_on_unmapped_request() {
490        let p = permissions();
491        let l = lattice(3);
492        let u = ucan_with(vec![cap("mac://model/*", "model/read")]);
493        let policy = compile(&u, &l, &p);
494        // Unmapped verb → no rule → deny.
495        let req = AccessRequest {
496            resource: Resource::new("mac://model/qwen"),
497            ability: Ability::new("admin/x"),
498            caveats: Caveats::empty(),
499        };
500        assert_eq!(matrix_decides(&p, &policy.matrix, &req), Decision::Deny);
501        // Unmapped resource → no rule → deny.
502        let req2 = AccessRequest {
503            resource: Resource::new("mac://other/z"),
504            ability: Ability::new("model/read"),
505            caveats: Caveats::empty(),
506        };
507        assert_eq!(matrix_decides(&p, &policy.matrix, &req2), Decision::Deny);
508    }
509
510    // ---- TE matrix well-formedness ------------------------------------------
511
512    #[test]
513    fn matrix_well_formed_no_contradiction() {
514        // allow ∩ escalate = ∅ (a triple is never both Permit and Escalate), even
515        // with a non-empty escalate band; te_decision is single-valued and
516        // default-deny; and the compiler itself emits no escalate band.
517        let allow = HashSet::from([
518            TeRule {
519                subject_type: SubjectType(1),
520                object_type: ObjectType(0),
521                action: TeAction(0),
522            },
523            TeRule {
524                subject_type: SubjectType(1),
525                object_type: ObjectType(1),
526                action: TeAction(0),
527            },
528        ]);
529        let escalate = HashSet::from([TeRule {
530            subject_type: SubjectType(1),
531            object_type: ObjectType(2),
532            action: TeAction(1),
533        }]);
534        let matrix = TeMatrix::new(allow, escalate);
535        let (a_vec, e_vec) = matrix.sorted_rules();
536        let a_set: BTreeSet<_> = a_vec.into_iter().collect();
537        let e_set: BTreeSet<_> = e_vec.into_iter().collect();
538        assert!(!e_set.is_empty(), "must exercise a non-empty escalate band");
539        assert!(a_set.is_disjoint(&e_set), "allow ∩ escalate must be ∅");
540        for r in &a_set {
541            assert_eq!(matrix.te_decision(*r), Decision::Permit);
542        }
543        for r in &e_set {
544            assert_eq!(matrix.te_decision(*r), Decision::Escalate);
545        }
546        let absent = TeRule {
547            subject_type: SubjectType(9),
548            object_type: ObjectType(9),
549            action: TeAction(9),
550        };
551        assert_eq!(matrix.te_decision(absent), Decision::Deny, "absent ⇒ deny");
552
553        let p = permissions();
554        let l = lattice(3);
555        let policy = compile(
556            &ucan_with(vec![cap("mac://model/qwen", "model/read")]),
557            &l,
558            &p,
559        );
560        assert!(
561            policy.matrix.sorted_rules().1.is_empty(),
562            "the compiler must not produce an escalate band"
563        );
564    }
565
566    // ---- compile: determinism -----------------------------------------------
567
568    #[test]
569    fn compile_is_deterministic_byte_identical_hash() {
570        let p = permissions();
571        let l = lattice(5);
572        let u1 = ucan_with(vec![
573            cap("mac://model/qwen", "model/read"),
574            cap("mac://model/llama", "model/write"),
575        ]);
576        let u2 = ucan_with(vec![
577            cap("mac://model/llama", "model/write"),
578            cap("mac://model/qwen", "model/read"),
579        ]);
580        let h1 = compile(&u1, &l, &p).policy_hash().unwrap();
581        let h2 = compile(&u2, &l, &p).policy_hash().unwrap();
582        assert_eq!(h1, h2, "compilation must be order-independent");
583    }
584
585    #[test]
586    fn compile_generation_bound_to_lattice() {
587        let p = permissions();
588        let l = lattice(42);
589        let u = ucan_with(vec![cap("mac://model/qwen", "model/read")]);
590        assert_eq!(compile(&u, &l, &p).generation, 42);
591    }
592
593    // ---- authorize (the reference decision) ---------------------------------
594
595    #[test]
596    fn authorize_decides_via_attenuation() {
597        let grant = vec![cap("mac://model/*", "model/read")];
598        assert_eq!(
599            authorize(
600                &grant,
601                &AccessRequest {
602                    resource: Resource::new("mac://model/qwen"),
603                    ability: Ability::new("model/read"),
604                    caveats: Caveats::empty(),
605                }
606            ),
607            Decision::Permit
608        );
609        assert_eq!(
610            authorize(
611                &grant,
612                &AccessRequest {
613                    resource: Resource::new("mac://model/qwen"),
614                    ability: Ability::new("model/write"),
615                    caveats: Caveats::empty(),
616                }
617            ),
618            Decision::Deny
619        );
620    }
621
622    #[test]
623    fn authorize_respects_caveats() {
624        let mut cv = BTreeMap::new();
625        cv.insert("tenant".to_owned(), CaveatValue::Text("acme".to_owned()));
626        let grant = vec![Capability::with_caveats(
627            Resource::new("mac://model/*"),
628            Ability::new("model/read"),
629            Caveats(cv.clone()),
630        )];
631        // No caveat → not covered → deny.
632        assert_eq!(
633            authorize(
634                &grant,
635                &AccessRequest {
636                    resource: Resource::new("mac://model/qwen"),
637                    ability: Ability::new("model/read"),
638                    caveats: Caveats::empty(),
639                }
640            ),
641            Decision::Deny
642        );
643        // Exact caveat → permit.
644        assert_eq!(
645            authorize(
646                &grant,
647                &AccessRequest {
648                    resource: Resource::new("mac://model/qwen"),
649                    ability: Ability::new("model/read"),
650                    caveats: Caveats(cv.clone()),
651                }
652            ),
653            Decision::Permit
654        );
655        // Different value for the same key → not covered → deny.
656        let mut wrong = BTreeMap::new();
657        wrong.insert("tenant".to_owned(), CaveatValue::Text("evil".to_owned()));
658        assert_eq!(
659            authorize(
660                &grant,
661                &AccessRequest {
662                    resource: Resource::new("mac://model/qwen"),
663                    ability: Ability::new("model/read"),
664                    caveats: Caveats(wrong),
665                }
666            ),
667            Decision::Deny
668        );
669        // Required caveat plus extra restriction (more restricted) → permit.
670        let mut more = cv;
671        more.insert("max".to_owned(), CaveatValue::Int(5));
672        assert_eq!(
673            authorize(
674                &grant,
675                &AccessRequest {
676                    resource: Resource::new("mac://model/qwen"),
677                    ability: Ability::new("model/read"),
678                    caveats: Caveats(more),
679                }
680            ),
681            Decision::Permit
682        );
683    }
684
685    #[test]
686    fn authorize_at_temporal_gate() {
687        // An expired / not-yet-valid grant denies even a covered request.
688        let grant = vec![cap("mac://model/qwen", "model/read")];
689        let nbf = Some(100);
690        let exp = Some(200);
691        let req = AccessRequest {
692            resource: Resource::new("mac://model/qwen"),
693            ability: Ability::new("model/read"),
694            caveats: Caveats::empty(),
695        };
696        assert_eq!(authorize_at(&grant, nbf, exp, &req, 150), Decision::Permit);
697        assert_eq!(authorize_at(&grant, nbf, exp, &req, 99), Decision::Deny);
698        assert_eq!(authorize_at(&grant, nbf, exp, &req, 201), Decision::Deny);
699        // Inclusive boundaries.
700        assert_eq!(authorize_at(&grant, nbf, exp, &req, 100), Decision::Permit);
701        assert_eq!(authorize_at(&grant, nbf, exp, &req, 200), Decision::Permit);
702    }
703
704    // ---- compile_policy: fail-closed signing --------------------------------
705
706    #[test]
707    fn compile_policy_signs_only_when_no_escalation() {
708        let p = permissions();
709        let l = lattice(11);
710        let id = identity();
711        let u = ucan_signed_by(&id, vec![cap("mac://model/qwen", "model/read")]);
712        let (policy, signed) = compile_policy(&u, &l, &p, &id.ed_sk, &id.pq_sk).unwrap();
713        signed
714            .verify_binds(
715                &id.ed_sk.verifying_key(),
716                &id.pq_vk,
717                &u,
718                policy.generation,
719                &policy.policy_hash().unwrap(),
720            )
721            .unwrap();
722    }
723
724    /// A PermissionMap that lowers ANY recognized capability to read AND write on
725    /// ALL objects — granting more than the source capability authorizes. Its
726    /// granted_access is the honest id→request inverse (it does not hide the
727    /// over-grant), so check_no_escalation catches the escalation.
728    struct EscalatingPermissions {
729        subject: SubjectType,
730    }
731    impl PermissionMap for EscalatingPermissions {
732        fn permissions_for(&self, cap: &Capability) -> BTreeSet<TeRule> {
733            if action_id(cap.ability.as_str()).is_none() {
734                return BTreeSet::new();
735            }
736            if !cap.resource.as_str().starts_with("mac://model/") {
737                return BTreeSet::new();
738            }
739            let mut out = BTreeSet::new();
740            for (oi, _name) in OBJECTS.iter().enumerate() {
741                for a in [TeAction(0), TeAction(1)] {
742                    out.insert(TeRule {
743                        subject_type: self.subject,
744                        object_type: ObjectType(oi as u32),
745                        action: a,
746                    });
747                }
748            }
749            out
750        }
751        fn granted_access(&self, rule: &TeRule) -> Option<AccessRequest> {
752            if rule.subject_type != self.subject {
753                return None;
754            }
755            let name = object_name(rule.object_type)?;
756            let verb = action_verb(rule.action)?;
757            Some(AccessRequest {
758                resource: Resource::new(format!("mac://model/{name}")),
759                ability: Ability::new(verb),
760                caveats: Caveats::empty(),
761            })
762        }
763    }
764
765    #[test]
766    fn compile_policy_refuses_escalating_map() {
767        // Drive compile_policy end-to-end with a genuinely escalating map and a
768        // narrow grant: it must return CompileError::Escalation and produce no
769        // SignedApproval.
770        let wide = EscalatingPermissions {
771            subject: SubjectType(1),
772        };
773        let l = lattice(3);
774        let id = identity();
775        let u = ucan_signed_by(&id, vec![cap("mac://model/qwen", "model/read")]);
776        match compile_policy(&u, &l, &wide, &id.ed_sk, &id.pq_sk) {
777            Err(CompileError::Escalation(PrivilegeEscalation { access, .. })) => {
778                assert!(access.is_some(), "escalation must name a concrete access");
779            }
780            other => panic!("an escalating map MUST be rejected (no signature); got {other:?}"),
781        }
782    }
783
784    #[test]
785    fn check_catches_escalation_a_self_check_would_miss() {
786        // A check that re-ran permissions_for would compare the map's output to a
787        // re-fold of itself and pass. check_no_escalation checks each rule's access
788        // against the grant instead, so it catches the over-grant.
789        let wide = EscalatingPermissions {
790            subject: SubjectType(1),
791        };
792        let l = lattice(3);
793        let u = ucan_with(vec![cap("mac://model/qwen", "model/read")]);
794        let policy = compile(&u, &l, &wide);
795
796        // The emitted allow-set equals a re-fold of the same permissions_for (a
797        // self-check would pass).
798        let self_fold: BTreeSet<TeRule> = {
799            let mut s = BTreeSet::new();
800            for c in u.capabilities() {
801                s.extend(wide.permissions_for(c));
802            }
803            s
804        };
805        assert_eq!(
806            allow_set(&policy),
807            self_fold,
808            "a self-check would pass this"
809        );
810
811        // The authority-anchored check catches it.
812        match check_no_escalation(&u, &policy, &wide) {
813            Err(PrivilegeEscalation {
814                access: Some(a), ..
815            }) => {
816                let claimed = a.as_capability();
817                assert!(
818                    !u.capabilities().iter().any(|h| h.authorizes(&claimed)),
819                    "the escalation's access must be unauthorized by the grant"
820                );
821            }
822            other => panic!("must catch the escalation; got {other:?}"),
823        }
824    }
825
826    // ---- from_verified keystone + tamper (S5 → S4 wiring) -------------------
827
828    struct StubSigner {
829        key: [u8; 32],
830    }
831    impl PolicySigner for StubSigner {
832        fn sign(&self, input: &[u8]) -> Result<Vec<u8>, PolicyDistError> {
833            let mut h = blake3::Hasher::new();
834            h.update(&self.key);
835            h.update(input);
836            Ok(h.finalize().as_bytes().to_vec())
837        }
838    }
839    struct StubVerifier {
840        key: [u8; 32],
841    }
842    impl PolicyVerifier for StubVerifier {
843        fn verify(&self, input: &[u8], sig: &[u8]) -> Result<(), PolicyDistError> {
844            let mut h = blake3::Hasher::new();
845            h.update(&self.key);
846            h.update(input);
847            if h.finalize().as_bytes().as_slice() == sig {
848                Ok(())
849            } else {
850                Err(PolicyDistError::BadSignature("stub mismatch".into()))
851            }
852        }
853    }
854
855    #[test]
856    fn from_verified_keystone_then_loader_accepts() {
857        let p = permissions();
858        let l = lattice(13);
859        let id = identity();
860        let u = ucan_signed_by(&id, vec![cap("mac://model/qwen", "model/read")]);
861        let (policy, signed) = compile_policy(&u, &l, &p, &id.ed_sk, &id.pq_sk).unwrap();
862
863        let binding = signed.verify(&id.ed_sk.verifying_key(), &id.pq_vk).unwrap();
864        let approval = PolicyApproval::from_verified(binding);
865        assert_eq!(approval.generation, policy.generation);
866        assert_eq!(approval.approved_hash, policy.policy_hash().unwrap());
867
868        let key = [5u8; 32];
869        let signed_policy = sign_policy(&policy, &StubSigner { key }).unwrap();
870        let loader = PolicyLoader::new(StubVerifier { key }).with_approval(approval);
871        let loaded = loader.load(&signed_policy).unwrap();
872        assert_eq!(loaded.generation, policy.generation);
873    }
874
875    #[test]
876    fn tampered_hash_fails_verify_binds_before_loader() {
877        let p = permissions();
878        let l = lattice(13);
879        let id = identity();
880        let u = ucan_signed_by(&id, vec![cap("mac://model/qwen", "model/read")]);
881        let (policy, signed) = compile_policy(&u, &l, &p, &id.ed_sk, &id.pq_sk).unwrap();
882
883        let mut tampered = policy.policy_hash().unwrap();
884        tampered[0] ^= 0xFF;
885        let res = signed.verify_binds(
886            &id.ed_sk.verifying_key(),
887            &id.pq_vk,
888            &u,
889            policy.generation,
890            &tampered,
891        );
892        assert!(
893            matches!(
894                res,
895                Err(hyprstream_rpc::auth::ucan::approval::ApprovalError::BundleHashMismatch)
896            ),
897            "a tampered hash must fail verify_binds before the loader"
898        );
899    }
900
901    // ---- differential property tests: matrix evaluation ≡ authorize ---------
902
903    /// Adversarial capabilities: exact, wildcard, near-misses, and an unmapped
904    /// namespace.
905    fn arb_capability() -> impl Strategy<Value = Capability> {
906        let resources = prop_oneof![
907            Just("mac://model/qwen"),
908            Just("mac://model/llama"),
909            Just("mac://model/mistral"),
910            Just("mac://model/*"),
911            Just("mac://model/qwen2"), // superstring of "qwen"
912            Just("mac://model/qwe"),   // non-boundary prefix of "qwen"
913            Just("mac://model"),       // bare prefix
914            Just("mac://other/x"),     // unmapped namespace
915        ];
916        let abilities = prop_oneof![
917            Just("model/read"),
918            Just("model/write"),
919            Just("model/rea"), // near-miss prefix of "model/read"
920            Just("model"),     // bare namespace
921            Just("admin/x"),   // unmapped verb
922        ];
923        (resources, abilities).prop_map(|(r, a)| cap(r, a))
924    }
925
926    fn arb_grant() -> impl Strategy<Value = Vec<Capability>> {
927        prop::collection::vec(arb_capability(), 0..5)
928    }
929
930    /// Adversarial requests: mapped objects/verbs plus near-misses the matrix must
931    /// not permit unless a grant capability truly authorizes them.
932    fn arb_request() -> impl Strategy<Value = AccessRequest> {
933        let resources = prop_oneof![
934            Just("mac://model/qwen"),
935            Just("mac://model/llama"),
936            Just("mac://model/mistral"),
937            Just("mac://model/qwen2"),
938            Just("mac://model/qwe"),
939            Just("mac://other/z"),
940        ];
941        let abilities = prop_oneof![
942            Just("model/read"),
943            Just("model/write"),
944            Just("model/rea"),
945            Just("admin/y"),
946        ];
947        (resources, abilities).prop_map(|(r, a)| AccessRequest {
948            resource: Resource::new(r),
949            ability: Ability::new(a),
950            caveats: Caveats::empty(),
951        })
952    }
953
954    /// Is the request in the map's recognized domain (concrete object AND verb)?
955    /// Uses the inverse id maps, not permissions_for.
956    fn is_mapped(req: &AccessRequest) -> bool {
957        let obj_ok = req
958            .resource
959            .as_str()
960            .strip_prefix("mac://model/")
961            .is_some_and(|name| OBJECTS.contains(&name));
962        let verb_ok = action_id(req.ability.as_str()).is_some();
963        obj_ok && verb_ok
964    }
965
966    /// Decide a request against the emitted matrix directly: permit iff some emitted
967    /// rule's granted_access authorizes it. Evaluates the compiled matrix the way a
968    /// PEP would, then maps each granted rule back through `authorizes` — no call to
969    /// permissions_for.
970    fn matrix_decides(p: &TestPermissions, matrix: &TeMatrix, req: &AccessRequest) -> Decision {
971        let claimed = req.as_capability();
972        let (allow, _escalate) = matrix.sorted_rules();
973        for rule in &allow {
974            if matrix.te_decision(*rule) != Decision::Permit {
975                continue;
976            }
977            if let Some(a) = p.granted_access(rule) {
978                if a.as_capability().authorizes(&claimed) {
979                    return Decision::Permit;
980                }
981            }
982        }
983        Decision::Deny
984    }
985
986    proptest! {
987        #![proptest_config(ProptestConfig::with_cases(512))]
988
989        /// The matrix evaluation agrees with `authorize` on every adversarial
990        /// request, and the policy never escalates for any grant.
991        #[test]
992        fn matrix_agrees_with_authorize(
993            grant in arb_grant(),
994            req in arb_request(),
995        ) {
996            let p = permissions();
997            let l = lattice(1);
998            let u = ucan_with(grant.clone());
999            let policy = compile(&u, &l, &p);
1000
1001            prop_assert_eq!(check_no_escalation(&u, &policy, &p), Ok(()));
1002
1003            let reference = authorize(u.capabilities(), &req);
1004            let matrix = matrix_decides(&p, &policy.matrix, &req);
1005
1006            // Security direction over the full space: the matrix never permits what
1007            // the reference denies.
1008            if matrix == Decision::Permit {
1009                prop_assert_eq!(reference, Decision::Permit,
1010                    "matrix permitted what authorize denies (escalation) on {:?}", req);
1011            }
1012
1013            // Full agreement holds on the mapped domain; outside it the matrix is
1014            // intentionally silent (default-deny) — a safe under-grant.
1015            if is_mapped(&req) {
1016                prop_assert_eq!(matrix, reference,
1017                    "on the mapped domain, matrix and authorize must agree on {:?} for grant {:?}",
1018                    req, grant);
1019            }
1020        }
1021
1022        /// One-directional no-escalation: the matrix can never permit what
1023        /// `authorize` denies.
1024        #[test]
1025        fn matrix_permit_implies_authorize_permit(
1026            grant in arb_grant(),
1027            req in arb_request(),
1028        ) {
1029            let p = permissions();
1030            let l = lattice(1);
1031            let u = ucan_with(grant);
1032            let policy = compile(&u, &l, &p);
1033            if matrix_decides(&p, &policy.matrix, &req) == Decision::Permit {
1034                prop_assert_eq!(authorize(u.capabilities(), &req), Decision::Permit,
1035                    "matrix permitted what authorize denies — an escalation");
1036            }
1037        }
1038
1039        /// Temporal: out of the grant's window, `authorize_at` denies even when the
1040        /// matrix would permit; in window, matrix permit implies authorize permit.
1041        #[test]
1042        fn temporal_gate_differential(
1043            grant in arb_grant(),
1044            req in arb_request(),
1045            now in 0u64..400u64,
1046        ) {
1047            let p = permissions();
1048            let l = lattice(1);
1049            let mut u = ucan_with(grant);
1050            u.payload.not_before = Some(100);
1051            u.payload.expiration = Some(200);
1052            let policy = compile(&u, &l, &p);
1053
1054            let matrix_permits = matrix_decides(&p, &policy.matrix, &req) == Decision::Permit;
1055            let at = authorize_at(
1056                u.capabilities(),
1057                u.payload.not_before,
1058                u.payload.expiration,
1059                &req,
1060                now,
1061            );
1062            let in_window = (100..=200).contains(&now);
1063
1064            if !in_window {
1065                prop_assert_eq!(at, Decision::Deny,
1066                    "out-of-window request must be denied (now={})", now);
1067            } else if matrix_permits {
1068                prop_assert_eq!(at, Decision::Permit,
1069                    "in-window matrix permit must match authorize permit");
1070            }
1071        }
1072
1073        /// Reordering the grant's capabilities yields a byte-identical policy hash.
1074        #[test]
1075        fn compile_is_deterministic_under_reordering(
1076            grant in arb_grant(),
1077            seed in any::<u64>(),
1078        ) {
1079            let p = permissions();
1080            let l = lattice(1);
1081            let mut shuffled = grant.clone();
1082            if shuffled.len() > 1 {
1083                let n = shuffled.len();
1084                let k = (seed as usize) % n;
1085                shuffled.rotate_left(k);
1086                shuffled.reverse();
1087            }
1088            let h1 = compile(&ucan_with(grant), &l, &p).policy_hash().unwrap();
1089            let h2 = compile(&ucan_with(shuffled), &l, &p).policy_hash().unwrap();
1090            prop_assert_eq!(h1, h2, "reordering the grant must not change the hash");
1091        }
1092    }
1093}