Skip to main content

hyprstream_rpc/crypto/
cose_encrypt.rs

1//! Canonical COSE_Encrypt0 sealing over Hyprstream's pinned hybrid-KEM suite.
2//!
3//! This module implements the reusable confidentiality substrate for #553.  The
4//! outer object and its authenticated-data construction are COSE_Encrypt0 from
5//! RFC 9052, and the content algorithm is the registered ChaCha20/Poly1305 COSE
6//! algorithm (24).  Key establishment is Hyprstream's suite-identified N-KEM
7//! combiner in [`crate::crypto::hybrid_kem`].
8//!
9//! This is deliberately **not** called HPKE or COSE-HPKE.  Hyprstream's N-KEM
10//! combiner is not an HPKE ciphersuite, and its composite encapsulation material
11//! is not the `enc` / `ek` value defined by `draft-ietf-cose-hpke`.  The private
12//! labels below define a project-local profile and make no draft-interoperability
13//! claim.  PQUIP / RFC 9794 supplies transition terminology, not wire semantics.
14//!
15//! New consumers should use [`seal`] and [`seal_prederived`] with an owning
16//! [`OutboundNonceLedger`], and [`open`] and [`open_prederived`] with an owning
17//! [`InboundReplayLedger`].  The fresh-encapsulation envelope wrappers at the
18//! bottom remain only for the already-landed signed envelope path, whose replay
19//! lifecycle is owned by `SignedEnvelope`.
20
21use std::collections::HashSet;
22
23use anyhow::{bail, Context, Result};
24use chacha20poly1305::aead::{Aead, KeyInit, Payload};
25use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
26use coset::cbor::value::Value as CborValue;
27use coset::{
28    iana::{self, EnumI64},
29    CborSerializable, CoseEncrypt0, CoseEncrypt0Builder, Header, HeaderBuilder, Label,
30    RegisteredLabelWithPrivate,
31};
32use hkdf::Hkdf;
33use sha2::{Digest, Sha256};
34use zeroize::Zeroizing;
35
36use crate::crypto::hybrid_kem::{
37    self, HybridKemMaterial, RecipientKeypair, RecipientPublic, SuiteId,
38};
39
40/// Maximum plaintext accepted by this substrate (16 MiB).
41pub const MAX_PLAINTEXT_BYTES: usize = 16 * 1024 * 1024;
42/// Maximum caller-supplied external AAD / transcript bytes (64 KiB).
43pub const MAX_EXTERNAL_AAD_BYTES: usize = 64 * 1024;
44/// Maximum canonical COSE object accepted before parsing or KEM work.
45pub const MAX_COSE_BYTES: usize = MAX_PLAINTEXT_BYTES + 16 * 1024;
46/// Maximum recipient or key identifier length.
47pub const MAX_IDENTIFIER_BYTES: usize = 256;
48/// Maximum number of nonce/replay entries retained by one ledger.
49pub const MAX_LEDGER_ENTRIES: usize = 1_048_576;
50
51const ALG_CHACHA20POLY1305: i64 = iana::Algorithm::ChaCha20Poly1305 as i64;
52
53// Project-local private-use labels.  They intentionally do not reuse the
54// provisional `ek` label or algorithm assignments from draft-ietf-cose-hpke.
55const HDR_SUITE_ID: i64 = -65538;
56const HDR_KEM_MATERIAL: i64 = -65539;
57const HDR_RECIPIENT_ID: i64 = -65540;
58const HDR_NONCE_DOMAIN: i64 = -65541;
59const HDR_EPOCH: i64 = -65542;
60const HDR_SEQUENCE: i64 = -65543;
61
62const KDF_KEY_LABEL: &[u8] = b"hyprstream cose-encrypt0 base key v2";
63const KDF_CONTEXT_LABEL: &[u8] = b"hyprstream cose-encrypt0 context key v2";
64const COMPAT_RECIPIENT_LABEL: &[u8] = b"hyprstream cose-encrypt0 compat recipient v2";
65const COMPAT_KEY_LABEL: &[u8] = b"hyprstream cose-encrypt0 compat key v2";
66const COMPAT_DOMAIN_LABEL: &[u8] = b"hyprstream cose-encrypt0 compat domain v2";
67
68// These structural limits are deliberately much tighter than the 16 MiB wire
69// cap.  This profile has a three-item outer array, at most eight protected
70// headers, one unprotected header, and a five-item `crit` array.  The modest
71// headroom permits future private headers without allowing a small input to
72// amplify into a large generic `ciborium::Value` tree before schema validation.
73const MAX_CBOR_DEPTH: usize = 8;
74const MAX_CBOR_CONTAINER_ITEMS: usize = 32;
75const MAX_CBOR_TOTAL_ITEMS: usize = 64;
76const MAX_PROTECTED_HEADER_BYTES: usize = 4 * 1024;
77const MAX_HEADER_VALUE_BYTES: usize = 4 * 1024;
78const MAX_HEADER_TEXT_BYTES: usize = MAX_IDENTIFIER_BYTES;
79
80/// Authenticated identity and nonce coordinates for one sealed object.
81///
82/// `nonce_domain` is a lifecycle-generated, collision-resistant identifier for
83/// one direction/track/key domain.  The owner must not reuse it when restarting
84/// a lifecycle with the same key.  Epoch installation and retirement policy is
85/// intentionally outside #553 and belongs to #554/#555.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub struct SealContext {
88    /// Canonical recipient identity (for example, an accepted service DID).
89    pub recipient_id: Vec<u8>,
90    /// Selected recipient key identifier.
91    pub key_id: Vec<u8>,
92    /// Collision-resistant lifecycle/direction/track nonce domain.
93    pub nonce_domain: [u8; 32],
94    /// Installed epoch.  It is encoded as a u32 in the 96-bit nonce.
95    pub epoch: u32,
96    /// Monotonic sequence within the epoch.
97    pub sequence: u64,
98}
99
100impl SealContext {
101    fn validate(&self) -> Result<()> {
102        validate_identifier("recipient id", &self.recipient_id)?;
103        validate_identifier("key id", &self.key_id)?;
104        if self.nonce_domain == [0; 32] {
105            bail!("nonce domain must not be all zero");
106        }
107        Ok(())
108    }
109}
110
111#[derive(Clone, Debug, Hash, PartialEq, Eq)]
112struct NonceUse {
113    suite: u16,
114    recipient_id: Vec<u8>,
115    key_id: Vec<u8>,
116    nonce_domain: [u8; 32],
117    epoch: u32,
118    sequence: u64,
119}
120
121impl NonceUse {
122    fn new(suite: SuiteId, context: &SealContext) -> Self {
123        Self {
124            suite: suite.as_u16(),
125            recipient_id: context.recipient_id.clone(),
126            key_id: context.key_id.clone(),
127            nonce_domain: context.nonce_domain,
128            epoch: context.epoch,
129            sequence: context.sequence,
130        }
131    }
132}
133
134/// Irreversible bounded state for outbound nonce use.
135///
136/// One ledger owns the complete lifetime of the base key supplied to `seal*`.
137/// It may be dropped only after that base key has been irreversibly destroyed or
138/// rotated out; constructing a replacement ledger while retaining the key would
139/// discard its nonce-safety history.  Burns are never evicted or retired, and
140/// capacity exhaustion therefore requires base-key rotation.  A coordinate is
141/// burned before cryptographic work, so even an error cannot make an uncertain
142/// nonce reusable.
143#[derive(Debug)]
144pub struct OutboundNonceLedger {
145    capacity: usize,
146    seen: HashSet<NonceUse>,
147}
148
149impl OutboundNonceLedger {
150    /// Construct outbound state with a finite non-zero lifetime capacity.
151    pub fn new(capacity: usize) -> Result<Self> {
152        if capacity == 0 || capacity > MAX_LEDGER_ENTRIES {
153            bail!("outbound nonce ledger capacity must be in 1..={MAX_LEDGER_ENTRIES}");
154        }
155        Ok(Self {
156            capacity,
157            seen: HashSet::with_capacity(capacity.min(4096)),
158        })
159    }
160
161    /// Number of irreversibly burned nonce coordinates.
162    pub fn len(&self) -> usize {
163        self.seen.len()
164    }
165
166    /// Whether no coordinates have been burned.
167    pub fn is_empty(&self) -> bool {
168        self.seen.is_empty()
169    }
170
171    fn ensure_unseen(&self, usage: &NonceUse) -> Result<()> {
172        if self.seen.contains(usage) {
173            bail!("nonce coordinate already used or ciphertext replayed");
174        }
175        Ok(())
176    }
177
178    fn record(&mut self, usage: NonceUse) -> Result<()> {
179        self.ensure_unseen(&usage)?;
180        if self.seen.len() >= self.capacity {
181            bail!("outbound nonce ledger capacity exhausted; destroy and rotate the base key");
182        }
183        self.seen.insert(usage);
184        Ok(())
185    }
186}
187
188/// Bounded state for authenticated inbound replay rejection.
189///
190/// Unlike outbound burns, replay entries may be retired after the public
191/// lifecycle owner has made the corresponding epoch unacceptable before
192/// calling `open*`.  Retirement does not and cannot affect outbound state.
193#[derive(Debug)]
194pub struct InboundReplayLedger {
195    capacity: usize,
196    seen: HashSet<NonceUse>,
197}
198
199impl InboundReplayLedger {
200    /// Construct inbound replay state with a finite non-zero capacity.
201    pub fn new(capacity: usize) -> Result<Self> {
202        if capacity == 0 || capacity > MAX_LEDGER_ENTRIES {
203            bail!("inbound replay ledger capacity must be in 1..={MAX_LEDGER_ENTRIES}");
204        }
205        Ok(Self {
206            capacity,
207            seen: HashSet::with_capacity(capacity.min(4096)),
208        })
209    }
210
211    /// Number of retained authenticated replay coordinates.
212    pub fn len(&self) -> usize {
213        self.seen.len()
214    }
215
216    /// Whether no replay coordinates are retained.
217    pub fn is_empty(&self) -> bool {
218        self.seen.is_empty()
219    }
220
221    /// Retire an inbound epoch after the owner has made it unacceptable.
222    ///
223    /// This is replay-retention management only; epoch install, accept, grace,
224    /// and retirement policy remain with #554/#555.
225    pub fn retire_epoch(
226        &mut self,
227        suite: SuiteId,
228        recipient_id: &[u8],
229        key_id: &[u8],
230        nonce_domain: &[u8; 32],
231        epoch: u32,
232    ) {
233        self.seen.retain(|entry| {
234            !(entry.suite == suite.as_u16()
235                && entry.recipient_id == recipient_id
236                && entry.key_id == key_id
237                && &entry.nonce_domain == nonce_domain
238                && entry.epoch == epoch)
239        });
240    }
241
242    fn ensure_unseen(&self, usage: &NonceUse) -> Result<()> {
243        if self.seen.contains(usage) {
244            bail!("ciphertext replayed");
245        }
246        Ok(())
247    }
248
249    fn record(&mut self, usage: NonceUse) -> Result<()> {
250        self.ensure_unseen(&usage)?;
251        if self.seen.len() >= self.capacity {
252            bail!("inbound replay ledger capacity exhausted; retire an unacceptable epoch");
253        }
254        self.seen.insert(usage);
255        Ok(())
256    }
257}
258
259/// Derive a separated base content key from a hybrid combiner secret.
260pub fn derive_aead_key(hybrid_secret: &[u8; 32]) -> Zeroizing<[u8; 32]> {
261    let hk = Hkdf::<Sha256>::new(None, hybrid_secret);
262    let mut key = [0u8; 32];
263    // SHA-256's HKDF output limit is far above 32 bytes.
264    if hk.expand(KDF_KEY_LABEL, &mut key).is_err() {
265        unreachable!("HKDF-SHA256 cannot reject a 32-byte output");
266    }
267    Zeroizing::new(key)
268}
269
270fn validate_identifier(name: &str, value: &[u8]) -> Result<()> {
271    if value.is_empty() || value.len() > MAX_IDENTIFIER_BYTES {
272        bail!("{name} length must be in 1..={MAX_IDENTIFIER_BYTES}");
273    }
274    Ok(())
275}
276
277fn validate_inputs(context: &SealContext, plaintext_len: usize, external_aad: &[u8]) -> Result<()> {
278    context.validate()?;
279    if plaintext_len > MAX_PLAINTEXT_BYTES {
280        bail!("plaintext exceeds {MAX_PLAINTEXT_BYTES}-byte limit");
281    }
282    if external_aad.len() > MAX_EXTERNAL_AAD_BYTES {
283        bail!("external AAD exceeds {MAX_EXTERNAL_AAD_BYTES}-byte limit");
284    }
285    Ok(())
286}
287
288fn derive_context_key(
289    base_key: &[u8; 32],
290    suite: SuiteId,
291    context: &SealContext,
292) -> Result<Zeroizing<[u8; 32]>> {
293    context.validate()?;
294    let mut info = Vec::with_capacity(
295        KDF_CONTEXT_LABEL.len() + context.recipient_id.len() + context.key_id.len() + 80,
296    );
297    append_lp(&mut info, KDF_CONTEXT_LABEL)?;
298    info.extend_from_slice(&suite.as_u16().to_be_bytes());
299    append_lp(&mut info, &context.recipient_id)?;
300    append_lp(&mut info, &context.key_id)?;
301    info.extend_from_slice(&context.nonce_domain);
302    info.extend_from_slice(&context.epoch.to_be_bytes());
303
304    let hk =
305        Hkdf::<Sha256>::from_prk(base_key).map_err(|_| anyhow::anyhow!("invalid HKDF base key"))?;
306    let mut key = [0u8; 32];
307    hk.expand(&info, &mut key)
308        .map_err(|_| anyhow::anyhow!("COSE context KDF info too long"))?;
309    Ok(Zeroizing::new(key))
310}
311
312fn append_lp(out: &mut Vec<u8>, value: &[u8]) -> Result<()> {
313    let len = u32::try_from(value.len()).context("context field too long")?;
314    out.extend_from_slice(&len.to_be_bytes());
315    out.extend_from_slice(value);
316    Ok(())
317}
318
319fn derive_nonce(context: &SealContext) -> [u8; 12] {
320    let mut nonce = [0u8; 12];
321    nonce[..4].copy_from_slice(&context.epoch.to_be_bytes());
322    nonce[4..].copy_from_slice(&context.sequence.to_be_bytes());
323    nonce
324}
325
326fn aead_seal(key: &[u8; 32], nonce: &[u8; 12], plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
327    ChaCha20Poly1305::new(Key::from_slice(key))
328        .encrypt(
329            Nonce::from_slice(nonce),
330            Payload {
331                msg: plaintext,
332                aad,
333            },
334        )
335        .map_err(|_| anyhow::anyhow!("ChaCha20Poly1305 encrypt failed"))
336}
337
338fn aead_open(key: &[u8; 32], nonce: &[u8; 12], ciphertext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
339    ChaCha20Poly1305::new(Key::from_slice(key))
340        .decrypt(
341            Nonce::from_slice(nonce),
342            Payload {
343                msg: ciphertext,
344                aad,
345            },
346        )
347        .map_err(|_| anyhow::anyhow!("ChaCha20Poly1305 decrypt/auth failed"))
348}
349
350fn private_label(value: i64) -> RegisteredLabelWithPrivate<iana::HeaderParameter> {
351    RegisteredLabelWithPrivate::PrivateUse(value)
352}
353
354fn critical_headers() -> Vec<RegisteredLabelWithPrivate<iana::HeaderParameter>> {
355    vec![
356        private_label(HDR_SUITE_ID),
357        private_label(HDR_RECIPIENT_ID),
358        private_label(HDR_NONCE_DOMAIN),
359        private_label(HDR_EPOCH),
360        private_label(HDR_SEQUENCE),
361    ]
362}
363
364fn build_protected(suite: SuiteId, context: &SealContext) -> Header {
365    HeaderBuilder::new()
366        .algorithm(iana::Algorithm::ChaCha20Poly1305)
367        .key_id(context.key_id.clone())
368        .add_critical_label(private_label(HDR_SUITE_ID))
369        .add_critical_label(private_label(HDR_RECIPIENT_ID))
370        .add_critical_label(private_label(HDR_NONCE_DOMAIN))
371        .add_critical_label(private_label(HDR_EPOCH))
372        .add_critical_label(private_label(HDR_SEQUENCE))
373        .value(HDR_SUITE_ID, CborValue::Integer(suite.as_u16().into()))
374        .value(
375            HDR_RECIPIENT_ID,
376            CborValue::Bytes(context.recipient_id.clone()),
377        )
378        .value(
379            HDR_NONCE_DOMAIN,
380            CborValue::Bytes(context.nonce_domain.to_vec()),
381        )
382        .value(HDR_EPOCH, CborValue::Integer(context.epoch.into()))
383        .value(HDR_SEQUENCE, CborValue::Integer(context.sequence.into()))
384        .build()
385}
386
387fn empty_except_rest(header: &Header) -> bool {
388    header.alg.is_none()
389        && header.crit.is_empty()
390        && header.content_type.is_none()
391        && header.key_id.is_empty()
392        && header.iv.is_empty()
393        && header.partial_iv.is_empty()
394        && header.counter_signatures.is_empty()
395}
396
397fn require_exact_protected(
398    enc: &CoseEncrypt0,
399    expected_suite: SuiteId,
400    expected: &SealContext,
401) -> Result<()> {
402    let header = &enc.protected.header;
403    match header.alg.as_ref() {
404        Some(coset::Algorithm::Assigned(a)) if a.to_i64() == ALG_CHACHA20POLY1305 => {}
405        Some(coset::Algorithm::Assigned(a)) => {
406            bail!(
407                "COSE_Encrypt0 algorithm {} is not ChaCha20Poly1305 (24)",
408                a.to_i64()
409            )
410        }
411        Some(coset::Algorithm::PrivateUse(value)) => {
412            bail!("private-use COSE algorithm {value} is not accepted")
413        }
414        Some(coset::Algorithm::Text(value)) => bail!("text COSE algorithm {value} is unsupported"),
415        None => bail!("COSE_Encrypt0 missing protected algorithm"),
416    }
417    if header.crit != critical_headers() {
418        bail!("COSE_Encrypt0 critical-header set/order is not canonical");
419    }
420    if header.key_id != expected.key_id {
421        bail!("COSE_Encrypt0 recipient key id mismatch");
422    }
423    if header.content_type.is_some()
424        || !header.iv.is_empty()
425        || !header.partial_iv.is_empty()
426        || !header.counter_signatures.is_empty()
427    {
428        bail!("COSE_Encrypt0 contains unsupported protected headers");
429    }
430    if header.rest.len() != 5 {
431        bail!("COSE_Encrypt0 protected private-header set is not exact");
432    }
433
434    require_int(
435        header,
436        HDR_SUITE_ID,
437        i128::from(expected_suite.as_u16()),
438        "suite",
439    )?;
440    require_bytes(
441        header,
442        HDR_RECIPIENT_ID,
443        &expected.recipient_id,
444        "recipient id",
445    )?;
446    require_bytes(
447        header,
448        HDR_NONCE_DOMAIN,
449        &expected.nonce_domain,
450        "nonce domain",
451    )?;
452    require_int(header, HDR_EPOCH, i128::from(expected.epoch), "epoch")?;
453    require_int(
454        header,
455        HDR_SEQUENCE,
456        i128::from(expected.sequence),
457        "sequence",
458    )?;
459    Ok(())
460}
461
462fn require_int(header: &Header, label: i64, expected: i128, name: &str) -> Result<()> {
463    match unique_header_value(header, label)? {
464        CborValue::Integer(value) if i128::from(*value) == expected => Ok(()),
465        CborValue::Integer(value) => {
466            let actual = i128::from(*value);
467            bail!("COSE_Encrypt0 {name} mismatch: {actual} != {expected}")
468        }
469        _ => bail!("COSE_Encrypt0 {name} header has wrong type"),
470    }
471}
472
473fn require_bytes(header: &Header, label: i64, expected: &[u8], name: &str) -> Result<()> {
474    match unique_header_value(header, label)? {
475        CborValue::Bytes(value) if value == expected => Ok(()),
476        CborValue::Bytes(_) => bail!("COSE_Encrypt0 {name} mismatch"),
477        _ => bail!("COSE_Encrypt0 {name} header has wrong type"),
478    }
479}
480
481fn unique_header_value(header: &Header, label: i64) -> Result<&CborValue> {
482    let mut values = header.rest.iter().filter_map(|(candidate, value)| {
483        if candidate == &Label::Int(label) {
484            Some(value)
485        } else {
486            None
487        }
488    });
489    let value = values
490        .next()
491        .ok_or_else(|| anyhow::anyhow!("COSE_Encrypt0 missing private header {label}"))?;
492    if values.next().is_some() {
493        bail!("COSE_Encrypt0 duplicate private header {label}");
494    }
495    Ok(value)
496}
497
498fn require_material(enc: &CoseEncrypt0) -> Result<HybridKemMaterial> {
499    if !empty_except_rest(&enc.unprotected) || enc.unprotected.rest.len() != 1 {
500        bail!("COSE_Encrypt0 unprotected header set is not exact");
501    }
502    match unique_header_value(&enc.unprotected, HDR_KEM_MATERIAL)? {
503        CborValue::Bytes(value) => HybridKemMaterial::decode(value),
504        _ => bail!("COSE_Encrypt0 hybrid-KEM material has wrong type"),
505    }
506}
507
508fn require_no_unprotected(enc: &CoseEncrypt0) -> Result<()> {
509    if !enc.unprotected.is_empty() {
510        bail!("pre-derived-key COSE_Encrypt0 must have no unprotected headers");
511    }
512    Ok(())
513}
514
515/// Allocation-free structural validation of the small CBOR subset used by the
516/// COSE profile.  In addition to bounding work, this independently enforces RFC
517/// 8949 core deterministic argument encodings and map-key order (encoded-key
518/// bytes compared lexicographically).  It intentionally performs no COSE
519/// semantics; `coset` remains the sole semantic decoder below.
520struct CborPreflight<'a> {
521    input: &'a [u8],
522    offset: usize,
523    items: usize,
524    max_byte_string: usize,
525}
526
527impl<'a> CborPreflight<'a> {
528    fn new(input: &'a [u8], max_byte_string: usize) -> Self {
529        Self {
530            input,
531            offset: 0,
532            items: 0,
533            max_byte_string,
534        }
535    }
536
537    fn finish(self) -> Result<()> {
538        if self.offset != self.input.len() {
539            bail!("CBOR contains trailing data");
540        }
541        Ok(())
542    }
543
544    fn read_byte(&mut self) -> Result<u8> {
545        let byte = *self.input.get(self.offset).context("truncated CBOR item")?;
546        self.offset += 1;
547        Ok(byte)
548    }
549
550    fn read_exact<const N: usize>(&mut self) -> Result<[u8; N]> {
551        let end = self.offset.checked_add(N).context("CBOR length overflow")?;
552        let bytes = self
553            .input
554            .get(self.offset..end)
555            .context("truncated CBOR argument")?;
556        self.offset = end;
557        bytes.try_into().context("invalid CBOR argument width")
558    }
559
560    fn head(&mut self) -> Result<(u8, u64)> {
561        self.items = self.items.checked_add(1).context("CBOR item overflow")?;
562        if self.items > MAX_CBOR_TOTAL_ITEMS {
563            bail!("CBOR contains more than {MAX_CBOR_TOTAL_ITEMS} items");
564        }
565        let initial = self.read_byte()?;
566        let major = initial >> 5;
567        let additional = initial & 0x1f;
568        let argument = match additional {
569            value @ 0..=23 => u64::from(value),
570            24 => {
571                let value = u64::from(self.read_byte()?);
572                if value < 24 {
573                    bail!("CBOR argument is not shortest-form encoded");
574                }
575                value
576            }
577            25 => {
578                let value = u64::from(u16::from_be_bytes(self.read_exact()?));
579                if value <= u64::from(u8::MAX) {
580                    bail!("CBOR argument is not shortest-form encoded");
581                }
582                value
583            }
584            26 => {
585                let value = u64::from(u32::from_be_bytes(self.read_exact()?));
586                if value <= u64::from(u16::MAX) {
587                    bail!("CBOR argument is not shortest-form encoded");
588                }
589                value
590            }
591            27 => {
592                let value = u64::from_be_bytes(self.read_exact()?);
593                if value <= u64::from(u32::MAX) {
594                    bail!("CBOR argument is not shortest-form encoded");
595                }
596                value
597            }
598            31 => bail!("indefinite-length CBOR is forbidden"),
599            _ => bail!("reserved CBOR additional-information value"),
600        };
601        Ok((major, argument))
602    }
603
604    fn length(argument: u64) -> Result<usize> {
605        usize::try_from(argument).context("CBOR length does not fit address space")
606    }
607
608    fn bytes(&mut self, expected_major: u8, limit: usize) -> Result<&'a [u8]> {
609        let (major, argument) = self.head()?;
610        if major != expected_major {
611            bail!("unexpected CBOR major type {major}, expected {expected_major}");
612        }
613        let length = Self::length(argument)?;
614        if length > limit {
615            bail!("CBOR string length {length} exceeds {limit}-byte limit");
616        }
617        let end = self
618            .offset
619            .checked_add(length)
620            .context("CBOR string length overflow")?;
621        let bytes = self
622            .input
623            .get(self.offset..end)
624            .context("truncated CBOR string")?;
625        self.offset = end;
626        Ok(bytes)
627    }
628
629    fn container(&mut self, expected_major: u8) -> Result<usize> {
630        let (major, argument) = self.head()?;
631        if major != expected_major {
632            bail!("unexpected CBOR major type {major}, expected {expected_major}");
633        }
634        let length = Self::length(argument)?;
635        if length > MAX_CBOR_CONTAINER_ITEMS {
636            bail!("CBOR container has {length} entries; limit is {MAX_CBOR_CONTAINER_ITEMS}");
637        }
638        Ok(length)
639    }
640
641    fn item(&mut self, depth: usize) -> Result<()> {
642        if depth > MAX_CBOR_DEPTH {
643            bail!("CBOR nesting exceeds depth {MAX_CBOR_DEPTH}");
644        }
645        let start = self.offset;
646        let (major, argument) = self.head()?;
647        match major {
648            0 | 1 => {}
649            2 | 3 => {
650                let length = Self::length(argument)?;
651                let limit = if major == 2 {
652                    self.max_byte_string
653                } else {
654                    MAX_HEADER_TEXT_BYTES
655                };
656                if length > limit {
657                    bail!("CBOR string length {length} exceeds {limit}-byte limit");
658                }
659                self.offset = self
660                    .offset
661                    .checked_add(length)
662                    .context("CBOR string length overflow")?;
663                if self.offset > self.input.len() {
664                    bail!("truncated CBOR string");
665                }
666            }
667            4 => {
668                let length = Self::length(argument)?;
669                if length > MAX_CBOR_CONTAINER_ITEMS {
670                    bail!("CBOR array has {length} entries; limit is {MAX_CBOR_CONTAINER_ITEMS}");
671                }
672                for _ in 0..length {
673                    self.item(depth + 1)?;
674                }
675            }
676            5 => {
677                let length = Self::length(argument)?;
678                if length > MAX_CBOR_CONTAINER_ITEMS {
679                    bail!("CBOR map has {length} entries; limit is {MAX_CBOR_CONTAINER_ITEMS}");
680                }
681                let mut previous_key: Option<(usize, usize)> = None;
682                for _ in 0..length {
683                    let key_start = self.offset;
684                    self.item(depth + 1)?;
685                    let key_end = self.offset;
686                    if let Some((previous_start, previous_end)) = previous_key {
687                        let previous = &self.input[previous_start..previous_end];
688                        let current = &self.input[key_start..key_end];
689                        if previous >= current {
690                            bail!("CBOR map keys are duplicate or not in deterministic order");
691                        }
692                    }
693                    previous_key = Some((key_start, key_end));
694                    self.item(depth + 1)?;
695                }
696            }
697            // Tags, floats, simple values, and break are not used anywhere in
698            // this fixed COSE profile.  Rejecting them keeps the preflight small
699            // and prevents semantic-decoder discrepancies.
700            6 | 7 => bail!("unsupported CBOR type in COSE_Encrypt0 profile"),
701            _ => unreachable!("CBOR major type is three bits"),
702        }
703        if self.offset <= start {
704            bail!("CBOR scanner made no progress");
705        }
706        Ok(())
707    }
708}
709
710fn preflight_cose_encrypt0(cose_bytes: &[u8]) -> Result<()> {
711    let mut outer = CborPreflight::new(cose_bytes, MAX_HEADER_VALUE_BYTES);
712    let top_level_items = outer.container(4)?;
713    if top_level_items != 3 {
714        bail!("COSE_Encrypt0 must be a definite three-element array");
715    }
716
717    let protected = outer.bytes(2, MAX_PROTECTED_HEADER_BYTES)?;
718    let mut protected_scanner = CborPreflight::new(protected, MAX_HEADER_VALUE_BYTES);
719    let protected_entries = protected_scanner.container(5)?;
720    if protected_entries > 16 {
721        bail!("protected header map has too many entries");
722    }
723    // Rewind and scan the entire map so key ordering and nested values are
724    // checked by the same generic deterministic scanner.
725    protected_scanner.offset = 0;
726    protected_scanner.items = 0;
727    protected_scanner.item(0)?;
728    protected_scanner.finish()?;
729
730    let unprotected_start = outer.offset;
731    let unprotected_entries = outer.container(5)?;
732    if unprotected_entries > 16 {
733        bail!("unprotected header map has too many entries");
734    }
735    outer.offset = unprotected_start;
736    outer.items -= 1;
737    outer.item(0)?;
738
739    let ciphertext = outer.bytes(2, MAX_PLAINTEXT_BYTES + 16)?;
740    if ciphertext.len() < 16 {
741        bail!("COSE_Encrypt0 ciphertext is shorter than its AEAD tag");
742    }
743    outer.finish()
744}
745
746fn parse_canonical(cose_bytes: &[u8]) -> Result<CoseEncrypt0> {
747    if cose_bytes.len() > MAX_COSE_BYTES {
748        bail!("COSE_Encrypt0 exceeds {MAX_COSE_BYTES}-byte limit");
749    }
750    preflight_cose_encrypt0(cose_bytes)
751        .context("COSE_Encrypt0 failed bounded deterministic CBOR preflight")?;
752    let enc = CoseEncrypt0::from_slice(cose_bytes)
753        .map_err(|error| anyhow::anyhow!("malformed COSE_Encrypt0: {error}"))?;
754    let ciphertext_len = enc
755        .ciphertext
756        .as_ref()
757        .context("COSE_Encrypt0 has no ciphertext")?
758        .len();
759    if !(16..=MAX_PLAINTEXT_BYTES + 16).contains(&ciphertext_len) {
760        bail!("COSE_Encrypt0 ciphertext length is outside bounded AEAD limits");
761    }
762
763    let mut normalized = enc.clone();
764    normalized.protected.original_data = None;
765    let canonical = normalized
766        .to_vec()
767        .map_err(|error| anyhow::anyhow!("cannot canonicalize COSE_Encrypt0: {error}"))?;
768    if canonical != cose_bytes {
769        bail!("COSE_Encrypt0 is not deterministic/canonical CBOR");
770    }
771    Ok(enc)
772}
773
774fn seal_core(
775    base_key: &[u8; 32],
776    suite: SuiteId,
777    context: &SealContext,
778    material: Option<&HybridKemMaterial>,
779    plaintext: &[u8],
780    external_aad: &[u8],
781) -> Result<Vec<u8>> {
782    validate_inputs(context, plaintext.len(), external_aad)?;
783    let context_key = derive_context_key(base_key, suite, context)?;
784    let nonce = derive_nonce(context);
785    let mut builder = CoseEncrypt0Builder::new().protected(build_protected(suite, context));
786    if let Some(material) = material {
787        let unprotected = HeaderBuilder::new()
788            .value(HDR_KEM_MATERIAL, CborValue::Bytes(material.encode()))
789            .build();
790        builder = builder.unprotected(unprotected);
791    }
792    let enc = builder
793        .try_create_ciphertext(plaintext, external_aad, |pt, cose_aad| {
794            aead_seal(&context_key, &nonce, pt, cose_aad)
795        })?
796        .build();
797    let bytes = enc
798        .to_vec()
799        .map_err(|error| anyhow::anyhow!("serialize COSE_Encrypt0: {error}"))?;
800    if bytes.len() > MAX_COSE_BYTES {
801        bail!("serialized COSE_Encrypt0 exceeds {MAX_COSE_BYTES}-byte limit");
802    }
803    Ok(bytes)
804}
805
806fn open_core(
807    base_key: &[u8; 32],
808    expected_suite: SuiteId,
809    expected: &SealContext,
810    enc: &CoseEncrypt0,
811    external_aad: &[u8],
812) -> Result<Vec<u8>> {
813    validate_inputs(expected, 0, external_aad)?;
814    require_exact_protected(enc, expected_suite, expected)?;
815    let context_key = derive_context_key(base_key, expected_suite, expected)?;
816    let nonce = derive_nonce(expected);
817    enc.decrypt_ciphertext(
818        external_aad,
819        || anyhow::anyhow!("COSE_Encrypt0 has no ciphertext"),
820        |ciphertext, cose_aad| aead_open(&context_key, &nonce, ciphertext, cose_aad),
821    )
822}
823
824/// Seal to a hybrid recipient with bounded canonical COSE and nonce-use state.
825pub fn seal(
826    recipient: &RecipientPublic,
827    context: &SealContext,
828    plaintext: &[u8],
829    external_aad: &[u8],
830    nonce_ledger: &mut OutboundNonceLedger,
831) -> Result<Vec<u8>> {
832    validate_inputs(context, plaintext.len(), external_aad)?;
833    nonce_ledger.record(NonceUse::new(recipient.suite_id, context))?;
834    let (material, secret) = hybrid_kem::encapsulate_to(recipient)?;
835    let base_key = derive_aead_key(&secret);
836    seal_core(
837        &base_key,
838        recipient.suite_id,
839        context,
840        Some(&material),
841        plaintext,
842        external_aad,
843    )
844}
845
846/// Open from a hybrid recipient and record replay state after authentication.
847pub fn open(
848    recipient: &RecipientKeypair,
849    expected: &SealContext,
850    cose_bytes: &[u8],
851    external_aad: &[u8],
852    replay_ledger: &mut InboundReplayLedger,
853) -> Result<Vec<u8>> {
854    validate_inputs(expected, 0, external_aad)?;
855    let usage = NonceUse::new(recipient.suite_id, expected);
856    replay_ledger.ensure_unseen(&usage)?;
857    let enc = parse_canonical(cose_bytes)?;
858    require_exact_protected(&enc, recipient.suite_id, expected)?;
859    let material = require_material(&enc)?;
860    if material.suite_id != recipient.suite_id {
861        bail!("hybrid-KEM material suite does not match recipient suite");
862    }
863    let secret = hybrid_kem::decapsulate(recipient, &material)?;
864    let base_key = derive_aead_key(&secret);
865    let plaintext = open_core(&base_key, recipient.suite_id, expected, &enc, external_aad)?;
866    replay_ledger.record(usage)?;
867    Ok(plaintext)
868}
869
870/// Seal with a pre-derived base key and explicit lifecycle-owned nonce state.
871///
872/// The base key must be independently bound to the same pinned suite.  This is
873/// the narrow seam intended for #554/#555 after their handshake/epoch commit.
874pub fn seal_prederived(
875    base_key: &[u8; 32],
876    suite: SuiteId,
877    context: &SealContext,
878    plaintext: &[u8],
879    external_aad: &[u8],
880    nonce_ledger: &mut OutboundNonceLedger,
881) -> Result<Vec<u8>> {
882    validate_inputs(context, plaintext.len(), external_aad)?;
883    nonce_ledger.record(NonceUse::new(suite, context))?;
884    seal_core(base_key, suite, context, None, plaintext, external_aad)
885}
886
887/// Open with a pre-derived base key and explicit replay state.
888pub fn open_prederived(
889    base_key: &[u8; 32],
890    expected_suite: SuiteId,
891    expected: &SealContext,
892    cose_bytes: &[u8],
893    external_aad: &[u8],
894    replay_ledger: &mut InboundReplayLedger,
895) -> Result<Vec<u8>> {
896    validate_inputs(expected, 0, external_aad)?;
897    let usage = NonceUse::new(expected_suite, expected);
898    replay_ledger.ensure_unseen(&usage)?;
899    let enc = parse_canonical(cose_bytes)?;
900    require_no_unprotected(&enc)?;
901    let plaintext = open_core(base_key, expected_suite, expected, &enc, external_aad)?;
902    replay_ledger.record(usage)?;
903    Ok(plaintext)
904}
905
906fn compatibility_context(
907    recipient: &RecipientPublic,
908    external_aad: &[u8],
909    epoch: u64,
910    sequence: u64,
911) -> Result<SealContext> {
912    if external_aad.len() > MAX_EXTERNAL_AAD_BYTES {
913        bail!("external AAD exceeds {MAX_EXTERNAL_AAD_BYTES}-byte limit");
914    }
915    recipient.validate()?;
916    let epoch = u32::try_from(epoch).context("epoch exceeds u32 nonce domain")?;
917    let encoded = recipient.encode();
918    let recipient_id = digest_parts(COMPAT_RECIPIENT_LABEL, &[&encoded]).to_vec();
919    let key_id = digest_parts(COMPAT_KEY_LABEL, &[&encoded]).to_vec();
920    let nonce_domain = digest_parts(COMPAT_DOMAIN_LABEL, &[external_aad]);
921    Ok(SealContext {
922        recipient_id,
923        key_id,
924        nonce_domain,
925        epoch,
926        sequence,
927    })
928}
929
930fn digest_parts(label: &[u8], parts: &[&[u8]]) -> [u8; 32] {
931    let mut hash = Sha256::new();
932    hash.update(label);
933    for part in parts {
934        hash.update((part.len() as u64).to_be_bytes());
935        hash.update(part);
936    }
937    hash.finalize().into()
938}
939
940/// Compatibility wrapper for the existing encrypted-envelope lifecycle.
941///
942/// New code must use [`seal`] with an owning [`OutboundNonceLedger`].
943pub fn seal_to_recipient(
944    recipient: &RecipientPublic,
945    plaintext: &[u8],
946    external_aad: &[u8],
947    epoch: u64,
948    sequence: u64,
949) -> Result<Vec<u8>> {
950    let context = compatibility_context(recipient, external_aad, epoch, sequence)?;
951    validate_inputs(&context, plaintext.len(), external_aad)?;
952    let (material, secret) = hybrid_kem::encapsulate_to(recipient)?;
953    let base_key = derive_aead_key(&secret);
954    seal_core(
955        &base_key,
956        recipient.suite_id,
957        &context,
958        Some(&material),
959        plaintext,
960        external_aad,
961    )
962}
963
964/// Compatibility wrapper for the existing encrypted-envelope lifecycle.
965///
966/// New code must use [`open`] with an owning [`InboundReplayLedger`].
967pub fn open_from_recipient(
968    recipient: &RecipientKeypair,
969    cose_bytes: &[u8],
970    external_aad: &[u8],
971    epoch: u64,
972    sequence: u64,
973) -> Result<Vec<u8>> {
974    let context = compatibility_context(&recipient.public(), external_aad, epoch, sequence)?;
975    validate_inputs(&context, 0, external_aad)?;
976    let enc = parse_canonical(cose_bytes)?;
977    require_exact_protected(&enc, recipient.suite_id, &context)?;
978    let material = require_material(&enc)?;
979    let secret = hybrid_kem::decapsulate(recipient, &material)?;
980    let base_key = derive_aead_key(&secret);
981    open_core(&base_key, recipient.suite_id, &context, &enc, external_aad)
982}
983
984#[cfg(test)]
985#[allow(clippy::unwrap_used, clippy::expect_used)]
986mod tests {
987    use super::*;
988    use crate::crypto::hybrid_kem::{generate_recipient, recipient_from_seeds, KemId, KemShare};
989
990    const SUITE: SuiteId = SuiteId::HyKemX25519MlKem768;
991    const AAD: &[u8] = b"canonical transcript bytes";
992
993    fn context(sequence: u64) -> SealContext {
994        SealContext {
995            recipient_id: b"did:at9p:example/service/inference".to_vec(),
996            key_id: b"did:at9p:example#mesh-kem-7".to_vec(),
997            nonce_domain: [0x5a; 32],
998            epoch: 3,
999            sequence,
1000        }
1001    }
1002
1003    fn outbound_ledger() -> OutboundNonceLedger {
1004        OutboundNonceLedger::new(32).unwrap()
1005    }
1006
1007    fn inbound_ledger() -> InboundReplayLedger {
1008        InboundReplayLedger::new(32).unwrap()
1009    }
1010
1011    fn material(enc: &CoseEncrypt0) -> HybridKemMaterial {
1012        require_material(enc).unwrap()
1013    }
1014
1015    fn replace_material(enc: &mut CoseEncrypt0, value: &HybridKemMaterial) {
1016        let (_, header_value) = enc
1017            .unprotected
1018            .rest
1019            .iter_mut()
1020            .find(|(label, _)| label == &Label::Int(HDR_KEM_MATERIAL))
1021            .unwrap();
1022        *header_value = CborValue::Bytes(value.encode());
1023    }
1024
1025    fn encode_value(value: &CborValue) -> Vec<u8> {
1026        let mut bytes = Vec::new();
1027        ciborium::ser::into_writer(value, &mut bytes).unwrap();
1028        bytes
1029    }
1030
1031    fn mutate_protected_map(
1032        sealed: &[u8],
1033        mutation: impl FnOnce(&mut Vec<(CborValue, CborValue)>),
1034    ) -> Vec<u8> {
1035        let mut top: CborValue = ciborium::de::from_reader(sealed).unwrap();
1036        let top_array = match &mut top {
1037            CborValue::Array(items) => items,
1038            _ => panic!("COSE_Encrypt0 must be an array"),
1039        };
1040        let protected_bytes = match &mut top_array[0] {
1041            CborValue::Bytes(bytes) => bytes,
1042            _ => panic!("protected header must be a byte string"),
1043        };
1044        let mut protected: CborValue =
1045            ciborium::de::from_reader(protected_bytes.as_slice()).unwrap();
1046        let map = match &mut protected {
1047            CborValue::Map(entries) => entries,
1048            _ => panic!("protected header must contain a map"),
1049        };
1050        mutation(map);
1051        *protected_bytes = encode_value(&protected);
1052        encode_value(&top)
1053    }
1054
1055    fn replace_once(bytes: &mut Vec<u8>, needle: &[u8], replacement: &[u8]) {
1056        let offset = bytes
1057            .windows(needle.len())
1058            .position(|candidate| candidate == needle)
1059            .expect("mutation target must exist");
1060        bytes.splice(offset..offset + needle.len(), replacement.iter().copied());
1061    }
1062
1063    #[test]
1064    fn recipient_roundtrip_and_replay_rejected() {
1065        let recipient = generate_recipient(SUITE).unwrap();
1066        let ctx = context(9);
1067        let mut outbound = outbound_ledger();
1068        let sealed = seal(&recipient.public(), &ctx, b"secret", AAD, &mut outbound).unwrap();
1069        let mut inbound = inbound_ledger();
1070        assert_eq!(
1071            open(&recipient, &ctx, &sealed, AAD, &mut inbound).unwrap(),
1072            b"secret"
1073        );
1074        assert!(open(&recipient, &ctx, &sealed, AAD, &mut inbound).is_err());
1075    }
1076
1077    #[test]
1078    fn outbound_nonce_reuse_is_burned() {
1079        let recipient = generate_recipient(SUITE).unwrap();
1080        let ctx = context(4);
1081        let mut outbound = outbound_ledger();
1082        seal(&recipient.public(), &ctx, b"first", AAD, &mut outbound).unwrap();
1083        assert!(seal(&recipient.public(), &ctx, b"second", AAD, &mut outbound).is_err());
1084    }
1085
1086    #[test]
1087    fn wrong_context_fields_and_aad_rejected() {
1088        let recipient = generate_recipient(SUITE).unwrap();
1089        let ctx = context(7);
1090        let sealed = seal(
1091            &recipient.public(),
1092            &ctx,
1093            b"secret",
1094            AAD,
1095            &mut outbound_ledger(),
1096        )
1097        .unwrap();
1098        let mutations = [
1099            {
1100                let mut value = ctx.clone();
1101                value.recipient_id.push(b'x');
1102                value
1103            },
1104            {
1105                let mut value = ctx.clone();
1106                value.key_id.push(b'x');
1107                value
1108            },
1109            {
1110                let mut value = ctx.clone();
1111                value.nonce_domain[0] ^= 1;
1112                value
1113            },
1114            {
1115                let mut value = ctx.clone();
1116                value.epoch += 1;
1117                value
1118            },
1119            {
1120                let mut value = ctx.clone();
1121                value.sequence += 1;
1122                value
1123            },
1124        ];
1125        for mutation in mutations {
1126            assert!(open(&recipient, &mutation, &sealed, AAD, &mut inbound_ledger()).is_err());
1127        }
1128        assert!(open(
1129            &recipient,
1130            &ctx,
1131            &sealed,
1132            b"wrong transcript",
1133            &mut inbound_ledger()
1134        )
1135        .is_err());
1136    }
1137
1138    #[test]
1139    fn wrong_recipient_and_cartesian_component_keys_rejected() {
1140        let first = generate_recipient(SUITE).unwrap();
1141        let second = generate_recipient(SUITE).unwrap();
1142        let ctx = context(1);
1143        let sealed = seal(
1144            &first.public(),
1145            &ctx,
1146            b"secret",
1147            AAD,
1148            &mut outbound_ledger(),
1149        )
1150        .unwrap();
1151        assert!(open(&second, &ctx, &sealed, AAD, &mut inbound_ledger()).is_err());
1152
1153        let x_seed = [0x11; 32];
1154        let pq_seed_a = [0x22; 64];
1155        let pq_seed_b = [0x33; 64];
1156        let intended = recipient_from_seeds(SUITE, &[&x_seed, &pq_seed_a]).unwrap();
1157        let cartesian = recipient_from_seeds(SUITE, &[&x_seed, &pq_seed_b]).unwrap();
1158        let sealed = seal(
1159            &intended.public(),
1160            &context(2),
1161            b"secret",
1162            AAD,
1163            &mut outbound_ledger(),
1164        )
1165        .unwrap();
1166        assert!(open(&cartesian, &context(2), &sealed, AAD, &mut inbound_ledger()).is_err());
1167    }
1168
1169    #[test]
1170    fn missing_reordered_and_cross_encapsulation_pq_shares_rejected() {
1171        let recipient = generate_recipient(SUITE).unwrap();
1172        let ctx_a = context(10);
1173        let ctx_b = context(11);
1174        let sealed_a = seal(
1175            &recipient.public(),
1176            &ctx_a,
1177            b"a",
1178            AAD,
1179            &mut outbound_ledger(),
1180        )
1181        .unwrap();
1182        let sealed_b = seal(
1183            &recipient.public(),
1184            &ctx_b,
1185            b"b",
1186            AAD,
1187            &mut outbound_ledger(),
1188        )
1189        .unwrap();
1190        let enc_a = CoseEncrypt0::from_slice(&sealed_a).unwrap();
1191        let enc_b = CoseEncrypt0::from_slice(&sealed_b).unwrap();
1192
1193        let mut missing = material(&enc_a);
1194        missing.shares.pop();
1195        let mut mutated = enc_a.clone();
1196        replace_material(&mut mutated, &missing);
1197        mutated.protected.original_data = None;
1198        assert!(open(
1199            &recipient,
1200            &ctx_a,
1201            &mutated.to_vec().unwrap(),
1202            AAD,
1203            &mut inbound_ledger()
1204        )
1205        .is_err());
1206
1207        let original = material(&enc_a);
1208        let reordered = HybridKemMaterial {
1209            suite_id: SUITE,
1210            shares: vec![original.shares[1].clone(), original.shares[0].clone()],
1211        };
1212        let mut mutated = enc_a.clone();
1213        replace_material(&mut mutated, &reordered);
1214        mutated.protected.original_data = None;
1215        assert!(open(
1216            &recipient,
1217            &ctx_a,
1218            &mutated.to_vec().unwrap(),
1219            AAD,
1220            &mut inbound_ledger()
1221        )
1222        .is_err());
1223
1224        let mut crossed = original;
1225        let other = material(&enc_b);
1226        assert_eq!(crossed.shares[1].kem_id, KemId::MlKem768);
1227        crossed.shares[1] = KemShare {
1228            kem_id: KemId::MlKem768,
1229            bytes: other.shares[1].bytes.clone(),
1230        };
1231        let mut mutated = enc_a;
1232        replace_material(&mut mutated, &crossed);
1233        mutated.protected.original_data = None;
1234        assert!(open(
1235            &recipient,
1236            &ctx_a,
1237            &mutated.to_vec().unwrap(),
1238            AAD,
1239            &mut inbound_ledger()
1240        )
1241        .is_err());
1242    }
1243
1244    #[test]
1245    fn noncanonical_and_duplicate_headers_rejected() {
1246        let recipient = generate_recipient(SUITE).unwrap();
1247        let ctx = context(12);
1248        let sealed = seal(
1249            &recipient.public(),
1250            &ctx,
1251            b"secret",
1252            AAD,
1253            &mut outbound_ledger(),
1254        )
1255        .unwrap();
1256        assert_eq!(sealed[0], 0x83);
1257        let mut noncanonical = vec![0x98, 0x03];
1258        noncanonical.extend_from_slice(&sealed[1..]);
1259        assert!(open(&recipient, &ctx, &noncanonical, AAD, &mut inbound_ledger()).is_err());
1260
1261        let mut top: CborValue = ciborium::de::from_reader(sealed.as_slice()).unwrap();
1262        let array = match &mut top {
1263            CborValue::Array(value) => value,
1264            _ => panic!("COSE_Encrypt0 must be an array"),
1265        };
1266        let protected = match &mut array[0] {
1267            CborValue::Bytes(value) => value,
1268            _ => panic!("protected header must be bytes"),
1269        };
1270        assert!((0xa0..=0xb7).contains(&protected[0]));
1271        protected[0] += 1;
1272        let duplicate = CborValue::Map(vec![(
1273            CborValue::Integer(HDR_SUITE_ID.into()),
1274            CborValue::Integer(SUITE.as_u16().into()),
1275        )]);
1276        let mut encoded_duplicate = Vec::new();
1277        ciborium::ser::into_writer(&duplicate, &mut encoded_duplicate).unwrap();
1278        protected.extend_from_slice(&encoded_duplicate[1..]);
1279        let mut duplicate_wire = Vec::new();
1280        ciborium::ser::into_writer(&top, &mut duplicate_wire).unwrap();
1281        assert!(open(
1282            &recipient,
1283            &ctx,
1284            &duplicate_wire,
1285            AAD,
1286            &mut inbound_ledger()
1287        )
1288        .is_err());
1289    }
1290
1291    #[test]
1292    fn reordered_protected_and_unprotected_maps_are_rejected_by_preflight() {
1293        let recipient = generate_recipient(SUITE).unwrap();
1294        let sealed = seal(
1295            &recipient.public(),
1296            &context(121),
1297            b"secret",
1298            AAD,
1299            &mut outbound_ledger(),
1300        )
1301        .unwrap();
1302
1303        let reordered_protected = mutate_protected_map(&sealed, |entries| {
1304            let first = entries
1305                .iter()
1306                .position(|(key, _)| key == &CborValue::Integer(HDR_SUITE_ID.into()))
1307                .unwrap();
1308            let second = entries
1309                .iter()
1310                .position(|(key, _)| key == &CborValue::Integer(HDR_RECIPIENT_ID.into()))
1311                .unwrap();
1312            entries.swap(first, second);
1313        });
1314        assert!(parse_canonical(&reordered_protected).is_err());
1315
1316        let mut top: CborValue = ciborium::de::from_reader(sealed.as_slice()).unwrap();
1317        let unprotected = match &mut top {
1318            CborValue::Array(items) => match &mut items[1] {
1319                CborValue::Map(entries) => entries,
1320                _ => panic!("unprotected header must be a map"),
1321            },
1322            _ => panic!("COSE_Encrypt0 must be an array"),
1323        };
1324        unprotected.push((
1325            CborValue::Integer((-65560).into()),
1326            CborValue::Integer(1.into()),
1327        ));
1328        // Both private labels have equal-length encodings; -65539 sorts before
1329        // -65560 by its encoded argument.  Swap them to retain a valid map with
1330        // a mutation that only the independent ordering check must reject.
1331        unprotected.swap(0, 1);
1332        assert!(parse_canonical(&encode_value(&top)).is_err());
1333    }
1334
1335    #[test]
1336    fn nonminimal_header_keys_and_values_are_rejected_by_preflight() {
1337        let recipient = generate_recipient(SUITE).unwrap();
1338        let sealed = seal(
1339            &recipient.public(),
1340            &context(122),
1341            b"secret",
1342            AAD,
1343            &mut outbound_ledger(),
1344        )
1345        .unwrap();
1346
1347        // -65538 is major type 1 with argument 65537.  Eight argument bytes are
1348        // valid CBOR but not the shortest deterministic representation.
1349        let mut protected_key = mutate_protected_map(&sealed, |_| {});
1350        let mut top: CborValue = ciborium::de::from_reader(protected_key.as_slice()).unwrap();
1351        let protected = match &mut top {
1352            CborValue::Array(items) => match &mut items[0] {
1353                CborValue::Bytes(bytes) => bytes,
1354                _ => panic!("protected header must be bytes"),
1355            },
1356            _ => panic!("COSE_Encrypt0 must be an array"),
1357        };
1358        replace_once(
1359            protected,
1360            &[0x3a, 0x00, 0x01, 0x00, 0x01],
1361            &[0x3b, 0, 0, 0, 0, 0, 1, 0, 1],
1362        );
1363        protected_key = encode_value(&top);
1364        assert!(parse_canonical(&protected_key).is_err());
1365
1366        // The suite value 1 follows that key.  Encoding it as 0x18 0x01 is
1367        // likewise a valid but non-shortest integer representation.
1368        let mut top: CborValue = ciborium::de::from_reader(sealed.as_slice()).unwrap();
1369        let protected = match &mut top {
1370            CborValue::Array(items) => match &mut items[0] {
1371                CborValue::Bytes(bytes) => bytes,
1372                _ => panic!("protected header must be bytes"),
1373            },
1374            _ => panic!("COSE_Encrypt0 must be an array"),
1375        };
1376        replace_once(
1377            protected,
1378            &[0x3a, 0x00, 0x01, 0x00, 0x01, 0x01],
1379            &[0x3a, 0x00, 0x01, 0x00, 0x01, 0x18, 0x01],
1380        );
1381        assert!(parse_canonical(&encode_value(&top)).is_err());
1382
1383        // The unprotected private key -65539 is also rejected when widened.
1384        let mut unprotected_key = sealed.clone();
1385        replace_once(
1386            &mut unprotected_key,
1387            &[0x3a, 0x00, 0x01, 0x00, 0x02],
1388            &[0x3b, 0, 0, 0, 0, 0, 1, 0, 2],
1389        );
1390        assert!(parse_canonical(&unprotected_key).is_err());
1391
1392        // The hybrid material is a 16-bit-length byte string in the valid
1393        // object.  Widen only that length argument to 32 bits.
1394        let mut unprotected_value = sealed.clone();
1395        let key = [0x3a, 0x00, 0x01, 0x00, 0x02];
1396        let key_offset = unprotected_value
1397            .windows(key.len())
1398            .position(|candidate| candidate == key)
1399            .unwrap();
1400        let value_offset = key_offset + key.len();
1401        assert_eq!(unprotected_value[value_offset], 0x59);
1402        let high = unprotected_value[value_offset + 1];
1403        let low = unprotected_value[value_offset + 2];
1404        unprotected_value.splice(
1405            value_offset..value_offset + 3,
1406            [0x5a, 0x00, 0x00, high, low],
1407        );
1408        assert!(parse_canonical(&unprotected_value).is_err());
1409    }
1410
1411    #[test]
1412    fn hostile_cbor_is_rejected_before_value_tree_amplification() {
1413        let ciphertext = [0u8; 16];
1414        let finish = |mut prefix: Vec<u8>| {
1415            prefix.push(0x50);
1416            prefix.extend_from_slice(&ciphertext);
1417            prefix
1418        };
1419
1420        // A 12-byte prefix claims more than four billion array members.  The
1421        // preflight rejects the declared count without iterating or allocating.
1422        let amplified = finish(vec![
1423            0x83, 0x41, 0xa0, 0xa1, 0x00, 0x9a, 0xff, 0xff, 0xff, 0xff,
1424        ]);
1425        assert!(preflight_cose_encrypt0(&amplified).is_err());
1426
1427        let oversized_container = finish(vec![0x83, 0x41, 0xa0, 0xa1, 0x00, 0x98, 0x21]);
1428        assert!(preflight_cose_encrypt0(&oversized_container).is_err());
1429
1430        let indefinite = finish(vec![0x83, 0x41, 0xa0, 0xbf, 0xff]);
1431        assert!(preflight_cose_encrypt0(&indefinite).is_err());
1432
1433        let mut deep = vec![0x83, 0x41, 0xa0, 0xa1, 0x00];
1434        deep.extend(std::iter::repeat_n(0x81, MAX_CBOR_DEPTH + 1));
1435        deep.push(0x00);
1436        assert!(preflight_cose_encrypt0(&finish(deep)).is_err());
1437
1438        // A header byte string over the 4 KiB schema limit is rejected from its
1439        // five-byte declaration alone, before looking for or allocating bytes.
1440        let oversized_string = finish(vec![
1441            0x83, 0x41, 0xa0, 0xa1, 0x00, 0x5a, 0x00, 0x00, 0x10, 0x01,
1442        ]);
1443        assert!(preflight_cose_encrypt0(&oversized_string).is_err());
1444
1445        let mut trailing = finish(vec![0x83, 0x41, 0xa0, 0xa0]);
1446        trailing.push(0x00);
1447        assert!(preflight_cose_encrypt0(&trailing).is_err());
1448    }
1449
1450    #[test]
1451    fn deterministic_map_order_is_core_bytewise_lexicographic() {
1452        let finish = |mut prefix: Vec<u8>| {
1453            prefix.push(0x50);
1454            prefix.extend_from_slice(&[0u8; 16]);
1455            prefix
1456        };
1457        // RFC 8949 section 4.2.1 compares the deterministic key encodings
1458        // bytewise, so 100 (0x18 0x64) sorts before -1 (0x20).  The reverse is
1459        // the optional length-first order from section 4.2.3, which this profile
1460        // deliberately does not implement.
1461        let canonical = finish(vec![0x83, 0x41, 0xa0, 0xa2, 0x18, 0x64, 0x00, 0x20, 0x00]);
1462        assert!(preflight_cose_encrypt0(&canonical).is_ok());
1463
1464        let reversed = finish(vec![0x83, 0x41, 0xa0, 0xa2, 0x20, 0x00, 0x18, 0x64, 0x00]);
1465        assert!(preflight_cose_encrypt0(&reversed).is_err());
1466    }
1467
1468    #[test]
1469    fn focused_cose_gate_covers_every_hybrid_component_secret() {
1470        assert!(hybrid_kem::combiner_is_sensitive_to_every_component_for_cose());
1471    }
1472
1473    #[test]
1474    fn truncation_unknown_headers_and_tamper_rejected() {
1475        let recipient = generate_recipient(SUITE).unwrap();
1476        let ctx = context(13);
1477        let sealed = seal(
1478            &recipient.public(),
1479            &ctx,
1480            b"secret",
1481            AAD,
1482            &mut outbound_ledger(),
1483        )
1484        .unwrap();
1485        for cut in [0, 1, sealed.len() / 2, sealed.len() - 1] {
1486            assert!(open(&recipient, &ctx, &sealed[..cut], AAD, &mut inbound_ledger()).is_err());
1487        }
1488        let mut tampered = sealed.clone();
1489        let last = tampered.len() - 1;
1490        tampered[last] ^= 0x80;
1491        assert!(open(&recipient, &ctx, &tampered, AAD, &mut inbound_ledger()).is_err());
1492
1493        let mut unknown = CoseEncrypt0::from_slice(&sealed).unwrap();
1494        unknown
1495            .protected
1496            .header
1497            .rest
1498            .push((Label::Int(-65560), CborValue::Integer(1.into())));
1499        unknown.protected.original_data = None;
1500        assert!(open(
1501            &recipient,
1502            &ctx,
1503            &unknown.to_vec().unwrap(),
1504            AAD,
1505            &mut inbound_ledger()
1506        )
1507        .is_err());
1508    }
1509
1510    #[test]
1511    fn wrong_suite_and_algorithm_headers_rejected() {
1512        let recipient = generate_recipient(SUITE).unwrap();
1513        let ctx = context(14);
1514        let sealed = seal(
1515            &recipient.public(),
1516            &ctx,
1517            b"secret",
1518            AAD,
1519            &mut outbound_ledger(),
1520        )
1521        .unwrap();
1522
1523        let mut wrong_suite = CoseEncrypt0::from_slice(&sealed).unwrap();
1524        let (_, suite_value) = wrong_suite
1525            .protected
1526            .header
1527            .rest
1528            .iter_mut()
1529            .find(|(label, _)| label == &Label::Int(HDR_SUITE_ID))
1530            .unwrap();
1531        *suite_value = CborValue::Integer(2.into());
1532        wrong_suite.protected.original_data = None;
1533        assert!(open(
1534            &recipient,
1535            &ctx,
1536            &wrong_suite.to_vec().unwrap(),
1537            AAD,
1538            &mut inbound_ledger()
1539        )
1540        .is_err());
1541
1542        let mut wrong_algorithm = CoseEncrypt0::from_slice(&sealed).unwrap();
1543        wrong_algorithm.protected.header.alg =
1544            Some(coset::Algorithm::Assigned(iana::Algorithm::A256GCM));
1545        wrong_algorithm.protected.original_data = None;
1546        assert!(open(
1547            &recipient,
1548            &ctx,
1549            &wrong_algorithm.to_vec().unwrap(),
1550            AAD,
1551            &mut inbound_ledger()
1552        )
1553        .is_err());
1554    }
1555
1556    #[test]
1557    fn bounded_inputs_and_ledger_exhaustion_fail_closed() {
1558        let recipient = generate_recipient(SUITE).unwrap();
1559        let mut one = OutboundNonceLedger::new(1).unwrap();
1560        seal(&recipient.public(), &context(0), b"a", AAD, &mut one).unwrap();
1561        assert!(seal(&recipient.public(), &context(1), b"b", AAD, &mut one).is_err());
1562        assert!(OutboundNonceLedger::new(0).is_err());
1563        assert!(InboundReplayLedger::new(0).is_err());
1564        assert!(seal(
1565            &recipient.public(),
1566            &context(2),
1567            b"x",
1568            &vec![0; MAX_EXTERNAL_AAD_BYTES + 1],
1569            &mut outbound_ledger()
1570        )
1571        .is_err());
1572        assert!(seal(
1573            &recipient.public(),
1574            &context(3),
1575            &vec![0; MAX_PLAINTEXT_BYTES + 1],
1576            AAD,
1577            &mut outbound_ledger()
1578        )
1579        .is_err());
1580        assert!(open(
1581            &recipient,
1582            &context(4),
1583            &vec![0; MAX_COSE_BYTES + 1],
1584            AAD,
1585            &mut inbound_ledger()
1586        )
1587        .is_err());
1588    }
1589
1590    #[test]
1591    fn prederived_outbound_burn_survives_inbound_epoch_retirement() {
1592        let key = [0x42; 32];
1593        let ctx = context(21);
1594        let mut outbound = outbound_ledger();
1595        let sealed = seal_prederived(&key, SUITE, &ctx, b"block", AAD, &mut outbound).unwrap();
1596        let mut inbound = inbound_ledger();
1597        assert_eq!(
1598            open_prederived(&key, SUITE, &ctx, &sealed, AAD, &mut inbound).unwrap(),
1599            b"block"
1600        );
1601        inbound.retire_epoch(
1602            SUITE,
1603            &ctx.recipient_id,
1604            &ctx.key_id,
1605            &ctx.nonce_domain,
1606            ctx.epoch,
1607        );
1608        assert!(inbound.is_empty());
1609        assert!(seal_prederived(&key, SUITE, &ctx, b"again", AAD, &mut outbound).is_err());
1610    }
1611
1612    #[test]
1613    fn rfc8439_chacha20poly1305_vector() {
1614        // RFC 8439 section 2.8.2.  This proves the registered content algorithm;
1615        // it is not represented as a Hyprstream/COSE interoperability vector.
1616        let key = hex::decode("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f")
1617            .unwrap();
1618        let nonce = hex::decode("070000004041424344454647").unwrap();
1619        let aad = hex::decode("50515253c0c1c2c3c4c5c6c7").unwrap();
1620        let plaintext = hex::decode(concat!(
1621            "4c616469657320616e642047656e746c656d656e206f662074686520636c61737320",
1622            "6f66202739393a204966204920636f756c64206f6666657220796f75206f6e6c7920",
1623            "6f6e652074697020666f7220746865206675747572652c2073756e73637265656e20",
1624            "776f756c642062652069742e"
1625        ))
1626        .unwrap();
1627        let expected = hex::decode(concat!(
1628            "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6",
1629            "3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36",
1630            "92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc",
1631            "3ff4def08e4b7a9de576d26586cec64b61161ae10b594f09e26a7e902ecbd060",
1632            "0691"
1633        ))
1634        .unwrap();
1635        let mut key_array = [0; 32];
1636        key_array.copy_from_slice(&key);
1637        let mut nonce_array = [0; 12];
1638        nonce_array.copy_from_slice(&nonce);
1639        assert_eq!(
1640            aead_seal(&key_array, &nonce_array, &plaintext, &aad).unwrap(),
1641            expected
1642        );
1643    }
1644
1645    #[test]
1646    fn compatibility_wrappers_remain_canonical() {
1647        let recipient = generate_recipient(SUITE).unwrap();
1648        let sealed = seal_to_recipient(&recipient.public(), b"legacy", AAD, 0, 0).unwrap();
1649        assert_eq!(
1650            open_from_recipient(&recipient, &sealed, AAD, 0, 0).unwrap(),
1651            b"legacy"
1652        );
1653    }
1654
1655    #[test]
1656    fn compatibility_wrappers_validate_before_encoding_or_crypto() {
1657        let recipient = generate_recipient(SUITE).unwrap();
1658        let oversized_aad = vec![0u8; MAX_EXTERNAL_AAD_BYTES + 1];
1659        assert!(seal_to_recipient(&recipient.public(), b"legacy", &oversized_aad, 0, 0).is_err());
1660        assert!(open_from_recipient(&recipient, &[], &oversized_aad, 0, 0).is_err());
1661
1662        let mut malformed = recipient.public();
1663        malformed.eks.push(vec![0u8; 32]);
1664        assert!(seal_to_recipient(&malformed, b"legacy", AAD, 0, 0).is_err());
1665    }
1666}