hyprstream_rpc/auth/ucan/token.rs
1//! The typed **UCAN token** model + structural validation + hybrid-COSE
2//! signature verification (S5 / #571, milestone 1).
3//!
4//! We control both ends of this UCAN — issuance and consumption are internal to
5//! the MAC epic — so this is a **minimal, typed** model rather than a full
6//! JOSE/JWT UCAN. Crucially, UCAN signing is aligned with the project's hybrid
7//! post-quantum COSE composite (EdDSA + ML-DSA-65), **not** a JWT `ucan` crate:
8//! a UCAN is a CBOR payload signed with [`crate::crypto::cose_sign::sign_composite`]
9//! and verified with [`crate::crypto::cose_sign::verify_composite`]
10//! (`require_pq = true`). This keeps the whole authority chain on the same
11//! HNDL-resistant signature suite the rest of the TCB uses.
12//!
13//! ## Shape
14//!
15//! ```text
16//! Ucan {
17//! payload: UcanPayload { // the signed bytes (canonical CBOR)
18//! issuer: Did, // did:key of the signer
19//! audience: Did, // did:key of the delegate
20//! capabilities: [Capability], // the granted authority
21//! not_before / expiration: Option<u64> (unix seconds),
22//! nonce: ...,
23//! },
24//! proofs: [Ucan], // the delegation chain (delegator UCANs)
25//! signature: Vec<u8>, // detached hybrid-COSE composite over payload
26//! }
27//! ```
28//!
29//! Signature *verification* lives here. Delegation-chain + attenuation
30//! validation lives in [`super::chain`] (it is the most security-critical piece
31//! and is isolated for that reason).
32
33use super::capability::Capability;
34use serde::{Deserialize, Serialize};
35use std::fmt;
36
37/// The canonical decentralized identifier — there is exactly **one** `did:key`
38/// type and parser in the TCB (#578). S5 milestone 1 originally carried a local
39/// `Did(String)` + its own `did_key_to_ed25519` call; milestone 2 (#571) folds it
40/// onto [`crate::identity::Did`] so no second DID type or parser survives. The
41/// UCAN layer still supports `did:key` (Ed25519) exclusively — the Ed25519 key is
42/// resolved on demand via [`crate::identity::Did::to_ed25519`] (which delegates to
43/// the SAME `crate::did_key` parser the rest of `hyprstream-rpc` uses).
44pub use crate::identity::Did;
45
46/// Domain-separation AAD for UCAN payload signatures (distinct from the
47/// compiled-policy, approval, audit, and envelope AADs so a UCAN signature can
48/// never be replayed as another message type). Signed and verified by every
49/// producer/consumer of UCANs — the test helpers, the chain validator, the
50/// production `UcanVerifier` (the HTTP grant path's trust-store-backed
51/// verifier), and cross-process consumers. Promoted to a public non-test
52/// constant by S8 (#574) so the production verifier shares the exact AAD the
53/// signers use (a mismatch silently fails signature verification).
54pub const UCAN_AAD: &[u8] = b"hs-mac-ucan-payload-v1";
55
56/// Resolve the Ed25519 verifying-key bytes a UCAN `did:key` issuer/audience
57/// encodes, mapped to a fail-closed [`UcanError`]. Thin adapter over the canonical
58/// [`Did::to_ed25519`] so the UCAN signature/structure paths keep their typed
59/// error without re-implementing any `did:key` parsing (single parser, #578).
60fn did_ed25519_key(did: &Did) -> Result<[u8; 32], UcanError> {
61 did.to_ed25519().map_err(|e| UcanError::BadDid {
62 did: did.as_str().to_owned(),
63 reason: e.to_string(),
64 })
65}
66
67/// The signed body of a UCAN: everything an issuer commits to with their
68/// signature. Serialized to canonical CBOR ([`UcanPayload::signing_bytes`]) to
69/// produce the exact bytes the hybrid-COSE composite signs/verifies.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct UcanPayload {
72 /// The issuer (signer) DID.
73 pub issuer: Did,
74 /// The audience (delegate) DID — who this UCAN grants authority to.
75 pub audience: Did,
76 /// The capabilities granted by this UCAN.
77 pub capabilities: Vec<Capability>,
78 /// `not before` — earliest unix second at which this UCAN is valid.
79 #[serde(default)]
80 pub not_before: Option<u64>,
81 /// `expiration` — unix second after which this UCAN is invalid. `None` =
82 /// non-expiring (discouraged but representable).
83 #[serde(default)]
84 pub expiration: Option<u64>,
85 /// Replay-uniqueness nonce.
86 #[serde(default)]
87 pub nonce: Vec<u8>,
88}
89
90impl UcanPayload {
91 /// Canonical CBOR bytes of the payload — the exact bytes that are signed and
92 /// verified. Deterministic for a given payload (ciborium emits map keys in
93 /// struct-field order; the same payload always yields identical bytes), so a
94 /// signature over these bytes is stable across processes.
95 ///
96 /// Serializing an in-memory payload into a `Vec` is infallible for this
97 /// shape; we still avoid `unwrap`/`expect` in non-test code and surface any
98 /// (unreachable) encoder error as a fail-closed [`UcanError`].
99 pub fn signing_bytes(&self) -> Result<Vec<u8>, UcanError> {
100 let mut buf = Vec::new();
101 ciborium::ser::into_writer(self, &mut buf).map_err(|e| UcanError::Encode(e.to_string()))?;
102 Ok(buf)
103 }
104}
105
106/// A UCAN: a signed payload plus the proof chain of delegator UCANs.
107///
108/// The chain is the `proofs` vector — each entry is the *delegator's* UCAN whose
109/// audience is this UCAN's issuer and whose capabilities must cover this UCAN's
110/// (validated in [`super::chain`]). A root UCAN (self-issued authority) has an
111/// empty `proofs` vector.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113pub struct Ucan {
114 /// The signed claims.
115 pub payload: UcanPayload,
116 /// The delegation chain: delegator UCANs that authorize this one. Empty for
117 /// a root.
118 #[serde(default)]
119 pub proofs: Vec<Ucan>,
120 /// Detached hybrid-COSE composite signature over [`UcanPayload::signing_bytes`].
121 pub signature: Vec<u8>,
122}
123
124impl Ucan {
125 /// Decode a UCAN from canonical CBOR. Pure structural decode — does NOT
126 /// verify signatures or attenuation (call [`Ucan::verify_signatures`] then
127 /// [`super::chain::validate_chain`]).
128 ///
129 /// Fail-closed DoS guard: a decoded chain whose nesting meets or exceeds
130 /// [`super::chain::MAX_PROOF_DEPTH`] is rejected here, before it is ever
131 /// walked, so a maliciously deep `proofs`-within-`proofs` token cannot reach
132 /// (or exhaust the stack in) the validator. (The validator independently
133 /// re-enforces the same bound during the walk.)
134 pub fn from_cbor(bytes: &[u8]) -> Result<Self, UcanError> {
135 let ucan: Ucan =
136 ciborium::de::from_reader(bytes).map_err(|e| UcanError::Decode(e.to_string()))?;
137 // Match the validator's bound exactly: the walk rejects once a link index
138 // reaches `MAX_PROOF_DEPTH` (links `0..MAX_PROOF_DEPTH` are allowed), so a
139 // `proof_depth` of `MAX_PROOF_DEPTH` or more is over-deep.
140 let depth = ucan.proof_depth();
141 if depth >= super::chain::MAX_PROOF_DEPTH {
142 return Err(UcanError::Malformed(format!(
143 "delegation chain nested {depth} deep meets/exceeds maximum proof depth {}",
144 super::chain::MAX_PROOF_DEPTH
145 )));
146 }
147 Ok(ucan)
148 }
149
150 /// The maximum nesting depth of this UCAN's proof chain: `0` for a root (no
151 /// proofs), otherwise `1 + max(proof.proof_depth())`. Used by [`from_cbor`]
152 /// as a parse-time DoS bound. Walks the in-memory tree iteratively-bounded by
153 /// the already-decoded structure (the decode itself is what we cap).
154 ///
155 /// [`from_cbor`]: Ucan::from_cbor
156 pub fn proof_depth(&self) -> usize {
157 self.proofs
158 .iter()
159 .map(|p| 1 + p.proof_depth())
160 .max()
161 .unwrap_or(0)
162 }
163
164 /// Encode this UCAN to canonical CBOR.
165 pub fn to_cbor(&self) -> Result<Vec<u8>, UcanError> {
166 let mut buf = Vec::new();
167 ciborium::ser::into_writer(self, &mut buf).map_err(|e| UcanError::Encode(e.to_string()))?;
168 Ok(buf)
169 }
170
171 /// The issuer DID of this UCAN.
172 pub fn issuer(&self) -> &Did {
173 &self.payload.issuer
174 }
175
176 /// The audience DID of this UCAN.
177 pub fn audience(&self) -> &Did {
178 &self.payload.audience
179 }
180
181 /// The capabilities this UCAN grants.
182 pub fn capabilities(&self) -> &[Capability] {
183 &self.payload.capabilities
184 }
185
186 /// The **root** of this delegation chain — the self-issued authority at the
187 /// top, the entry with an empty `proofs` vector. For a delegated grant this
188 /// is the resource-owning delegator; its [`issuer`] is the source of
189 /// authority (#680/#681: the `sub`/delegator principal, distinct from the
190 /// leaf [`audience`] = the actor/presenter).
191 ///
192 /// M1 walks the single-delegator-per-link chain via `proofs[0]` (the
193 /// linkage `super::chain::validate` also enforces). Depth is bounded by
194 /// [`super::chain::MAX_PROOF_DEPTH`] at decode, so this cannot runaway.
195 ///
196 /// [`issuer`]: Self::issuer
197 /// [`audience`]: Self::audience
198 #[must_use]
199 pub fn root(&self) -> &Ucan {
200 let mut cur = self;
201 while let Some(delegator) = cur.proofs.first() {
202 cur = delegator;
203 }
204 cur
205 }
206
207 /// The DID of the delegation-chain root's issuer — the ultimate source of
208 /// authority (the resource-owning delegator). Convenience over
209 /// [`Self::root`]`().issuer()`. See [`Self::root`].
210 #[must_use]
211 pub fn root_issuer(&self) -> &Did {
212 self.root().issuer()
213 }
214
215 /// **Structural** validation independent of crypto/attenuation: a UCAN is
216 /// structurally well-formed iff both its DIDs resolve to valid `did:key`
217 /// Ed25519 identities and (if present) `not_before <= expiration`. Each
218 /// proof is recursively checked. Fail-closed on any malformation.
219 pub fn validate_structure(&self) -> Result<(), UcanError> {
220 // DIDs must be resolvable did:key identifiers.
221 let _ = did_ed25519_key(&self.payload.issuer)?;
222 let _ = did_ed25519_key(&self.payload.audience)?;
223 if let (Some(nbf), Some(exp)) = (self.payload.not_before, self.payload.expiration) {
224 if nbf > exp {
225 return Err(UcanError::Malformed(format!(
226 "not_before ({nbf}) is after expiration ({exp})"
227 )));
228 }
229 }
230 for proof in &self.proofs {
231 proof.validate_structure()?;
232 }
233 Ok(())
234 }
235
236 /// Is this UCAN temporally valid at `now` (unix seconds)? `not_before`
237 /// inclusive, `expiration` inclusive of `now <= exp`. A `None` bound is
238 /// unbounded on that side.
239 #[must_use]
240 pub fn is_valid_at(&self, now: u64) -> bool {
241 if let Some(nbf) = self.payload.not_before {
242 if now < nbf {
243 return false;
244 }
245 }
246 if let Some(exp) = self.payload.expiration {
247 if now > exp {
248 return false;
249 }
250 }
251 true
252 }
253
254 /// Verify the hybrid-COSE composite signature on THIS UCAN's payload, AND
255 /// recursively on every proof in the chain. The issuer's classical key is
256 /// taken from its `did:key`; the matching ML-DSA-65 anchor is resolved
257 /// through `verifier` (the trust store / key-binding layer — the same
258 /// `register_pq_trust` reality `crypto::pq` models). Fail-closed: any link
259 /// whose signature does not verify (or whose PQ anchor is missing under the
260 /// hybrid policy) rejects the whole UCAN.
261 ///
262 /// This does NOT check attenuation/delegation linkage — that is
263 /// [`super::chain::validate_chain`], deliberately separate.
264 pub fn verify_signatures<V: UcanVerifier + ?Sized>(
265 &self,
266 verifier: &V,
267 ) -> Result<(), UcanError> {
268 let ed_bytes = did_ed25519_key(&self.payload.issuer)?;
269 let payload_bytes = self.payload.signing_bytes()?;
270 verifier.verify(
271 &self.payload.issuer,
272 &ed_bytes,
273 &payload_bytes,
274 &self.signature,
275 )?;
276 for proof in &self.proofs {
277 proof.verify_signatures(verifier)?;
278 }
279 Ok(())
280 }
281}
282
283/// Resolves a UCAN issuer's verified key material and checks a detached
284/// hybrid-COSE signature over the payload bytes.
285///
286/// This is the seam between "what DID/key-binding layer says is anchored" and
287/// "what the UCAN verifier trusts". The production implementor resolves the
288/// issuer's anchored ML-DSA-65 verifying key (via the `register_pq_trust` /
289/// `PqTrustStore` binding referenced in `crypto::cose_sign`) keyed by the
290/// issuer's Ed25519 identity and calls
291/// [`crate::crypto::cose_sign::verify_composite`] with `require_pq = true`. The
292/// classical Ed25519 key is supplied (already decoded from the `did:key`).
293pub trait UcanVerifier {
294 /// Verify `signature` (a hybrid-COSE composite) over `payload` for the given
295 /// `issuer`, whose decoded Ed25519 verifying key bytes are `ed_key`. Returns
296 /// `Ok(())` iff the composite verifies under the project's hybrid policy
297 /// (both EdDSA and the anchored ML-DSA-65 layer). Fail-closed otherwise.
298 fn verify(
299 &self,
300 issuer: &Did,
301 ed_key: &[u8; 32],
302 payload: &[u8],
303 signature: &[u8],
304 ) -> Result<(), UcanError>;
305}
306
307// Blanket forwarding impls so a `&dyn UcanVerifier` (or `Box<dyn …>`) can be
308// passed anywhere a generic `V: UcanVerifier` is expected — notably S5's
309// `chain::validate<V>` and S6's runtime grant path. Without these, the runtime
310// path would have to be monomorphized on a concrete verifier type, which fights
311// the dynamic trust-store resolution S6 needs.
312impl<V: UcanVerifier + ?Sized> UcanVerifier for &V {
313 fn verify(
314 &self,
315 issuer: &Did,
316 ed_key: &[u8; 32],
317 payload: &[u8],
318 signature: &[u8],
319 ) -> Result<(), UcanError> {
320 (**self).verify(issuer, ed_key, payload, signature)
321 }
322}
323
324impl<V: UcanVerifier + ?Sized> UcanVerifier for std::boxed::Box<V> {
325 fn verify(
326 &self,
327 issuer: &Did,
328 ed_key: &[u8; 32],
329 payload: &[u8],
330 signature: &[u8],
331 ) -> Result<(), UcanError> {
332 (**self).verify(issuer, ed_key, payload, signature)
333 }
334}
335
336/// Errors from UCAN parsing, structure, and signature verification. All map to a
337/// fail-closed rejection at the call site.
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub enum UcanError {
340 /// CBOR decode failure.
341 Decode(String),
342 /// CBOR encode failure (effectively unreachable for in-memory shapes).
343 Encode(String),
344 /// A DID was not a well-formed `did:key` Ed25519 identifier.
345 BadDid { did: String, reason: String },
346 /// Structurally malformed (e.g. inverted validity window).
347 Malformed(String),
348 /// A signature did not verify under the hybrid policy.
349 BadSignature(String),
350}
351
352impl fmt::Display for UcanError {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 match self {
355 UcanError::Decode(e) => write!(f, "UCAN decode failed: {e}"),
356 UcanError::Encode(e) => write!(f, "UCAN encode failed: {e}"),
357 UcanError::BadDid { did, reason } => write!(f, "invalid did:key {did}: {reason}"),
358 UcanError::Malformed(e) => write!(f, "malformed UCAN: {e}"),
359 UcanError::BadSignature(e) => write!(f, "UCAN signature verification failed: {e}"),
360 }
361 }
362}
363
364impl std::error::Error for UcanError {}
365
366#[cfg(test)]
367#[allow(clippy::unwrap_used)]
368pub(super) mod test_support {
369 //! Shared test helpers for building and signing UCANs with the real hybrid
370 //! COSE path. Visible to sibling test modules (`chain`, `approval`).
371 use super::*;
372 use crate::auth::ucan::capability::{Ability, Capability, Resource};
373 use crate::crypto::cose_sign::{sign_composite, verify_composite};
374 use crate::crypto::pq::{ml_dsa_generate_keypair, MlDsaSigningKey, MlDsaVerifyingKey};
375 use ed25519_dalek::{SigningKey, VerifyingKey};
376 use std::collections::HashMap;
377
378 // The UCAN payload-signature AAD is the public `super::UCAN_AAD` constant
379 // (promoted out of `test_support` by S8 so production verifiers share it).
380
381 /// A hybrid keypair (Ed25519 + ML-DSA-65) bound to one DID identity.
382 pub struct TestIdentity {
383 pub ed_sk: SigningKey,
384 pub ed_vk: VerifyingKey,
385 pub pq_sk: MlDsaSigningKey,
386 pub pq_vk: MlDsaVerifyingKey,
387 }
388
389 impl TestIdentity {
390 pub fn generate() -> Self {
391 use rand::rngs::OsRng;
392 let ed_sk = SigningKey::generate(&mut OsRng);
393 let ed_vk = ed_sk.verifying_key();
394 let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
395 Self {
396 ed_sk,
397 ed_vk,
398 pq_sk,
399 pq_vk,
400 }
401 }
402
403 pub fn did(&self) -> Did {
404 Did::from_ed25519(&self.ed_vk.to_bytes())
405 }
406 }
407
408 pub fn cap(resource: &str, ability: &str) -> Capability {
409 Capability::new(Resource::new(resource), Ability::new(ability))
410 }
411
412 /// Build and hybrid-sign a UCAN from `issuer` to `audience` with `caps` and
413 /// the given `proofs`.
414 pub fn signed_ucan(
415 issuer: &TestIdentity,
416 audience: &Did,
417 caps: Vec<Capability>,
418 proofs: Vec<Ucan>,
419 ) -> Ucan {
420 let payload = UcanPayload {
421 issuer: issuer.did(),
422 audience: audience.clone(),
423 capabilities: caps,
424 not_before: None,
425 expiration: Some(9_999_999_999),
426 nonce: vec![1, 2, 3],
427 };
428 let bytes = payload.signing_bytes().unwrap();
429 let signature =
430 sign_composite(&issuer.ed_sk, Some(&issuer.pq_sk), &bytes, UCAN_AAD).unwrap();
431 Ucan {
432 payload,
433 proofs,
434 signature,
435 }
436 }
437
438 /// A trust store keyed by DID string → anchored ML-DSA-65 verifying key,
439 /// implementing [`UcanVerifier`] over the real hybrid composite verify.
440 pub struct TestTrustStore {
441 pub pq_by_did: HashMap<String, MlDsaVerifyingKey>,
442 }
443
444 impl TestTrustStore {
445 pub fn new() -> Self {
446 Self {
447 pq_by_did: HashMap::new(),
448 }
449 }
450 pub fn anchor(&mut self, id: &TestIdentity) {
451 self.pq_by_did
452 .insert(id.did().into_string(), id.pq_vk.clone());
453 }
454 }
455
456 impl UcanVerifier for TestTrustStore {
457 fn verify(
458 &self,
459 issuer: &Did,
460 ed_key: &[u8; 32],
461 payload: &[u8],
462 signature: &[u8],
463 ) -> Result<(), UcanError> {
464 let ed_vk = VerifyingKey::from_bytes(ed_key)
465 .map_err(|e| UcanError::BadSignature(e.to_string()))?;
466 let pq_vk = self.pq_by_did.get(issuer.as_str());
467 verify_composite(signature, &ed_vk, pq_vk, payload, UCAN_AAD, true)
468 .map(|_| ())
469 .map_err(|e| UcanError::BadSignature(e.to_string()))
470 }
471 }
472}
473
474#[cfg(test)]
475#[allow(clippy::unwrap_used)]
476mod tests {
477 use super::test_support::*;
478 use super::*;
479
480 #[test]
481 fn cbor_roundtrip_preserves_ucan() {
482 let alice = TestIdentity::generate();
483 let bob = TestIdentity::generate();
484 let u = signed_ucan(
485 &alice,
486 &bob.did(),
487 vec![cap("mac://model/*", "infer")],
488 vec![],
489 );
490 let bytes = u.to_cbor().unwrap();
491 let back = Ucan::from_cbor(&bytes).unwrap();
492 assert_eq!(u, back);
493 }
494
495 #[test]
496 fn signing_bytes_are_deterministic() {
497 let alice = TestIdentity::generate();
498 let bob = TestIdentity::generate();
499 let u = signed_ucan(&alice, &bob.did(), vec![cap("mac://x", "y")], vec![]);
500 assert_eq!(
501 u.payload.signing_bytes().unwrap(),
502 u.payload.signing_bytes().unwrap()
503 );
504 }
505
506 #[test]
507 fn validate_structure_accepts_well_formed() {
508 let alice = TestIdentity::generate();
509 let bob = TestIdentity::generate();
510 let u = signed_ucan(&alice, &bob.did(), vec![cap("mac://x", "y")], vec![]);
511 assert!(u.validate_structure().is_ok());
512 }
513
514 #[test]
515 fn validate_structure_rejects_bad_did() {
516 let alice = TestIdentity::generate();
517 let mut u = signed_ucan(&alice, &alice.did(), vec![], vec![]);
518 u.payload.audience = Did::new("did:web:example.com".to_owned());
519 assert!(matches!(
520 u.validate_structure(),
521 Err(UcanError::BadDid { .. })
522 ));
523 }
524
525 #[test]
526 fn validate_structure_rejects_inverted_window() {
527 let alice = TestIdentity::generate();
528 let mut u = signed_ucan(&alice, &alice.did(), vec![], vec![]);
529 u.payload.not_before = Some(100);
530 u.payload.expiration = Some(50);
531 assert!(matches!(
532 u.validate_structure(),
533 Err(UcanError::Malformed(_))
534 ));
535 }
536
537 #[test]
538 fn is_valid_at_respects_window() {
539 let alice = TestIdentity::generate();
540 let mut u = signed_ucan(&alice, &alice.did(), vec![], vec![]);
541 u.payload.not_before = Some(100);
542 u.payload.expiration = Some(200);
543 assert!(!u.is_valid_at(99));
544 assert!(u.is_valid_at(100));
545 assert!(u.is_valid_at(200));
546 assert!(!u.is_valid_at(201));
547 }
548
549 #[test]
550 fn verify_signatures_accepts_valid_hybrid_signature() {
551 let alice = TestIdentity::generate();
552 let bob = TestIdentity::generate();
553 let u = signed_ucan(
554 &alice,
555 &bob.did(),
556 vec![cap("mac://model/*", "infer")],
557 vec![],
558 );
559
560 let mut store = TestTrustStore::new();
561 store.anchor(&alice);
562 assert!(u.verify_signatures(&store).is_ok());
563 }
564
565 #[test]
566 fn verify_signatures_rejects_missing_pq_anchor() {
567 // No anchored ML-DSA key → require_pq=true must fail closed.
568 let alice = TestIdentity::generate();
569 let bob = TestIdentity::generate();
570 let u = signed_ucan(&alice, &bob.did(), vec![cap("mac://x", "y")], vec![]);
571 let store = TestTrustStore::new(); // empty: no anchor
572 assert!(matches!(
573 u.verify_signatures(&store),
574 Err(UcanError::BadSignature(_))
575 ));
576 }
577
578 #[test]
579 fn root_walks_to_the_self_issued_delegator() {
580 // user (root) ⟶ gateway ⟶ mcp. The delegator (source of authority) is
581 // the root's issuer (user); the actor/presenter is the leaf audience (mcp).
582 let user = TestIdentity::generate();
583 let gateway = TestIdentity::generate();
584 let mcp = TestIdentity::generate();
585
586 let root = signed_ucan(
587 &user,
588 &gateway.did(),
589 vec![cap("mac://model/x", "infer")],
590 vec![],
591 );
592 let leaf = signed_ucan(
593 &gateway,
594 &mcp.did(),
595 vec![cap("mac://model/x", "infer")],
596 vec![root.clone()],
597 );
598
599 assert_eq!(
600 leaf.audience(),
601 &mcp.did(),
602 "leaf audience = actor/presenter"
603 );
604 assert_eq!(
605 leaf.issuer(),
606 &gateway.did(),
607 "leaf issuer = immediate (intermediate) issuer"
608 );
609 assert_eq!(
610 leaf.root_issuer(),
611 &user.did(),
612 "root_issuer = ultimate delegator, NOT the immediate issuer"
613 );
614 assert!(leaf.root().proofs.is_empty(), "root has empty proofs");
615 // A root UCAN is its own root.
616 assert_eq!(root.root_issuer(), &user.did());
617 }
618
619 #[test]
620 fn verify_signatures_rejects_tampered_payload() {
621 let alice = TestIdentity::generate();
622 let bob = TestIdentity::generate();
623 let mut u = signed_ucan(
624 &alice,
625 &bob.did(),
626 vec![cap("mac://model/qwen", "infer")],
627 vec![],
628 );
629 // Widen the capability AFTER signing — signature must no longer verify.
630 u.payload.capabilities = vec![cap("mac://*", "*")];
631 let mut store = TestTrustStore::new();
632 store.anchor(&alice);
633 assert!(matches!(
634 u.verify_signatures(&store),
635 Err(UcanError::BadSignature(_))
636 ));
637 }
638
639 #[test]
640 fn verify_signatures_recurses_into_proofs() {
641 // root → alice → bob; tamper the embedded root proof, expect rejection.
642 let root = TestIdentity::generate();
643 let alice = TestIdentity::generate();
644 let bob = TestIdentity::generate();
645 let root_ucan = signed_ucan(&root, &alice.did(), vec![cap("mac://*", "*")], vec![]);
646 let mut alice_ucan = signed_ucan(
647 &alice,
648 &bob.did(),
649 vec![cap("mac://model/qwen", "infer")],
650 vec![root_ucan],
651 );
652
653 let mut store = TestTrustStore::new();
654 store.anchor(&root);
655 store.anchor(&alice);
656 assert!(alice_ucan.verify_signatures(&store).is_ok());
657
658 // Corrupt the proof's signature.
659 alice_ucan.proofs[0].signature[0] ^= 0xFF;
660 assert!(matches!(
661 alice_ucan.verify_signatures(&store),
662 Err(UcanError::BadSignature(_))
663 ));
664 }
665}