1use std::time::{SystemTime, UNIX_EPOCH};
85
86use anyhow::{anyhow, bail, Context, Result};
87use ed25519_dalek::{SigningKey, VerifyingKey};
88use hyprstream_pds::ledger::{AllocationRecord, GrantClass as PdsGrantClass, Unit as PdsUnit};
89use hyprstream_rpc::auth::ucan::capability::{
90 Ability, Capability, CaveatValue, Caveats, Resource as CapabilityResource,
91};
92use hyprstream_rpc::auth::ucan::chain;
93use hyprstream_rpc::auth::ucan::token::{Ucan, UcanPayload, UCAN_AAD};
94use hyprstream_rpc::crypto::cose_sign::{sign_composite, verify_composite};
95#[cfg(test)]
96use hyprstream_rpc::crypto::pq::ml_dsa_generate_keypair;
97use hyprstream_rpc::crypto::pq::{
98 ml_dsa_sk_from_seed, ml_dsa_sk_to_vk_bytes, ml_dsa_vk_from_bytes, MlDsaSigningKey,
99 MlDsaVerifyingKey,
100};
101use hyprstream_rpc::identity::Did;
102use rand::RngCore;
103
104use hyprstream_k8s::grant::{TenantGrantArtifacts, TenantGrantService, TenantGrantServiceError};
105use hyprstream_k8s::mesh::{TenantBinding, TenantEntitlement, TenantGrantClass};
106
107pub const TENANT_GRANT_ED25519_PURPOSE: &str = "hyprstream-tenant-grant-ed25519-v1";
115
116pub const TENANT_GRANT_ABILITY: &str = "ledger/spend";
124
125const CAVEAT_KIND: &str = "hs:tenant-grant:v1";
129
130#[derive(Clone)]
143pub struct TenantGrantIssuer {
144 ed_sk: SigningKey,
145 pq_sk: MlDsaSigningKey,
146 ed_vk: VerifyingKey,
150 pq_vk: MlDsaVerifyingKey,
151 issuer_did: Did,
152}
153
154impl std::fmt::Debug for TenantGrantIssuer {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 f.debug_struct("TenantGrantIssuer")
157 .field("issuer_did", &self.issuer_did.as_str())
158 .finish_non_exhaustive()
159 }
160}
161
162impl TenantGrantIssuer {
163 pub fn from_keys(ed_sk: SigningKey, pq_sk: MlDsaSigningKey) -> Result<Self> {
168 let ed_vk = ed_sk.verifying_key();
169 let pq_vk = ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(&pq_sk))
176 .context("decode the ML-DSA-65 verifying key from the signing key")?;
177 let issuer_did = Did::from_ed25519(&ed_vk.to_bytes());
178 Ok(Self {
179 ed_sk,
180 pq_sk,
181 ed_vk,
182 pq_vk,
183 issuer_did,
184 })
185 }
186
187 pub fn from_node_root(root: &SigningKey) -> Result<Self> {
196 let ed_sk =
197 hyprstream_rpc::node_identity::derive_purpose_key(root, TENANT_GRANT_ED25519_PURPOSE);
198 let pq_sk = derive_tenant_grant_mldsa_key(&ed_sk);
199 Self::from_keys(ed_sk, pq_sk)
200 }
201
202 #[cfg(test)]
204 #[allow(clippy::expect_used)]
205 pub fn generate_for_test() -> Self {
206 let mut ed_bytes = [0u8; 32];
207 rand::thread_rng().fill_bytes(&mut ed_bytes);
208 let ed_sk = SigningKey::from_bytes(&ed_bytes);
209 let pq_sk = ml_dsa_generate_keypair().0;
210 Self::from_keys(ed_sk, pq_sk)
211 .expect("a freshly generated keypair always decodes its verifying key")
212 }
213
214 pub fn issuer_did(&self) -> &Did {
216 &self.issuer_did
217 }
218
219 pub fn issuer_ed_vk(&self) -> VerifyingKey {
221 self.ed_vk
222 }
223
224 pub fn issuer_pq_vk(&self) -> MlDsaVerifyingKey {
226 self.pq_vk.clone()
227 }
228
229 pub fn compile(
242 &self,
243 binding: &TenantBinding,
244 epoch: u64,
245 now: u64,
246 ) -> Result<CompiledTenantGrant> {
247 let entitlement = binding
248 .spec
249 .entitlement
250 .as_ref()
251 .context("TenantBinding carries no entitlement — nothing to compile")?;
252
253 validate_entitlement(entitlement, now)?;
254
255 let holder = binding.spec.tenant.as_str();
265
266 let capability = tenant_grant_capability(&self.issuer_did, holder, entitlement, epoch)?;
267
268 let payload = UcanPayload {
269 issuer: self.issuer_did.clone(),
270 audience: self.issuer_did.clone(),
271 capabilities: vec![capability],
272 not_before: Some(now),
273 expiration: entitlement.expiration,
274 nonce: fresh_nonce(),
278 };
279 let signing_bytes = payload
280 .signing_bytes()
281 .context("encode UCAN payload signing bytes")?;
282 let signature = sign_composite(&self.ed_sk, Some(&self.pq_sk), &signing_bytes, UCAN_AAD)
283 .context("hybrid-PQC sign of UCAN payload")?;
284 let ucan = Ucan {
285 payload,
286 proofs: Vec::new(),
287 signature,
288 };
289
290 let grant_cid = cid_v1_string(&ucan)?;
295
296 let allocation = AllocationRecord::new(
297 grant_cid.clone(),
298 PdsUnit {
299 code: entitlement.unit.clone(),
300 issuer: self.issuer_did.as_str().to_owned(),
301 },
302 entitlement.amount,
303 epoch,
304 self.issuer_did.as_str(),
305 holder,
306 pds_grant_class(entitlement.class),
307 )
308 .context("construct allocation record")?;
309
310 let allocation_cid = allocation.cid().encode();
311
312 Ok(CompiledTenantGrant {
313 ucan,
314 allocation,
315 grant_cid,
316 allocation_cid,
317 epoch,
318 })
319 }
320}
321
322#[derive(Clone, Debug)]
333pub struct CompiledTenantGrant {
334 pub ucan: Ucan,
336 pub allocation: AllocationRecord,
338 pub grant_cid: String,
341 pub allocation_cid: String,
343 pub epoch: u64,
345}
346
347#[derive(Clone)]
363pub struct TenantGrantVerifier {
364 issuer_ed_vk: VerifyingKey,
365 issuer_pq_vk: MlDsaVerifyingKey,
366}
367
368impl std::fmt::Debug for TenantGrantVerifier {
369 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370 f.debug_struct("TenantGrantVerifier")
371 .field("issuer_ed_vk", &self.issuer_ed_vk.to_bytes())
372 .finish_non_exhaustive()
373 }
374}
375
376impl TenantGrantVerifier {
377 pub fn new(issuer_ed_vk: VerifyingKey, issuer_pq_vk: MlDsaVerifyingKey) -> Self {
380 Self {
381 issuer_ed_vk,
382 issuer_pq_vk,
383 }
384 }
385
386 pub fn from_issuer(issuer: &TenantGrantIssuer) -> Self {
388 Self::new(issuer.issuer_ed_vk(), issuer.issuer_pq_vk())
389 }
390
391 pub fn verify(&self, compiled: &CompiledTenantGrant, now: u64) -> Result<VerifiedTenantGrant> {
396 compiled
398 .ucan
399 .validate_structure()
400 .context("UCAN structural validation failed")?;
401
402 let signing_bytes = compiled
407 .ucan
408 .payload
409 .signing_bytes()
410 .context("encode UCAN payload signing bytes for verify")?;
411 let verified = verify_composite(
412 &compiled.ucan.signature,
413 &self.issuer_ed_vk,
414 Some(&self.issuer_pq_vk),
415 &signing_bytes,
416 UCAN_AAD,
417 true,
418 )
419 .context("UCAN composite signature verification failed")?;
420 if !verified.ml_dsa {
421 bail!("tenant grant signature missing the ML-DSA-65 leg (require_pq)");
422 }
423
424 let anchored_issuer = Did::from_ed25519(&self.issuer_ed_vk.to_bytes());
428 if compiled.ucan.payload.issuer != anchored_issuer {
429 bail!(
430 "UCAN payload issuer ({}) does not match the anchored issuer key ({})",
431 compiled.ucan.payload.issuer.as_str(),
432 anchored_issuer.as_str()
433 );
434 }
435
436 let recomputed_grant_cid = cid_v1_string(&compiled.ucan)?;
442 if recomputed_grant_cid != compiled.grant_cid {
443 bail!(
444 "presented grant CID ({}) does not match the UCAN's recomputed CID ({})",
445 compiled.grant_cid,
446 recomputed_grant_cid
447 );
448 }
449
450 chain::validate_chain(&compiled.ucan, now)
455 .context("UCAN chain/liveness validation failed")?;
456
457 let record_bytes = compiled.allocation.to_dag_cbor();
460 let redecoded = AllocationRecord::from_dag_cbor(&record_bytes)
461 .context("allocation record failed canonical round-trip")?;
462 if redecoded != compiled.allocation {
463 bail!("allocation record canonical round-trip mismatch");
464 }
465
466 let recomputed_allocation_cid = redecoded.cid().encode();
470 if recomputed_allocation_cid != compiled.allocation_cid {
471 bail!(
472 "presented allocation CID ({}) does not match the record's recomputed CID ({})",
473 compiled.allocation_cid,
474 recomputed_allocation_cid
475 );
476 }
477
478 if redecoded.issuer != anchored_issuer.as_str() {
483 bail!(
484 "allocation.issuer ({}) does not match the anchored issuer ({})",
485 redecoded.issuer,
486 anchored_issuer.as_str()
487 );
488 }
489 if redecoded.unit.issuer != anchored_issuer.as_str() {
490 bail!(
491 "allocation.unit.issuer ({}) does not match the anchored issuer ({})",
492 redecoded.unit.issuer,
493 anchored_issuer.as_str()
494 );
495 }
496
497 if redecoded.grant != compiled.grant_cid {
500 bail!(
501 "allocation.grant ({}) does not reference the presented grant CID ({})",
502 redecoded.grant,
503 compiled.grant_cid
504 );
505 }
506
507 verify_capability_matches_record(&compiled.ucan, &anchored_issuer, &redecoded)?;
514
515 Ok(VerifiedTenantGrant {
516 holder: redecoded.holder,
517 unit: redecoded.unit.code,
518 cap_amount: redecoded.amount,
519 exp: compiled.ucan.payload.expiration,
520 epoch: redecoded.epoch,
521 class: redecoded.class,
522 })
523 }
524}
525
526#[derive(Clone, Debug, PartialEq, Eq)]
535pub struct VerifiedTenantGrant {
536 pub holder: String,
538 pub unit: String,
540 pub cap_amount: u64,
542 pub exp: Option<u64>,
544 pub epoch: u64,
546 pub class: PdsGrantClass,
548}
549
550fn derive_tenant_grant_mldsa_key(ed25519_key: &SigningKey) -> MlDsaSigningKey {
560 let derived = hyprstream_rpc::node_identity::derive_purpose_key(
561 ed25519_key,
562 "hyprstream-tenant-grant-mldsa-v1",
563 );
564 let seed = derived.to_bytes();
565 ml_dsa_sk_from_seed(&seed)
572}
573
574fn tenant_grant_capability(
584 issuer: &Did,
585 holder: &str,
586 entitlement: &TenantEntitlement,
587 epoch: u64,
588) -> Result<Capability> {
589 let resource = CapabilityResource::new(tenant_grant_resource(issuer, holder));
590 let ability = Ability::new(TENANT_GRANT_ABILITY);
591 let amount = i64::try_from(entitlement.amount)
595 .context("entitlement.amount exceeds i64::MAX and cannot be encoded as a caveat")?;
596 let epoch = i64::try_from(epoch)
597 .context("allocation epoch exceeds i64::MAX and cannot be encoded as a caveat")?;
598 let mut caveats = Caveats::empty();
599 caveats
600 .0
601 .insert("kind".to_owned(), CaveatValue::Text(CAVEAT_KIND.to_owned()));
602 caveats.0.insert(
603 "unit".to_owned(),
604 CaveatValue::Text(entitlement.unit.clone()),
605 );
606 caveats
607 .0
608 .insert("amount".to_owned(), CaveatValue::Int(amount));
609 caveats
610 .0
611 .insert("epoch".to_owned(), CaveatValue::Int(epoch));
612 caveats.0.insert(
613 "class".to_owned(),
614 CaveatValue::Text(entitlement.class.as_str().to_owned()),
615 );
616 Ok(Capability {
617 resource,
618 ability,
619 caveats,
620 })
621}
622
623fn tenant_grant_resource(issuer: &Did, holder: &str) -> String {
627 format!("hs://tenant/{}/{}", issuer.as_str(), holder)
628}
629
630fn verify_capability_matches_record(
634 ucan: &Ucan,
635 anchored_issuer: &Did,
636 record: &AllocationRecord,
637) -> Result<()> {
638 let caps = ucan.capabilities();
639 let cap = caps
640 .first()
641 .ok_or_else(|| anyhow!("tenant grant UCAN carries no capability"))?;
642 if cap.ability.as_str() != TENANT_GRANT_ABILITY {
643 bail!(
644 "tenant grant capability has unexpected ability {} (require exactly {})",
645 cap.ability,
646 TENANT_GRANT_ABILITY
647 );
648 }
649 let expected_resource = tenant_grant_resource(anchored_issuer, &record.holder);
653 if cap.resource.as_str() != expected_resource {
654 bail!(
655 "grant capability resource ({}) does not bind the allocation holder ({})",
656 cap.resource.as_str(),
657 record.holder
658 );
659 }
660 let cv = |key: &str| -> Result<&CaveatValue> {
661 cap.caveats
662 .0
663 .get(key)
664 .ok_or_else(|| anyhow!("tenant grant caveat missing {key:?}"))
665 };
666 match cv("kind")? {
667 CaveatValue::Text(t) if t == CAVEAT_KIND => {}
668 other => bail!("grant caveat kind mismatch: {other:?}"),
669 }
670 match cv("unit")? {
671 CaveatValue::Text(t) if t == &record.unit.code => {}
672 other => bail!("grant caveat unit does not match record: {other:?}"),
673 }
674 match cv("amount")? {
676 CaveatValue::Int(a) if u64::try_from(*a) == Ok(record.amount) => {}
677 other => bail!("grant caveat amount does not match record: {other:?}"),
678 }
679 match cv("epoch")? {
680 CaveatValue::Int(e) if u64::try_from(*e) == Ok(record.epoch) => {}
681 other => bail!("grant caveat epoch does not match record: {other:?}"),
682 }
683 match cv("class")? {
684 CaveatValue::Text(t) if t == &record.class.as_str().to_owned() => {}
685 other => bail!("grant caveat class does not match record: {other:?}"),
686 }
687 Ok(())
688}
689
690fn validate_entitlement(entitlement: &TenantEntitlement, now: u64) -> Result<()> {
691 if entitlement.unit.is_empty() {
692 bail!("entitlement.unit must not be empty");
693 }
694 if entitlement.unit.chars().any(char::is_whitespace) {
695 bail!("entitlement.unit must not contain whitespace");
696 }
697 if let Some(exp) = entitlement.expiration {
698 if exp <= now {
699 bail!(
700 "entitlement.expiration ({exp}) must be in the future (now {now}); a grant that \
701 is born expired is never valid"
702 );
703 }
704 }
705 Ok(())
706}
707
708fn fresh_nonce() -> Vec<u8> {
710 let mut buf = [0u8; 16];
711 rand::thread_rng().fill_bytes(&mut buf);
712 buf.to_vec()
713}
714
715fn cid_v1_string(ucan: &Ucan) -> Result<String> {
719 let bytes = ucan
720 .to_cbor()
721 .context("UCAN CBOR encoding is infallible for this shape; encoding error is a bug")?;
722 Ok(hyprstream_pds::cid::Cid::from_dag_cbor(&bytes).encode())
723}
724
725pub fn now_unix() -> u64 {
730 SystemTime::now()
731 .duration_since(UNIX_EPOCH)
732 .map(|d| d.as_secs())
733 .unwrap_or(0)
734}
735
736fn pds_grant_class(class: TenantGrantClass) -> PdsGrantClass {
738 match class {
739 TenantGrantClass::Prepaid => PdsGrantClass::Prepaid,
740 TenantGrantClass::Underwritten => PdsGrantClass::Underwritten,
741 }
742}
743
744impl TenantGrantService for TenantGrantIssuer {
745 fn compile_grant(
746 &self,
747 binding: &TenantBinding,
748 epoch: u64,
749 now: u64,
750 ) -> Result<TenantGrantArtifacts, TenantGrantServiceError> {
751 let compiled = self
752 .compile(binding, epoch, now)
753 .map_err(|error| TenantGrantServiceError::new(format!("{error:#}")))?;
754 TenantGrantArtifacts::new(compiled.grant_cid, compiled.allocation_cid, compiled.epoch)
755 }
756}
757
758#[cfg(test)]
759mod tests {
760 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
761 use super::*;
762 use hyprstream_k8s::mesh::{TenantBindingSpec, TenantEntitlement};
763
764 fn binding(unit: &str, amount: u64, class: TenantGrantClass) -> TenantBinding {
765 TenantBinding::new(
766 "acme",
767 TenantBindingSpec {
768 namespace: "acme".to_owned(),
769 tenant: "did:web:tenant.acme.example".to_owned(),
770 entitlement: Some(TenantEntitlement {
771 unit: unit.to_owned(),
772 amount,
773 class,
774 expiration: None,
775 }),
776 },
777 )
778 }
779
780 #[test]
781 fn compile_then_verify_round_trips() {
782 let issuer = TenantGrantIssuer::generate_for_test();
783 let verifier = TenantGrantVerifier::from_issuer(&issuer);
784 let now = 1_700_000_000u64;
785 let binding = binding("compute-second", 3_600, TenantGrantClass::Underwritten);
786
787 let compiled = issuer
788 .compile(&binding, 7, now)
789 .expect("compile must succeed for a valid entitlement");
790
791 assert_eq!(compiled.allocation.grant, compiled.grant_cid);
793 assert!(compiled.grant_cid.starts_with('b'));
795 assert!(compiled.allocation_cid.starts_with('b'));
796
797 let verified = verifier
798 .verify(&compiled, now)
799 .expect("verify must succeed");
800 assert_eq!(verified.holder, "did:web:tenant.acme.example");
801 assert_eq!(verified.unit, "compute-second");
802 assert_eq!(verified.cap_amount, 3_600);
803 assert_eq!(verified.epoch, 7);
804 assert_eq!(verified.class, PdsGrantClass::Underwritten);
805 assert_eq!(verified.exp, None);
806 }
807
808 #[test]
809 fn tenant_grant_issuer_implements_k8s_service_boundary() {
810 let issuer = TenantGrantIssuer::generate_for_test();
811 let binding = binding("compute-second", 3_600, TenantGrantClass::Underwritten);
812 let status = hyprstream_k8s::grant::compile_tenant_binding_status(
813 &binding,
814 Some(&issuer),
815 7,
816 1_700_000_000,
817 );
818
819 assert_eq!(status.bound, Some(true));
820 assert_eq!(status.phase.as_deref(), Some("Bound"));
821 assert!(status
822 .grant_cid
823 .as_deref()
824 .is_some_and(|cid| cid.starts_with('b')));
825 assert!(status
826 .allocation_cid
827 .as_deref()
828 .is_some_and(|cid| cid.starts_with('b')));
829 assert_eq!(status.epoch, Some(7));
830 }
831
832 #[test]
833 fn two_compiles_of_the_same_binding_yield_distinct_grants() {
834 let issuer = TenantGrantIssuer::generate_for_test();
836 let now = 1_700_000_000u64;
837 let binding = binding("gpu-hour", 8, TenantGrantClass::Prepaid);
838 let a = issuer.compile(&binding, 1, now).unwrap();
839 let b = issuer.compile(&binding, 1, now).unwrap();
840 assert_ne!(a.grant_cid, b.grant_cid, "fresh nonce ⇒ distinct CIDs");
841 assert_ne!(a.allocation_cid, b.allocation_cid);
842 }
843
844 #[test]
845 fn verify_rejects_a_tampered_allocation_amount() {
846 let issuer = TenantGrantIssuer::generate_for_test();
847 let verifier = TenantGrantVerifier::from_issuer(&issuer);
848 let now = 1_700_000_000u64;
849 let binding = binding("compute-second", 100, TenantGrantClass::Underwritten);
850 let mut compiled = issuer.compile(&binding, 1, now).unwrap();
851
852 compiled.allocation = AllocationRecord::new(
855 compiled.grant_cid.clone(),
856 PdsUnit {
857 code: "compute-second".to_owned(),
858 issuer: issuer.issuer_did().as_str().to_owned(),
859 },
860 200,
861 1,
862 issuer.issuer_did().as_str(),
863 "did:web:tenant.acme.example",
864 PdsGrantClass::Underwritten,
865 )
866 .unwrap();
867 compiled.allocation_cid = compiled.allocation.cid().encode();
870
871 let err = verifier.verify(&compiled, now).unwrap_err();
872 assert!(
873 err.to_string().contains("amount"),
874 "tampered amount must be caught: {err}"
875 );
876 }
877
878 #[test]
879 fn verify_rejects_a_classical_only_signature() {
880 let issuer_ed_sk = {
883 let mut b = [0u8; 32];
884 rand::thread_rng().fill_bytes(&mut b);
885 SigningKey::from_bytes(&b)
886 };
887 let issuer_did = Did::from_ed25519(&issuer_ed_sk.verifying_key().to_bytes());
888 let now = 1_700_000_000u64;
889 let binding = binding("compute-second", 5, TenantGrantClass::Prepaid);
890
891 let entitlement = binding.spec.entitlement.as_ref().unwrap();
892 let capability =
893 tenant_grant_capability(&issuer_did, &binding.spec.tenant, entitlement, 1).unwrap();
894 let payload = UcanPayload {
895 issuer: issuer_did.clone(),
896 audience: issuer_did.clone(),
897 capabilities: vec![capability],
898 not_before: Some(now),
899 expiration: None,
900 nonce: fresh_nonce(),
901 };
902 let signing_bytes = payload.signing_bytes().unwrap();
903 let signature = sign_composite(&issuer_ed_sk, None, &signing_bytes, UCAN_AAD).unwrap();
905 let ucan = Ucan {
906 payload,
907 proofs: Vec::new(),
908 signature,
909 };
910 let grant_cid = cid_v1_string(&ucan).unwrap();
911 let allocation = AllocationRecord::new(
912 grant_cid.clone(),
913 PdsUnit {
914 code: "compute-second".to_owned(),
915 issuer: issuer_did.as_str().to_owned(),
916 },
917 5,
918 1,
919 issuer_did.as_str(),
920 "did:web:tenant.acme.example",
921 PdsGrantClass::Prepaid,
922 )
923 .unwrap();
924 let compiled = CompiledTenantGrant {
925 ucan,
926 allocation_cid: allocation.cid().encode(),
927 allocation,
928 grant_cid,
929 epoch: 1,
930 };
931
932 let verifier = TenantGrantVerifier::new(
934 issuer_ed_sk.verifying_key(),
935 ml_dsa_generate_keypair().1,
938 );
939 let err = verifier.verify(&compiled, now).unwrap_err();
940 assert!(
941 err.to_string().to_lowercase().contains("signature")
942 || err.to_string().contains("ML-DSA"),
943 "classical-only signature must fail closed: {err}"
944 );
945 }
946
947 #[test]
948 fn verify_rejects_an_expired_grant() {
949 let issuer = TenantGrantIssuer::generate_for_test();
950 let verifier = TenantGrantVerifier::from_issuer(&issuer);
951 let now = 1_700_000_000u64;
952
953 let mut binding = binding("compute-second", 1, TenantGrantClass::Underwritten);
954 binding.spec.entitlement.as_mut().unwrap().expiration = Some(now + 10);
955
956 let compiled = issuer.compile(&binding, 1, now).unwrap();
957 let err = verifier.verify(&compiled, now + 100).unwrap_err();
959 assert!(
960 err.to_string().to_lowercase().contains("expir")
961 || err.to_string().contains("liveness")
962 || err.to_string().contains("window"),
963 "expired grant must be rejected: {err}"
964 );
965 }
966
967 #[test]
968 fn verify_rejects_a_substituted_holder() {
969 let issuer = TenantGrantIssuer::generate_for_test();
974 let verifier = TenantGrantVerifier::from_issuer(&issuer);
975 let now = 1_700_000_000u64;
976 let binding = binding("compute-second", 100, TenantGrantClass::Underwritten);
977 let mut compiled = issuer.compile(&binding, 1, now).unwrap();
978
979 compiled.allocation = AllocationRecord::new(
980 compiled.grant_cid.clone(),
981 PdsUnit {
982 code: "compute-second".to_owned(),
983 issuer: issuer.issuer_did().as_str().to_owned(),
984 },
985 100,
986 1,
987 issuer.issuer_did().as_str(),
988 "did:web:evil.example",
989 PdsGrantClass::Underwritten,
990 )
991 .unwrap();
992 compiled.allocation_cid = compiled.allocation.cid().encode();
993
994 let err = verifier.verify(&compiled, now).unwrap_err();
995 assert!(
996 err.to_string().contains("holder") || err.to_string().contains("resource"),
997 "substituted holder must be caught by the signed resource binding: {err}"
998 );
999 }
1000
1001 #[test]
1002 fn verify_rejects_a_forged_grant_cid_binding() {
1003 let issuer = TenantGrantIssuer::generate_for_test();
1008 let verifier = TenantGrantVerifier::from_issuer(&issuer);
1009 let now = 1_700_000_000u64;
1010 let binding = binding("compute-second", 100, TenantGrantClass::Underwritten);
1011 let mut compiled = issuer.compile(&binding, 1, now).unwrap();
1012
1013 let fake_cid = "bafyreifakefakefakefakefakefakefakefakefakefakefakefakefake".to_owned();
1014 compiled.allocation.grant = fake_cid.clone();
1015 compiled.grant_cid = fake_cid;
1016 compiled.allocation_cid = compiled.allocation.cid().encode();
1017
1018 let err = verifier.verify(&compiled, now).unwrap_err();
1019 assert!(
1020 err.to_string().contains("recomputed"),
1021 "forged grant CID must be caught by recomputation: {err}"
1022 );
1023 }
1024
1025 #[test]
1026 fn verify_rejects_a_foreign_allocation_issuer() {
1027 let issuer = TenantGrantIssuer::generate_for_test();
1028 let verifier = TenantGrantVerifier::from_issuer(&issuer);
1029 let now = 1_700_000_000u64;
1030 let binding = binding("compute-second", 100, TenantGrantClass::Underwritten);
1031 let mut compiled = issuer.compile(&binding, 1, now).unwrap();
1032
1033 compiled.allocation = AllocationRecord::new(
1034 compiled.grant_cid.clone(),
1035 PdsUnit {
1036 code: "compute-second".to_owned(),
1037 issuer: "did:web:other-operator.example".to_owned(),
1038 },
1039 100,
1040 1,
1041 "did:web:other-operator.example",
1042 "did:web:tenant.acme.example",
1043 PdsGrantClass::Underwritten,
1044 )
1045 .unwrap();
1046 compiled.allocation_cid = compiled.allocation.cid().encode();
1047
1048 let err = verifier.verify(&compiled, now).unwrap_err();
1049 assert!(
1050 err.to_string().contains("issuer"),
1051 "foreign allocation issuer must be rejected: {err}"
1052 );
1053 }
1054
1055 #[test]
1056 fn verify_rejects_a_mismatched_allocation_cid() {
1057 let issuer = TenantGrantIssuer::generate_for_test();
1058 let verifier = TenantGrantVerifier::from_issuer(&issuer);
1059 let now = 1_700_000_000u64;
1060 let binding = binding("compute-second", 100, TenantGrantClass::Underwritten);
1061 let mut compiled = issuer.compile(&binding, 1, now).unwrap();
1062
1063 compiled.allocation_cid = "bafyreinotwhatwascomputed".to_owned();
1064
1065 let err = verifier.verify(&compiled, now).unwrap_err();
1066 assert!(
1067 err.to_string().contains("allocation CID"),
1068 "mismatched allocation CID must be rejected: {err}"
1069 );
1070 }
1071
1072 #[test]
1073 fn compile_rejects_amount_above_i64_max() {
1074 let issuer = TenantGrantIssuer::generate_for_test();
1077 let binding = binding("compute-second", u64::MAX, TenantGrantClass::Underwritten);
1078 let err = issuer.compile(&binding, 1, 1_700_000_000).unwrap_err();
1079 assert!(err.to_string().contains("amount"), "{err}");
1080 }
1081
1082 #[test]
1083 fn compile_rejects_epoch_above_i64_max() {
1084 let issuer = TenantGrantIssuer::generate_for_test();
1085 let binding = binding("compute-second", 1, TenantGrantClass::Underwritten);
1086 let err = issuer
1087 .compile(&binding, u64::MAX, 1_700_000_000)
1088 .unwrap_err();
1089 assert!(err.to_string().contains("epoch"), "{err}");
1090 }
1091
1092 #[test]
1093 fn compile_without_entitlement_is_an_error() {
1094 let issuer = TenantGrantIssuer::generate_for_test();
1095 let binding = TenantBinding::new(
1096 "acme",
1097 TenantBindingSpec {
1098 namespace: "acme".to_owned(),
1099 tenant: "did:web:t".to_owned(),
1100 entitlement: None,
1101 },
1102 );
1103 assert!(issuer.compile(&binding, 1, 1_700_000_000).is_err());
1104 }
1105
1106 #[test]
1107 fn compile_rejects_inverted_expiration() {
1108 let issuer = TenantGrantIssuer::generate_for_test();
1109 let now = 1_700_000_000u64;
1110 let mut binding = binding("compute-second", 1, TenantGrantClass::Underwritten);
1111 binding.spec.entitlement.as_mut().unwrap().expiration = Some(now - 1);
1112 assert!(issuer.compile(&binding, 1, now).is_err());
1113 }
1114
1115 #[test]
1116 fn from_node_root_is_deterministic() {
1117 let mut seed = [0u8; 32];
1118 rand::thread_rng().fill_bytes(&mut seed);
1119 let root = SigningKey::from_bytes(&seed);
1120 let a = TenantGrantIssuer::from_node_root(&root).unwrap();
1121 let b = TenantGrantIssuer::from_node_root(&root).unwrap();
1122 assert_eq!(
1123 a.issuer_did(),
1124 b.issuer_did(),
1125 "same root ⇒ same issuer DID"
1126 );
1127 assert_eq!(
1128 a.issuer_ed_vk().to_bytes(),
1129 b.issuer_ed_vk().to_bytes(),
1130 "purpose derivation is deterministic"
1131 );
1132 }
1133}