hyprstream_rpc/auth/ucan/approval.rs
1//! The signed **`(UCAN, bundle_hash)` approval binding** (S5 / #571).
2//!
3//! This is the containment backstop of the whole compiler design (#547, design
4//! §14): an approved UCAN is cryptographically tied to the **hash of the bundle
5//! it compiles to**, so a compiler bug can never produce a bundle that exceeds
6//! what was reviewed. The reviewer approves a specific `(UCAN, lattice
7//! generation, bundle_hash)` triple; the policy loader (S4
8//! `compiled::PolicyLoader`) then accepts ONLY a compiled policy whose recomputed
9//! hash matches an approval for its generation.
10//!
11//! ## What this binds, and why those three things
12//!
13//! - **`ucan_cid`** — the content hash (BLAKE3 of canonical CBOR) of the
14//! approved UCAN. Ties the approval to the *exact* delegation that was
15//! reviewed; re-issuing or mutating the UCAN changes the CID.
16//! - **`generation`** — the [`LatticeVersion`] generation the bundle is valid
17//! for. Binding it prevents replaying an approval under a different lattice
18//! version whose compartment bits mean something else (the same desync guard
19//! S4 enforces; design §14 crypto/policy-agility).
20//! - **`bundle_hash`** — the `[u8; 32]` BLAKE3 hash of the compiled bundle. This
21//! is **exactly** the value S4's `CompiledPolicy::policy_hash()` produces and
22//! `compiled::PolicyApproval::approved_hash` consumes, so an
23//! [`ApprovalBinding`] minted here drops straight into the S4 loader once
24//! bundle emission (milestone 2) is wired.
25//!
26//! ## Signing: hybrid COSE, NEVER Ed25519-only
27//!
28//! The binding is signed with the project's hybrid post-quantum COSE composite
29//! (EdDSA + ML-DSA-65) via [`crate::crypto::cose_sign::sign_composite`] and
30//! verified with `require_pq = true`. A classical-only signature is rejected
31//! (fail-closed) — an approval is a long-lived authority artifact and is exactly
32//! the kind of confidentiality/integrity-critical object the hybrid-PQC plan
33//! requires to resist harvest-now-decrypt-later forgery.
34
35use crate::crypto::cose_sign::{sign_composite, verify_composite};
36use crate::crypto::pq::{MlDsaSigningKey, MlDsaVerifyingKey};
37use ed25519_dalek::{SigningKey, VerifyingKey};
38use serde::{Deserialize, Serialize};
39use std::fmt;
40
41use super::token::Ucan;
42
43/// Domain-separation AAD for approval-binding signatures. Distinct from the UCAN
44/// payload AAD (`hs-mac-ucan-payload-v1`), the compiled-policy AAD
45/// (`hs-mac-compiled-policy-v1`), and envelope AADs, so an approval signature can
46/// never be confused with — or replayed as — any other signed object.
47pub const APPROVAL_AAD: &[u8] = b"hs-mac-ucan-approval-v1";
48
49/// BLAKE3 content id of a UCAN: hash of its canonical CBOR encoding. The same
50/// codec the rest of the MAC stack uses, so the CID is stable across processes.
51pub fn ucan_cid(ucan: &Ucan) -> Result<[u8; 32], ApprovalError> {
52 let bytes = ucan
53 .to_cbor()
54 .map_err(|e| ApprovalError::Encode(e.to_string()))?;
55 Ok(*blake3::hash(&bytes).as_bytes())
56}
57
58/// The reviewed binding: the approved UCAN's CID, the lattice generation it is
59/// valid for, and the hash of the bundle it compiles to. These are the bytes the
60/// hybrid-COSE signature covers (see [`ApprovalBinding::signing_payload`]).
61///
62/// `bundle_hash` is intentionally a raw `[u8; 32]` — the exact type S4's
63/// `CompiledPolicy::policy_hash()` returns — so milestone-2 bundle emission feeds
64/// its output straight in with no conversion, and a verified binding yields an
65/// S4 `compiled::PolicyApproval { generation, approved_hash: bundle_hash }`.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct ApprovalBinding {
68 /// BLAKE3 CID of the approved UCAN ([`ucan_cid`]).
69 pub ucan_cid: [u8; 32],
70 /// The lattice/policy generation this bundle is valid for
71 /// ([`LatticeVersion::generation`]). Bound so the approval cannot be replayed
72 /// under a different compartment vocabulary.
73 pub generation: u64,
74 /// BLAKE3 hash of the compiled bundle (== S4 `CompiledPolicy::policy_hash()`).
75 pub bundle_hash: [u8; 32],
76}
77
78impl ApprovalBinding {
79 /// Construct a binding from an approved UCAN, the generation it targets, and
80 /// the hash of the bundle it compiled to.
81 pub fn new(ucan: &Ucan, generation: u64, bundle_hash: [u8; 32]) -> Result<Self, ApprovalError> {
82 Ok(Self {
83 ucan_cid: ucan_cid(ucan)?,
84 generation,
85 bundle_hash,
86 })
87 }
88
89 /// The exact, domain-separated bytes the signature covers:
90 /// `b"hs-mac-ucan-approval" || ucan_cid || generation_be || bundle_hash`.
91 /// Deterministic and length-prefixed by fixed field widths, so the layout is
92 /// unambiguous.
93 pub fn signing_payload(&self) -> Vec<u8> {
94 let mut v = Vec::with_capacity(19 + 32 + 8 + 32);
95 v.extend_from_slice(b"hs-mac-ucan-approval"); // intra-payload tag (belt-and-braces with AAD)
96 v.extend_from_slice(&self.ucan_cid);
97 v.extend_from_slice(&self.generation.to_be_bytes());
98 v.extend_from_slice(&self.bundle_hash);
99 v
100 }
101}
102
103/// A signed approval: the binding plus a detached hybrid-COSE composite
104/// signature over its [`ApprovalBinding::signing_payload`]. This is the artifact
105/// a reviewer/authority emits and the policy loader consumes.
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107pub struct SignedApproval {
108 /// The reviewed binding (re-derivable + re-hashable at the verifier).
109 pub binding: ApprovalBinding,
110 /// Detached hybrid-COSE composite signature (EdDSA + ML-DSA-65).
111 pub signature: Vec<u8>,
112}
113
114impl SignedApproval {
115 /// Sign an approval binding with the authority's HYBRID keypair. `pq_sk`
116 /// MUST be `Some` — an approval is never Ed25519-only (design §14). Passing
117 /// the classical key without a PQ key is rejected fail-closed so a misuse
118 /// can't silently downgrade the suite.
119 pub fn sign(
120 binding: ApprovalBinding,
121 ed_sk: &SigningKey,
122 pq_sk: &MlDsaSigningKey,
123 ) -> Result<Self, ApprovalError> {
124 let payload = binding.signing_payload();
125 let signature = sign_composite(ed_sk, Some(pq_sk), &payload, APPROVAL_AAD)
126 .map_err(|e| ApprovalError::Sign(e.to_string()))?;
127 Ok(Self { binding, signature })
128 }
129
130 /// Verify the approval under the HYBRID policy (`require_pq = true`): both the
131 /// EdDSA and the anchored ML-DSA-65 layers must verify against the authority's
132 /// keys, over the binding's signing payload. Fail-closed: a stripped PQ layer,
133 /// a wrong key, or a tampered binding all reject.
134 ///
135 /// On success returns the verified [`ApprovalBinding`] (so the caller does not
136 /// re-trust `self.binding` without having checked the signature).
137 pub fn verify(
138 &self,
139 ed_vk: &VerifyingKey,
140 pq_vk: &MlDsaVerifyingKey,
141 ) -> Result<&ApprovalBinding, ApprovalError> {
142 let payload = self.binding.signing_payload();
143 verify_composite(
144 &self.signature,
145 ed_vk,
146 Some(pq_vk),
147 &payload,
148 APPROVAL_AAD,
149 true,
150 )
151 .map_err(|e| ApprovalError::Verify(e.to_string()))?;
152 Ok(&self.binding)
153 }
154
155 /// Verify the approval AND confirm it binds the given UCAN, generation, and
156 /// bundle hash. This is the check the policy loader runs: it has the compiled
157 /// bundle's `(generation, bundle_hash)` and the approved UCAN in hand and must
158 /// confirm the signed approval covers exactly them. Fail-closed on any
159 /// mismatch.
160 pub fn verify_binds(
161 &self,
162 ed_vk: &VerifyingKey,
163 pq_vk: &MlDsaVerifyingKey,
164 ucan: &Ucan,
165 generation: u64,
166 bundle_hash: &[u8; 32],
167 ) -> Result<(), ApprovalError> {
168 let binding = self.verify(ed_vk, pq_vk)?;
169 let cid = ucan_cid(ucan)?;
170 if binding.ucan_cid != cid {
171 return Err(ApprovalError::UcanMismatch);
172 }
173 if binding.generation != generation {
174 return Err(ApprovalError::GenerationMismatch {
175 approved: binding.generation,
176 bundle: generation,
177 });
178 }
179 if &binding.bundle_hash != bundle_hash {
180 return Err(ApprovalError::BundleHashMismatch);
181 }
182 Ok(())
183 }
184}
185
186/// Errors from approval construction / signing / verification. All fail-closed.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub enum ApprovalError {
189 /// UCAN encode failure while computing the CID.
190 Encode(String),
191 /// Hybrid-COSE signing failed.
192 Sign(String),
193 /// Hybrid-COSE verification failed (bad signature, stripped PQ layer, etc.).
194 Verify(String),
195 /// The signed approval does not bind the presented UCAN.
196 UcanMismatch,
197 /// The approval's generation does not match the bundle's generation.
198 GenerationMismatch { approved: u64, bundle: u64 },
199 /// The approval's bundle hash does not match the presented bundle.
200 BundleHashMismatch,
201}
202
203impl fmt::Display for ApprovalError {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 match self {
206 ApprovalError::Encode(e) => write!(f, "approval UCAN encode failed: {e}"),
207 ApprovalError::Sign(e) => write!(f, "approval signing failed: {e}"),
208 ApprovalError::Verify(e) => write!(f, "approval verification failed: {e}"),
209 ApprovalError::UcanMismatch => {
210 write!(f, "signed approval does not bind the presented UCAN")
211 }
212 ApprovalError::GenerationMismatch { approved, bundle } => write!(
213 f,
214 "approval generation {approved} != bundle generation {bundle}"
215 ),
216 ApprovalError::BundleHashMismatch => {
217 write!(
218 f,
219 "approval bundle hash does not match the presented bundle"
220 )
221 }
222 }
223 }
224}
225
226impl std::error::Error for ApprovalError {}
227
228#[cfg(test)]
229#[allow(clippy::unwrap_used)]
230mod tests {
231 use super::super::token::test_support::*;
232 use super::*;
233
234 /// A fresh authority hybrid keypair + a sample approved UCAN.
235 fn setup() -> (TestIdentity, Ucan, u64, [u8; 32]) {
236 let authority = TestIdentity::generate();
237 let issuer = TestIdentity::generate();
238 let ucan = signed_ucan(
239 &issuer,
240 &issuer.did(),
241 vec![cap("mac://model/*", "infer")],
242 vec![],
243 );
244 let generation = 7u64;
245 // Stand-in bundle hash (milestone 2 supplies the real CompiledPolicy::policy_hash()).
246 let bundle_hash = *blake3::hash(b"compiled-bundle-bytes").as_bytes();
247 (authority, ucan, generation, bundle_hash)
248 }
249
250 #[test]
251 fn ucan_cid_is_stable_and_content_sensitive() {
252 let issuer = TestIdentity::generate();
253 let a = signed_ucan(&issuer, &issuer.did(), vec![cap("mac://x", "y")], vec![]);
254 assert_eq!(ucan_cid(&a).unwrap(), ucan_cid(&a).unwrap());
255 let b = signed_ucan(&issuer, &issuer.did(), vec![cap("mac://x", "z")], vec![]);
256 assert_ne!(ucan_cid(&a).unwrap(), ucan_cid(&b).unwrap());
257 }
258
259 #[test]
260 fn sign_then_verify_roundtrips() {
261 let (auth, ucan, generation, bundle_hash) = setup();
262 let binding = ApprovalBinding::new(&ucan, generation, bundle_hash).unwrap();
263 let signed = SignedApproval::sign(binding.clone(), &auth.ed_sk, &auth.pq_sk).unwrap();
264 let verified = signed.verify(&auth.ed_vk, &auth.pq_vk).unwrap();
265 assert_eq!(verified, &binding);
266 }
267
268 #[test]
269 fn verify_rejects_wrong_authority_key() {
270 let (auth, ucan, generation, bundle_hash) = setup();
271 let other = TestIdentity::generate();
272 let binding = ApprovalBinding::new(&ucan, generation, bundle_hash).unwrap();
273 let signed = SignedApproval::sign(binding, &auth.ed_sk, &auth.pq_sk).unwrap();
274 // Wrong PQ key.
275 assert!(matches!(
276 signed.verify(&auth.ed_vk, &other.pq_vk),
277 Err(ApprovalError::Verify(_))
278 ));
279 // Wrong Ed key.
280 assert!(matches!(
281 signed.verify(&other.ed_vk, &auth.pq_vk),
282 Err(ApprovalError::Verify(_))
283 ));
284 }
285
286 #[test]
287 fn verify_rejects_tampered_binding() {
288 let (auth, ucan, generation, bundle_hash) = setup();
289 let binding = ApprovalBinding::new(&ucan, generation, bundle_hash).unwrap();
290 let mut signed = SignedApproval::sign(binding, &auth.ed_sk, &auth.pq_sk).unwrap();
291 // Flip the bundle hash after signing.
292 signed.binding.bundle_hash[0] ^= 0xFF;
293 assert!(matches!(
294 signed.verify(&auth.ed_vk, &auth.pq_vk),
295 Err(ApprovalError::Verify(_))
296 ));
297 }
298
299 #[test]
300 fn verify_binds_confirms_exact_triple() {
301 let (auth, ucan, generation, bundle_hash) = setup();
302 let binding = ApprovalBinding::new(&ucan, generation, bundle_hash).unwrap();
303 let signed = SignedApproval::sign(binding, &auth.ed_sk, &auth.pq_sk).unwrap();
304
305 // Correct triple binds.
306 assert!(signed
307 .verify_binds(&auth.ed_vk, &auth.pq_vk, &ucan, generation, &bundle_hash)
308 .is_ok());
309
310 // Wrong generation.
311 assert!(matches!(
312 signed.verify_binds(
313 &auth.ed_vk,
314 &auth.pq_vk,
315 &ucan,
316 generation + 1,
317 &bundle_hash
318 ),
319 Err(ApprovalError::GenerationMismatch { .. })
320 ));
321
322 // Wrong bundle hash.
323 let wrong = *blake3::hash(b"different-bundle").as_bytes();
324 assert!(matches!(
325 signed.verify_binds(&auth.ed_vk, &auth.pq_vk, &ucan, generation, &wrong),
326 Err(ApprovalError::BundleHashMismatch)
327 ));
328
329 // Wrong UCAN.
330 let other_issuer = TestIdentity::generate();
331 let other_ucan = signed_ucan(
332 &other_issuer,
333 &other_issuer.did(),
334 vec![cap("mac://q", "r")],
335 vec![],
336 );
337 assert!(matches!(
338 signed.verify_binds(
339 &auth.ed_vk,
340 &auth.pq_vk,
341 &other_ucan,
342 generation,
343 &bundle_hash
344 ),
345 Err(ApprovalError::UcanMismatch)
346 ));
347 }
348
349 #[test]
350 fn signing_payload_binds_all_three_fields() {
351 // Distinct (cid, generation, bundle_hash) → distinct signing payloads.
352 let issuer = TestIdentity::generate();
353 let ucan = signed_ucan(&issuer, &issuer.did(), vec![cap("mac://x", "y")], vec![]);
354 let b1 = ApprovalBinding::new(&ucan, 1, [0u8; 32]).unwrap();
355 let mut b2 = b1.clone();
356 b2.generation = 2;
357 let mut b3 = b1.clone();
358 b3.bundle_hash = [9u8; 32];
359 assert_ne!(b1.signing_payload(), b2.signing_payload());
360 assert_ne!(b1.signing_payload(), b3.signing_payload());
361 }
362}