Skip to main content

hyprstream_k8s_pds/
lib.rs

1//! AGPL PDS adapter for [`hyprstream_k8s::mesh::TenantBinding`] grant compilation.
2//!
3//! A `TenantBinding` is an **admin-authorable surface**, never the authority.
4//! When [`hyprstream_k8s::mesh::TenantBindingSpec::entitlement`] is set, the
5//! operator invokes this adapter through
6//! [`hyprstream_k8s::grant::TenantGrantService`] and compiles
7//! it — signing **as issuer** — into the two artifacts that *are* the authority:
8//!
9//! 1. A **UCAN grant** ([`hyprstream_rpc::auth::ucan::Ucan`]) — an
10//!    issuer→holder capability signed with the project's hybrid-PQC COSE
11//!    composite (EdDSA + ML-DSA-65) via
12//!    [`hyprstream_rpc::crypto::cose_sign::sign_composite`] with `UCAN_AAD`.
13//!    The operator is the issuer; the tenant is the audience/holder.
14//! 2. An **`ai.hyprstream.ledger.allocation` record**
15//!    ([`hyprstream_pds::ledger::AllocationRecord`]) — the inventory line that
16//!    **lands in the tenant's PDS**, whose `grant` field references the UCAN's
17//!    CID. This is the durable, holder-controlled entitlement; revocation is
18//!    bumping the epoch (stop renewing + reissue), not editing the CRD.
19//!
20//! Enforcers (#781/#787/#790/#793/#794/#527) verify the **presented grant**
21//! (the UCAN CID + its allocation record), never the CRD. [`TenantGrantVerifier`]
22//! is the verification contract — the exact shape of that consume-side check —
23//! so the consumer issues can wire it without re-deriving the compile/verify
24//! correspondence.
25//!
26//! ## What this module deliberately leaves to the consumer issues
27//!
28//! Per #929's narrow scope:
29//! - **PDS publish** of the allocation record into the tenant's MST (the
30//!   physical "lands in inventory") — needs the #910 multi-collection write
31//!   path + the tenant's signing key, both operator-bootstrap concerns. This
32//!   module produces the record; landing it is plumbing.
33//! - **Operator issuer-key bootstrap in-cluster** — [`TenantGrantIssuer`]
34//!   takes already-resolved key material; deriving it from `node_identity`'s
35//!   root store at operator startup is the K5b runtime's job.
36//! - **Enforcer consumption** (admission, receipts, autoscaling bounds) —
37//!   #781/#787/#790/#793/#794/#527/#792/#795/#784. The compiled grant is the
38//!   primitive they consume; [`TenantGrantVerifier`] is the contract.
39//! - **S6 short-ttl sender-bound (DPoP) renewal** — greenfield (#921 gap 2);
40//!   the `epoch` counter on the allocation record is the revocation handle
41//!   until the renewal layer exists.
42//!
43//! ## Downstream composition
44//!
45//! The Apache substrate depends only on its service-neutral contract. A
46//! downstream binary enables the substrate's `k8s,grant` features, opts into
47//! this AGPL adapter, and passes the issuer to the generic operator without
48//! contacting a cluster during compilation:
49//!
50//! ```no_run
51//! use std::sync::Arc;
52//! use hyprstream_k8s::kube::Client;
53//! use hyprstream_k8s::operator::{
54//!     run_operator_with_grant_service, HyprstreamOperatorRpc, OperatorConfig,
55//!     OperatorError, OperatorState,
56//! };
57//! use hyprstream_k8s_pds::TenantGrantIssuer;
58//!
59//! fn configured_state<R: HyprstreamOperatorRpc>(
60//!     client: Client,
61//!     rpc: Arc<R>,
62//!     config: OperatorConfig,
63//!     issuer: TenantGrantIssuer,
64//! ) -> OperatorState<R> {
65//!     OperatorState::new(client, rpc, config)
66//!         .with_grant_service(Some(Arc::new(issuer)))
67//! }
68//!
69//! async fn run<R: HyprstreamOperatorRpc>(
70//!     client: Client,
71//!     rpc: Arc<R>,
72//!     config: OperatorConfig,
73//!     issuer: TenantGrantIssuer,
74//! ) -> Result<(), OperatorError> {
75//!     run_operator_with_grant_service(
76//!         client,
77//!         rpc,
78//!         config,
79//!         Some(Arc::new(issuer)),
80//!     ).await
81//! }
82//! ```
83
84use 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
107/// HKDF purpose label for the operator's tenant-grant Ed25519 issuer key.
108///
109/// Key-separated (PQUIP) from the node's mesh/JWT/KEM purposes in
110/// `hyprstream_rpc::node_identity`: a `TenantGrantIssuer` key is bound to
111/// exactly one cryptographic purpose — *issuing tenant entitlement grants* —
112/// so a compromise of any other derived key cannot forge a grant. Use via
113/// [`TenantGrantIssuer::from_node_root`].
114pub const TENANT_GRANT_ED25519_PURPOSE: &str = "hyprstream-tenant-grant-ed25519-v1";
115
116/// The UCAN ability a compiled tenant grant carries.
117///
118/// `ledger/spend` is the resource-class verb an enforcer's
119/// `GrantVerifier`-shaped check attenuates against: a holder may spend the
120/// granted amount of the granted unit, attenuated by the capability caveats
121/// (unit/amount/epoch/class). The action-vocabulary seam (#582) maps this to
122/// concrete enforcer operations later; it is structural here.
123pub const TENANT_GRANT_ABILITY: &str = "ledger/spend";
124
125/// Domain-separation tag included in every compiled grant's capability caveat
126/// map so a tenant grant can never be confused with another UCAN capability
127/// type sharing the `ledger/spend` ability.
128const CAVEAT_KIND: &str = "hs:tenant-grant:v1";
129
130/// The operator's issuer key material for compiling tenant grants.
131///
132/// Holds the Ed25519 + ML-DSA-65 signing keys the operator signs UCANs with,
133/// plus the derived issuer DID. The operator is the **unit issuer** (D8-1:
134/// credits are the unit-issuer's liability), so every grant compiled by one
135/// issuer carries that issuer's DID as both the UCAN `issuer` and the
136/// allocation record `issuer`/`unit.issuer`.
137///
138/// Construct with [`TenantGrantIssuer::from_keys`] (production: keys resolved
139/// from the node identity store) or [`TenantGrantIssuer::from_node_root`]
140/// (derives a purpose-separated key from the operator's persisted root), or
141/// `TenantGrantIssuer::generate_for_test` in unit tests.
142#[derive(Clone)]
143pub struct TenantGrantIssuer {
144    ed_sk: SigningKey,
145    pq_sk: MlDsaSigningKey,
146    // Verifying keys + issuer DID are derived once at construction (the keys are
147    // immutable for the issuer's lifetime) and cached so the hot paths are pure
148    // accessors — no per-call trait dispatch, no re-deriving the DID.
149    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    /// Construct from already-resolved key material.
164    ///
165    /// The issuer DID is derived from `ed_sk`'s verifying key so the two can
166    /// never drift.
167    pub fn from_keys(ed_sk: SigningKey, pq_sk: MlDsaSigningKey) -> Result<Self> {
168        let ed_vk = ed_sk.verifying_key();
169        // Resolve the PQ verifying key through the `hyprstream_crypto::pq` byte
170        // helpers rather than the `Keypair` trait so this crate does not take a
171        // direct dep on the `signature`/`ml_dsa` crates just to call
172        // `sk.verifying_key()`. Decoding can only fail on a malformed signing
173        // key, which is a caller bug — surfaced as an error rather than a panic
174        // so this constructor is clippy-clean under the `-D expect_used` lint.
175        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    /// Derive a purpose-separated tenant-grant issuer from the operator's
188    /// persisted node root key.
189    ///
190    /// Mirrors `hyprstream_rpc::node_identity::derive_mesh_mldsa_key` (HKDF
191    /// over the Ed25519 seed) but under the dedicated
192    /// [`TENANT_GRANT_ED25519_PURPOSE`] label, then re-seeds the ML-DSA-65 key
193    /// from the derived Ed25519 bytes. Key-separated from every other derived
194    /// purpose (PQUIP).
195    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    /// Generate a fresh, random issuer keypair (tests only).
203    #[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    /// The issuer DID (the operator's `did:key` for this grant purpose).
215    pub fn issuer_did(&self) -> &Did {
216        &self.issuer_did
217    }
218
219    /// The issuer's Ed25519 verifying key (the verifier-side anchor).
220    pub fn issuer_ed_vk(&self) -> VerifyingKey {
221        self.ed_vk
222    }
223
224    /// The issuer's ML-DSA-65 verifying key (the PQ leg of the composite).
225    pub fn issuer_pq_vk(&self) -> MlDsaVerifyingKey {
226        self.pq_vk.clone()
227    }
228
229    /// Compile a [`TenantBinding`]'s entitlement into the issuer-signed grant +
230    /// inventory allocation record (#929).
231    ///
232    /// `epoch` is the issuance epoch (revocation = bump it + reissue); `now` is
233    /// unix seconds used for `not_before` and to sanity-check an author-supplied
234    /// `expiration`. The CRD's [`TenantEntitlement`] is the authoring surface;
235    /// the returned [`CompiledTenantGrant`] is the authority that lands in the
236    /// tenant's inventory.
237    ///
238    /// Fails closed on any malformation: an absent entitlement, a tenant DID
239    /// that cannot anchor an Ed25519 audience, an inverted expiry, or a signing
240    /// error. It never emits a half-signed grant.
241    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        // The holder/audience is the tenant DID. UCAN audiences are did:key
256        // (Ed25519) for signature linkage; we accept any did: method the PDS
257        // already classifies, but the UCAN payload's audience is stored as the
258        // tenant string verbatim. A non-did:key audience is still a valid
259        // *allocation record* holder (pairwise or did:web), but the UCAN chain
260        // validator requires did:key, so we issue the UCAN to the operator's
261        // own issuer DID as the capability owner and encode the holder in the
262        // capability resource + caveats. The allocation record's `holder`
263        // (below) is the authoritative subject.
264        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            // Replay-uniqueness: a fresh random nonce per compiled grant. Two
275            // compiles of the same binding at the same epoch (e.g. operator
276            // restart) yield distinct UCANs/CIDs by construction.
277            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        // The grant CID is the atproto-canonical content address of the UCAN:
291        // CIDv1 dag-cbor (sha2-256) over its canonical CBOR. This is the
292        // `format: "cid"` string the allocation record's `grant` field
293        // references and enforcers present.
294        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/// The output of compiling a [`TenantBinding`]: the authority artifacts.
323///
324/// - [`Self::ucan`] is the issuer-signed capability (presented by the holder,
325///   verified by enforcers).
326/// - [`Self::allocation`] is the `ai.hyprstream.ledger.allocation` record that
327///   lands in the tenant's PDS inventory (whose `grant` field references
328///   [`Self::grant_cid`]).
329/// - [`Self::grant_cid`] / [`Self::allocation_cid`] are the CIDv1 strings the
330///   operator records in [`hyprstream_k8s::mesh::TenantBindingStatus`] as
331///   observed truth.
332#[derive(Clone, Debug)]
333pub struct CompiledTenantGrant {
334    /// The issuer-signed UCAN grant.
335    pub ucan: Ucan,
336    /// The inventory allocation record (lands in the tenant's PDS).
337    pub allocation: AllocationRecord,
338    /// CIDv1 of [`Self::ucan`] — what enforcers present + what
339    /// `allocation.grant` references.
340    pub grant_cid: String,
341    /// CIDv1 of [`Self::allocation`] — the durable inventory line.
342    pub allocation_cid: String,
343    /// The issuance epoch recorded on the allocation.
344    pub epoch: u64,
345}
346
347/// The verification contract for enforcers (#781/#787/#790/#793/#794/#527).
348///
349/// This is the exact check a consumer enforcer performs on a *presented* grant:
350/// structural UCAN validation → hybrid-PQC composite signature verification
351/// against the issuer's anchored keys (require_pq = true, fail-closed) →
352/// delegation-chain liveness at `now` → allocation record round-trip →
353/// grant-CID↔allocation binding. On success it yields a
354/// [`VerifiedTenantGrant`] shaped exactly like the enforcer-plane
355/// `VerifiedGrant { holder, unit, cap_amount, exp, epoch }` so the consumer
356/// issues map it 1:1.
357///
358/// A production `GrantVerifier` impl resolves `grant_cid → (Ucan,
359/// AllocationRecord)` by fetching from the holder's PDS, then calls
360/// [`TenantGrantVerifier::verify`]; this struct owns only the verify-once
361/// half so it is trivially testable without a PDS.
362#[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    /// Construct from the issuer's verifying keys (the anchored side of
378    /// [`TenantGrantIssuer`]).
379    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    /// Construct from an issuer (mirrors its public keys).
387    pub fn from_issuer(issuer: &TenantGrantIssuer) -> Self {
388        Self::new(issuer.issuer_ed_vk(), issuer.issuer_pq_vk())
389    }
390
391    /// Verify a compiled grant the way an enforcer will.
392    ///
393    /// `now` is unix seconds; the UCAN's `not_before`/`expiration` window is
394    /// checked against it via [`chain::validate`].
395    pub fn verify(&self, compiled: &CompiledTenantGrant, now: u64) -> Result<VerifiedTenantGrant> {
396        // 1. Structural validity (DIDs resolve, window is well-ordered).
397        compiled
398            .ucan
399            .validate_structure()
400            .context("UCAN structural validation failed")?;
401
402        // 2. Hybrid-PQC composite signature over the payload signing bytes,
403        //    against the issuer's anchored keys. require_pq = true: a
404        //    classical-only signature on a tenant grant is a fail-closed
405        //    reject (a long-lived authority artifact must be HNDL-resistant).
406        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        // 2b. The signed payload's issuer MUST be the DID of the anchored
425        //     Ed25519 key. Without this, a UCAN validly signed by the anchored
426        //     key could claim a different issuer identity in its payload.
427        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        // 2c. The presented `grant_cid` MUST be the recomputed CID of the
437        //     presented UCAN. The signature covers only the UCAN payload — the
438        //     CID strings arrive alongside it, so an attacker could otherwise
439        //     pair a valid UCAN with an arbitrary `grant_cid` and a forged
440        //     allocation that references that same arbitrary string.
441        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        // 3. Delegation-chain liveness. A compiled tenant grant is a root
451        //    (empty proofs), so this re-checks the not_before/expiration window
452        //    against `now` — enforcers MUST reject an expired grant even if the
453        //    signature is valid.
454        chain::validate_chain(&compiled.ucan, now)
455            .context("UCAN chain/liveness validation failed")?;
456
457        // 4. The allocation record round-trips through its canonical DAG-CBOR
458        //    — a tampered record cannot survive this.
459        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        // 4b. The presented `allocation_cid` MUST be the recomputed CID of the
467        //     presented record — same reasoning as the grant CID: the CID
468        //     string is unsigned transport metadata, never trusted as given.
469        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        // 4c. The allocation's issuer fields MUST be the anchored issuer: the
479        //     signature proves who signed the UCAN, but the allocation record
480        //     itself is unsigned here — an attacker could otherwise attach a
481        //     record naming a different issuer/unit-issuer to a valid UCAN.
482        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        // 5. The allocation's `grant` field MUST reference the presented UCAN's
498        //    CID, binding the inventory line to the capability it draws down.
499        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        // 6. The capability must agree with the allocation record: exact
508        //    ability, holder bound through the signed resource, and caveats
509        //    matching the record fields (unit/amount/epoch/class). This is
510        //    what stops a holder-substitution: the holder lives in the
511        //    *signed* capability resource, so a forged record naming a
512        //    different holder cannot match it.
513        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/// The verified shape of a compiled tenant grant — the data an enforcer admits
527/// against.
528///
529/// Field-for-field compatible with the enforcer-plane
530/// `hyprstream::services::ledger::VerifiedGrant { holder, unit, cap_amount, exp,
531/// epoch }`; the consumer issues implement their `GrantVerifier` by resolving a
532/// presented `grant_cid` to a [`CompiledTenantGrant`] and calling
533/// [`TenantGrantVerifier::verify`].
534#[derive(Clone, Debug, PartialEq, Eq)]
535pub struct VerifiedTenantGrant {
536    /// The holder (tenant DID / pairwise id) whose inventory this grant is.
537    pub holder: String,
538    /// The issuer-scoped credit unit code (the unit's issuer is the operator).
539    pub unit: String,
540    /// The total cap authorized (smallest quantum).
541    pub cap_amount: u64,
542    /// Grant expiry (unix seconds), if the UCAN carries one.
543    pub exp: Option<u64>,
544    /// Allocation epoch (revocation counter).
545    pub epoch: u64,
546    /// Grant class.
547    pub class: PdsGrantClass,
548}
549
550// ────────────────────────────────────────────────────────────────────────────
551// Helpers
552// ────────────────────────────────────────────────────────────────────────────
553
554/// Derive the tenant-grant ML-DSA-65 key from a derived Ed25519 purpose key.
555///
556/// Mirrors `node_identity::derive_mesh_mldsa_key` (re-seed ML-DSA-65 from the
557/// derived Ed25519 bytes) but is kept local so the `TENANT_GRANT_ED25519_PURPOSE`
558/// separation is the single source of truth for both legs.
559fn 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    // NOTE: the reference derivation in `node_identity::derive_mesh_mldsa_key`
566    // zeroizes the seed here; we omit that only to avoid taking a direct dep on
567    // the `zeroize` crate in this otherwise-light crate. The seed is a 32-byte
568    // stack value derived from an already-purpose-separated HKDF output, dropped
569    // immediately; the key-separation (distinct HKDF label) is the load-bearing
570    // property, not the in-memory wipe.
571    ml_dsa_sk_from_seed(&seed)
572}
573
574/// Build the single capability a tenant grant carries.
575///
576/// - `resource` = `hs://tenant/<issuer>/<holder>` — names *whose inventory* the
577///   grant is in (the issuer's liability, the holder's balance), scoped under
578///   the issuer so two operators' grants cannot cross-contend.
579/// - `ability` = `ledger/spend` ([`TENANT_GRANT_ABILITY`]).
580/// - `caveats` bind the unit / amount / epoch / class / kind so attenuation is
581///   value-aware at the enforcer (a delegated subset cannot widen amount or
582///   flip class).
583fn 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    // `CaveatValue::Int` is signed; a value that cannot be represented is a
592    // hard error, never a clamp — a clamped amount would mint a grant that
593    // fails its own verification, and a wrapped epoch would encode as negative.
594    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
623/// The capability resource string binding an issuer's liability to a holder's
624/// balance: `hs://tenant/<issuer>/<holder>`. Single source of truth for both
625/// the compile side and the verify side's holder-binding check.
626fn tenant_grant_resource(issuer: &Did, holder: &str) -> String {
627    format!("hs://tenant/{}/{}", issuer.as_str(), holder)
628}
629
630/// Verify the UCAN capability matches the allocation record: exactly one
631/// capability with exactly [`TENANT_GRANT_ABILITY`], the holder bound through
632/// the signed resource string, and caveats matching the record's fields.
633fn 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    // The holder is not a caveat — it lives in the signed resource string. The
650    // record's holder MUST reconstruct the exact resource the issuer signed,
651    // or the record names a substituted holder.
652    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    // Lossless compare: a negative caveat can never equal a u64 field.
675    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
708/// 16-byte random nonce, fresh per compile.
709fn fresh_nonce() -> Vec<u8> {
710    let mut buf = [0u8; 16];
711    rand::thread_rng().fill_bytes(&mut buf);
712    buf.to_vec()
713}
714
715/// The atproto-canonical CIDv1 string of a UCAN (dag-cbor, sha2-256) over its
716/// canonical CBOR encoding. This is the `format: "cid"` string the allocation
717/// record's `grant` field references and enforcers present.
718fn 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
725/// Unix seconds from the system wall clock; never panics on platforms without a
726/// wall clock (returns 0, which fails the expiry check closed). Used by the
727/// operator's `TenantBinding` reconcile to stamp `not_before` and check
728/// author-supplied expiries.
729pub fn now_unix() -> u64 {
730    SystemTime::now()
731        .duration_since(UNIX_EPOCH)
732        .map(|d| d.as_secs())
733        .unwrap_or(0)
734}
735
736/// Map the Apache data contract to the PDS lexicon.
737fn 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        // The allocation record references the grant CID.
792        assert_eq!(compiled.allocation.grant, compiled.grant_cid);
793        // The grant CID is a CIDv1 string.
794        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        // The nonce makes each compile unique even at the same epoch.
835        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        // Tamper: bump the allocation amount without re-signing the UCAN. The
853        // capability caveat (amount=100) no longer matches the record (200).
854        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        // Keep the presented allocation CID consistent with the tampered
868        // record so the signed amount caveat is what catches the tamper.
869        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        // A grant signed without the PQ leg must fail closed at verify
881        // (require_pq = true) — the long-lived authority must be HNDL-resistant.
882        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        // Classical-only sign (pq_sk = None).
904        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        // Verifier anchored on the Ed25519 key but WITH a PQ key requirement.
933        let verifier = TenantGrantVerifier::new(
934            issuer_ed_sk.verifying_key(),
935            // A throwaway, *wrong* PQ key: a classical-only signature cannot
936            // satisfy require_pq regardless of the anchored PQ key.
937            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        // Verify at `now + 100`: past expiration.
958        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        // A valid signed UCAN paired with a forged allocation record naming a
970        // different holder: every unsigned field (grant ref, unit, amount,
971        // epoch, class, issuer, allocation CID) is made self-consistent, so
972        // only the signed capability resource can catch the substitution.
973        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        // The attacker controls both `grant_cid` and `allocation.grant`
1004        // (neither is covered by the UCAN signature), so making them agree on
1005        // an arbitrary string must still fail: the grant CID is recomputed
1006        // from the presented UCAN, never trusted as given.
1007        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        // No silent clamp: an amount that cannot be a signed caveat is a
1075        // compile error, never a grant that fails its own verification.
1076        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}