1use 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
29pub trait PermissionMap {
33 fn permissions_for(&self, cap: &Capability) -> BTreeSet<TeRule>;
36
37 fn granted_access(&self, rule: &TeRule) -> Option<AccessRequest>;
41}
42
43#[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
61pub 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#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct PrivilegeEscalation {
77 pub rule: TeRule,
79 pub access: Option<AccessRequest>,
82}
83
84pub 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
118pub 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
137pub 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
149pub 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#[derive(Debug, thiserror::Error)]
174pub enum CompileError {
175 #[error("compiled policy escalates privilege beyond the grant: {0:?}")]
177 Escalation(PrivilegeEscalation),
178 #[error("policy hash failed: {0}")]
180 Hash(#[from] PolicyDistError),
181 #[error("approval signing failed: {0}")]
183 Approval(#[from] ApprovalError),
184}
185
186pub 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 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 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 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 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 #[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 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), action: TeAction(1), };
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 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 policy.matrix = TeMatrix::from_allow(HashSet::new());
451 assert_eq!(check_no_escalation(&u, &policy, &p), Ok(()));
453 assert!(missing_permission(&u, &policy, &p).is_some());
455 }
456
457 #[test]
458 fn wildcard_grant_fans_out_no_wildcard_rule() {
459 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 #[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 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 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 #[test]
513 fn matrix_well_formed_no_contradiction() {
514 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 #[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 #[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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 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"), Just("mac://model/qwe"), Just("mac://model"), Just("mac://other/x"), ];
916 let abilities = prop_oneof![
917 Just("model/read"),
918 Just("model/write"),
919 Just("model/rea"), Just("model"), Just("admin/x"), ];
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 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 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 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 #[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 if matrix == Decision::Permit {
1009 prop_assert_eq!(reference, Decision::Permit,
1010 "matrix permitted what authorize denies (escalation) on {:?}", req);
1011 }
1012
1013 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 #[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 #[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 #[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}