Skip to main content

hyprstream_crypto/
cose_sign1.rs

1//! COSE_Sign1 (RFC 9052) detached-payload signing for the hyprstream
2//! `SignedEnvelope`.
3//!
4//! Stage C of Phase 0.5 migrates envelope authentication from a bespoke
5//! `Ed25519.sign(serialize(envelope))` scheme to standards-based
6//! COSE_Sign1 with a detached payload and a domain-separating
7//! `external_aad`.
8//!
9//! # Wire shape
10//!
11//! Each `SignedEnvelope.signatures` entry is the CBOR encoding of a
12//! `COSE_Sign1` structure (see RFC 9052 §4.2). The signed payload is the
13//! Cap'n Proto-canonical bytes of the `RequestEnvelope`, *detached* — it
14//! is not embedded in the COSE structure itself. The signer's identity
15//! and algorithm are conveyed via the protected header (`kid`, `alg`).
16//!
17//! # external_aad
18//!
19//! To prevent schema-confusion (signing one schema's bytes and replaying
20//! them as another schema), `external_aad` is computed as the CBOR
21//! encoding of `[envelope_schema_id, inner_type_id]` — two Cap'n Proto
22//! file/type IDs as `u64`s. Sender and receiver must agree on these
23//! IDs; the verifier passes them in, and a mismatch causes verification
24//! to fail with `InvalidSignature`.
25
26use anyhow::{anyhow, bail, Context, Result};
27use coset::{
28    cbor::Value as CborValue,
29    iana::{self, EnumI64},
30    CborSerializable, CoseSign1, CoseSign1Builder, HeaderBuilder, Label,
31};
32
33/// Build the COSE `external_aad` for envelope signing.
34///
35/// Encoded as CBOR `[envelope_schema_id, inner_type_id]` — both `u64`.
36/// Receivers MUST pass the same values they expect to verify; otherwise
37/// signature verification fails.
38pub fn build_external_aad(envelope_schema_id: u64, inner_type_id: u64) -> Vec<u8> {
39    let value = CborValue::Array(vec![
40        CborValue::Integer(envelope_schema_id.into()),
41        CborValue::Integer(inner_type_id.into()),
42    ]);
43    let mut buf = Vec::with_capacity(24);
44    // CBOR encoding of a fixed two-integer array writes into an
45    // unbounded Vec; the writer is infallible for this shape, but we
46    // still drop any error rather than panic.
47    if ciborium::ser::into_writer(&value, &mut buf).is_err() {
48        return Vec::new();
49    }
50    buf
51}
52
53/// Trait abstracting over a signing key.
54///
55/// Implemented for `ed25519_dalek::SigningKey` below; ML-DSA-65 / PQ
56/// support can be added later by implementing this trait + extending
57/// `alg_for_signer`.
58pub trait CoseSigner {
59    /// IANA COSE algorithm identifier (e.g. `iana::Algorithm::EdDSA`).
60    fn alg(&self) -> iana::Algorithm;
61
62    /// Stable key identifier used for the COSE `kid` protected header.
63    ///
64    /// Convention: for Ed25519 signers this is the 32-byte raw verifying
65    /// key. Verifiers look the signer up by this `kid`.
66    fn kid(&self) -> Vec<u8>;
67
68    /// Sign arbitrary bytes (the COSE `Sig_structure` value).
69    fn sign(&self, msg: &[u8]) -> Vec<u8>;
70}
71
72/// Trait abstracting over a verifying key.
73pub trait CoseVerifier {
74    fn alg(&self) -> iana::Algorithm;
75    fn verify(&self, msg: &[u8], sig: &[u8]) -> Result<()>;
76}
77
78impl CoseSigner for ed25519_dalek::SigningKey {
79    fn alg(&self) -> iana::Algorithm {
80        iana::Algorithm::EdDSA
81    }
82    fn kid(&self) -> Vec<u8> {
83        self.verifying_key().to_bytes().to_vec()
84    }
85    fn sign(&self, msg: &[u8]) -> Vec<u8> {
86        use ed25519_dalek::Signer;
87        Signer::sign(self, msg).to_bytes().to_vec()
88    }
89}
90
91impl CoseVerifier for ed25519_dalek::VerifyingKey {
92    fn alg(&self) -> iana::Algorithm {
93        iana::Algorithm::EdDSA
94    }
95    fn verify(&self, msg: &[u8], sig: &[u8]) -> Result<()> {
96        if sig.len() != 64 {
97            bail!("Ed25519 signature must be 64 bytes, got {}", sig.len());
98        }
99        let mut arr = [0u8; 64];
100        arr.copy_from_slice(sig);
101        let signature = ed25519_dalek::Signature::from_bytes(&arr);
102        self.verify_strict(msg, &signature)
103            .map_err(|e| anyhow!("Ed25519 verification failed: {e}"))
104    }
105}
106
107/// Sign `payload` (detached) with `signing_key`, producing CBOR-encoded
108/// `COSE_Sign1` bytes.
109///
110/// The protected header contains the algorithm + `kid`. `external_aad`
111/// is folded into the `Sig_structure` per RFC 9052 §4.4 but is not
112/// transmitted in the COSE object — receivers must reconstruct it.
113pub fn sign_detached<S: CoseSigner>(
114    signing_key: &S,
115    payload: &[u8],
116    external_aad: &[u8],
117) -> Result<Vec<u8>> {
118    let protected = HeaderBuilder::new()
119        .algorithm(signing_key.alg())
120        .key_id(signing_key.kid())
121        .build();
122
123    let cose = CoseSign1Builder::new()
124        .protected(protected)
125        .create_detached_signature(payload, external_aad, |bytes| signing_key.sign(bytes))
126        .build();
127
128    cose.to_vec()
129        .map_err(|e| anyhow!("failed to serialize COSE_Sign1: {e}"))
130}
131
132/// Verify a CBOR-encoded `COSE_Sign1` against the detached `payload`
133/// and `external_aad`.
134///
135/// On success returns `(kid_b64, alg_label)` where `kid_b64` is the
136/// signer key id (base64url, no padding) and `alg_label` is the
137/// well-known short name (e.g. `"EdDSA"`). Returns `Err` for malformed
138/// COSE, alg mismatch, missing `kid`, or signature failure.
139pub fn verify_detached<V: CoseVerifier>(
140    cose_sign1_bytes: &[u8],
141    verifying_key: &V,
142    payload: &[u8],
143    external_aad: &[u8],
144) -> Result<(String, String)> {
145    let cose = CoseSign1::from_slice(cose_sign1_bytes)
146        .map_err(|e| anyhow!("malformed COSE_Sign1: {e}"))?;
147
148    // Extract alg from protected header
149    let alg = cose
150        .protected
151        .header
152        .alg
153        .as_ref()
154        .ok_or_else(|| anyhow!("COSE_Sign1 missing alg in protected header"))?;
155    let alg_int = match alg {
156        coset::Algorithm::Assigned(a) => a.to_i64(),
157        coset::Algorithm::PrivateUse(v) => *v,
158        coset::Algorithm::Text(s) => bail!("unsupported text algorithm: {s}"),
159    };
160    let expected_alg_int = verifying_key.alg().to_i64();
161    if alg_int != expected_alg_int {
162        bail!("COSE_Sign1 alg mismatch: header={alg_int} expected={expected_alg_int}");
163    }
164    let alg_label = format!("{:?}", verifying_key.alg());
165
166    // Extract kid from protected header
167    let kid_bytes = &cose.protected.header.key_id;
168    if kid_bytes.is_empty() {
169        bail!("COSE_Sign1 missing kid in protected header");
170    }
171    use base64::Engine;
172    let kid_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(kid_bytes);
173
174    // Verify detached signature
175    cose.verify_detached_signature(payload, external_aad, |sig, data| {
176        verifying_key.verify(data, sig)
177    })
178    .context("COSE_Sign1 detached signature verification failed")?;
179
180    Ok((kid_b64, alg_label))
181}
182
183/// Inspect a COSE_Sign1 without verifying it, returning `(kid_bytes, alg_int)`.
184///
185/// Used by receivers to dispatch a verifier from a key registry.
186pub fn peek_kid_alg(cose_sign1_bytes: &[u8]) -> Result<(Vec<u8>, i64)> {
187    let cose = CoseSign1::from_slice(cose_sign1_bytes)
188        .map_err(|e| anyhow!("malformed COSE_Sign1: {e}"))?;
189    let alg = cose
190        .protected
191        .header
192        .alg
193        .as_ref()
194        .ok_or_else(|| anyhow!("COSE_Sign1 missing alg"))?;
195    let alg_int = match alg {
196        coset::Algorithm::Assigned(a) => a.to_i64(),
197        coset::Algorithm::PrivateUse(v) => *v,
198        coset::Algorithm::Text(_) => bail!("text algorithms unsupported"),
199    };
200    let kid = cose.protected.header.key_id.clone();
201    if kid.is_empty() {
202        bail!("COSE_Sign1 missing kid");
203    }
204    Ok((kid, alg_int))
205}
206
207// Silence dead-code on the Label re-export until we exercise unprotected headers.
208#[allow(dead_code)]
209fn _label_marker(_: Label) {}
210
211// ────────────────────────────────────────────────────────────────────────────
212// Ed25519-specific concrete API for the envelope-signing call sites.
213//
214// `envelope.rs` was wired to a concrete-typed API (parse/sign_ed25519_detached/
215// verify_ed25519_detached) before this module's generic trait-based API
216// existed. The wrappers below preserve that call-site shape so the envelope
217// migration can land without churning unrelated code.
218// ────────────────────────────────────────────────────────────────────────────
219
220/// Parsed COSE_Sign1 with kid + alg extracted from the protected header.
221pub struct ParsedCoseSign1 {
222    /// The decoded COSE_Sign1 structure (signature bytes accessible via `.signature`).
223    pub sign1: CoseSign1,
224    /// Signer key id from the protected header.
225    pub kid: Vec<u8>,
226    /// IANA COSE algorithm integer (e.g. `-8` for EdDSA).
227    pub alg: i64,
228}
229
230/// Parse a CBOR-encoded COSE_Sign1 blob. Does not verify the signature.
231pub fn parse(blob: &[u8]) -> Result<ParsedCoseSign1> {
232    let sign1 = CoseSign1::from_slice(blob).map_err(|e| anyhow!("malformed COSE_Sign1: {e}"))?;
233    let alg = sign1
234        .protected
235        .header
236        .alg
237        .as_ref()
238        .ok_or_else(|| anyhow!("COSE_Sign1 missing alg"))?;
239    let alg_int = match alg {
240        coset::Algorithm::Assigned(a) => a.to_i64(),
241        coset::Algorithm::PrivateUse(v) => *v,
242        coset::Algorithm::Text(_) => bail!("text algorithms unsupported"),
243    };
244    let kid = sign1.protected.header.key_id.clone();
245    if kid.is_empty() {
246        bail!("COSE_Sign1 missing kid");
247    }
248    Ok(ParsedCoseSign1 {
249        sign1,
250        kid,
251        alg: alg_int,
252    })
253}
254
255/// Concrete Ed25519 detached-signature wrapper for envelope.rs.
256///
257/// Builds the `external_aad` from `(envelope_schema_id, inner_type_id)` and
258/// produces a CBOR-encoded COSE_Sign1 over `payload`.
259pub fn sign_ed25519_detached(
260    signing_key: &ed25519_dalek::SigningKey,
261    envelope_schema_id: u64,
262    inner_type_id: u64,
263    payload: &[u8],
264) -> Result<Vec<u8>> {
265    let aad = build_external_aad(envelope_schema_id, inner_type_id);
266    sign_detached(signing_key, payload, &aad)
267}
268
269/// Concrete Ed25519 verification wrapper. Reconstructs `external_aad` from
270/// the given schema/inner IDs and verifies the parsed COSE_Sign1's detached
271/// signature against `pubkey` + `payload`.
272pub fn verify_ed25519_detached(
273    parsed: &ParsedCoseSign1,
274    pubkey: &ed25519_dalek::VerifyingKey,
275    envelope_schema_id: u64,
276    inner_type_id: u64,
277    payload: &[u8],
278) -> Result<()> {
279    // Confirm the parsed alg matches EdDSA before doing the signature check.
280    let expected = iana::Algorithm::EdDSA.to_i64();
281    if parsed.alg != expected {
282        bail!(
283            "COSE_Sign1 alg mismatch: parsed={} expected EdDSA={}",
284            parsed.alg,
285            expected
286        );
287    }
288    let aad = build_external_aad(envelope_schema_id, inner_type_id);
289    parsed
290        .sign1
291        .verify_detached_signature(payload, &aad, |sig, data| {
292            <ed25519_dalek::VerifyingKey as CoseVerifier>::verify(pubkey, data, sig)
293        })
294        .context("COSE_Sign1 Ed25519 detached verification failed")
295}
296
297#[cfg(test)]
298#[allow(clippy::unwrap_used, clippy::expect_used)]
299mod tests {
300    use super::*;
301    use ed25519_dalek::SigningKey;
302    use rand::rngs::OsRng;
303
304    const SCHEMA_ID: u64 = 0xcf5e_016c_5d4a_af92;
305    const INNER_TYPE_ID: u64 = 0xdead_beef_cafe_babe;
306
307    fn fresh_key() -> SigningKey {
308        SigningKey::generate(&mut OsRng)
309    }
310
311    #[test]
312    fn external_aad_is_deterministic_cbor_array() {
313        let a = build_external_aad(SCHEMA_ID, INNER_TYPE_ID);
314        let b = build_external_aad(SCHEMA_ID, INNER_TYPE_ID);
315        assert_eq!(a, b, "external_aad must be deterministic");
316        // CBOR array(2) header is 0x82
317        assert_eq!(a[0], 0x82, "must encode as CBOR array of length 2");
318    }
319
320    #[test]
321    fn external_aad_distinguishes_inner_type() {
322        let a = build_external_aad(SCHEMA_ID, INNER_TYPE_ID);
323        let b = build_external_aad(SCHEMA_ID, INNER_TYPE_ID ^ 1);
324        assert_ne!(a, b);
325    }
326
327    #[test]
328    fn sign_verify_roundtrip() {
329        let sk = fresh_key();
330        let vk = sk.verifying_key();
331        let payload = b"hello cose";
332        let aad = build_external_aad(SCHEMA_ID, INNER_TYPE_ID);
333
334        let cose_bytes = sign_detached(&sk, payload, &aad).expect("sign");
335        let (kid, alg) = verify_detached(&cose_bytes, &vk, payload, &aad).expect("verify");
336
337        assert_eq!(alg, "EdDSA");
338        // kid is base64url(no-pad) of the raw 32-byte verifying key
339        use base64::Engine;
340        let expected_kid = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(vk.to_bytes());
341        assert_eq!(kid, expected_kid);
342    }
343
344    #[test]
345    fn tampered_payload_rejected() {
346        let sk = fresh_key();
347        let vk = sk.verifying_key();
348        let payload = b"original payload";
349        let aad = build_external_aad(SCHEMA_ID, INNER_TYPE_ID);
350
351        let cose_bytes = sign_detached(&sk, payload, &aad).expect("sign");
352        let tampered = b"tampered payload";
353        let err = verify_detached(&cose_bytes, &vk, tampered, &aad);
354        assert!(err.is_err(), "tampered payload must fail verification");
355    }
356
357    #[test]
358    fn tampered_external_aad_rejected() {
359        let sk = fresh_key();
360        let vk = sk.verifying_key();
361        let payload = b"payload";
362        let aad = build_external_aad(SCHEMA_ID, INNER_TYPE_ID);
363        let cose_bytes = sign_detached(&sk, payload, &aad).expect("sign");
364
365        let wrong_aad = build_external_aad(SCHEMA_ID, INNER_TYPE_ID ^ 1);
366        let err = verify_detached(&cose_bytes, &vk, payload, &wrong_aad);
367        assert!(err.is_err(), "schema-confusion (wrong aad) must fail");
368    }
369
370    #[test]
371    fn wrong_key_rejected() {
372        let sk = fresh_key();
373        let other = fresh_key().verifying_key();
374        let payload = b"payload";
375        let aad = build_external_aad(SCHEMA_ID, INNER_TYPE_ID);
376
377        let cose_bytes = sign_detached(&sk, payload, &aad).expect("sign");
378        let err = verify_detached(&cose_bytes, &other, payload, &aad);
379        assert!(err.is_err(), "wrong verifying key must fail");
380    }
381
382    #[test]
383    fn peek_kid_alg_works() {
384        let sk = fresh_key();
385        let aad = build_external_aad(SCHEMA_ID, INNER_TYPE_ID);
386        let cose_bytes = sign_detached(&sk, b"x", &aad).expect("sign");
387        let (kid, alg_int) = peek_kid_alg(&cose_bytes).expect("peek");
388        assert_eq!(kid, sk.verifying_key().to_bytes().to_vec());
389        assert_eq!(alg_int, iana::Algorithm::EdDSA.to_i64());
390    }
391}