Skip to main content

capsule_core/cbor/
mod.rs

1//! Canonical CBOR (RFC 8949 ยง4.2 deterministic encoding).
2//!
3//! This is the **shared, load-bearing** encoder for every byte string a signature or
4//! content hash commits to: the [sidecar](crate::sidecar), the encrypted
5//! [metadata blob](crate::crypto::encryption) plaintext, and the signed
6//! [manifests](crate::crypto::provenance). Two correct implementations MUST produce
7//! byte-identical output for the same logical document, or signatures fail to verify
8//! across peers โ€” so this module is a **blocking cross-language conformance gate**, not
9//! advisory. Conformance is pinned by the golden hex vectors in the tests below.
10//!
11//! SSoT for the ruleset: [Metadata โ€” Canonical CBOR Encoding].
12//!
13//! [Metadata โ€” Canonical CBOR Encoding]: https://docs/design/metadata/#canonical-cbor-encoding
14
15mod encode;
16mod open_map;
17
18use ciborium::value::Value;
19pub use open_map::OpenMap;
20use serde::Serialize;
21use serde::de::DeserializeOwned;
22use thiserror::Error;
23
24/// Errors from (de)serializing through the canonical codec.
25#[derive(Debug, Error)]
26pub enum CanonicalError {
27    /// The value could not be modeled as CBOR before canonicalization.
28    #[error("CBOR serialize failed: {0}")]
29    Serialize(String),
30    /// The input bytes were not valid CBOR.
31    #[error("CBOR deserialize failed: {0}")]
32    Deserialize(String),
33}
34
35/// Canonically encode an already-built CBOR [`Value`]. Infallible.
36pub fn value_to_canonical_vec(value: &Value) -> Vec<u8> {
37    let mut out = Vec::new();
38    encode::encode_value(value, &mut out);
39    out
40}
41
42/// Serialize a `T` and return its canonical CBOR bytes.
43pub fn to_canonical_vec<T: Serialize>(value: &T) -> Result<Vec<u8>, CanonicalError> {
44    Ok(value_to_canonical_vec(&to_value(value)?))
45}
46
47/// Decode CBOR bytes into a `T`. Decoding is tolerant of non-canonical input; callers
48/// that require canonical bytes re-encode via [`canonicalize`] or [`to_canonical_vec`].
49pub fn from_slice<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, CanonicalError> {
50    ciborium::de::from_reader(bytes).map_err(|e| CanonicalError::Deserialize(e.to_string()))
51}
52
53/// Re-encode arbitrary CBOR bytes into their canonical form. Used on the receive path:
54/// decode what arrived, then verify a signature against the canonical re-encoding.
55///
56/// The result is a fixed point: canonicalizing it again returns the same bytes. Input
57/// holding a negative bignum (tag 3) below `-2^127` is refused with
58/// [`CanonicalError::Deserialize`], because its canonical form is one the decoder cannot
59/// read back; the decoder already refuses that value written as a definite-length bignum,
60/// and this refuses it however else it was framed.
61pub fn canonicalize(bytes: &[u8]) -> Result<Vec<u8>, CanonicalError> {
62    let value: Value =
63        ciborium::de::from_reader(bytes).map_err(|e| CanonicalError::Deserialize(e.to_string()))?;
64    if has_unreadable_bignum(&value) {
65        return Err(CanonicalError::Deserialize(
66            "negative bignum below -2^127 is out of range".into(),
67        ));
68    }
69    Ok(value_to_canonical_vec(&value))
70}
71
72/// Whether `value` holds a tag-3 bignum whose canonical form the decoder refuses: a
73/// 16-byte magnitude with its top bit set, i.e. a value below `-2^127`, which does not fit
74/// the `i128` the decoder reads a definite-length bignum into. Larger magnitudes (more than
75/// 16 bytes) decode as an opaque tag and are not affected.
76fn has_unreadable_bignum(value: &Value) -> bool {
77    match value {
78        Value::Tag(tag, inner) => {
79            if let (encode::TAG_BIGNUM_NEG, Value::Bytes(b)) = (*tag, &**inner) {
80                let magnitude = encode::bignum_magnitude(b);
81                magnitude.len() == 16 && magnitude[0] & 0x80 != 0
82            } else {
83                has_unreadable_bignum(inner)
84            }
85        }
86        Value::Array(items) => items.iter().any(has_unreadable_bignum),
87        Value::Map(entries) => entries
88            .iter()
89            .any(|(k, v)| has_unreadable_bignum(k) || has_unreadable_bignum(v)),
90        _ => false,
91    }
92}
93
94/// Model a `T` as a CBOR [`Value`] (the intermediate non-canonical encoding is irrelevant;
95/// canonicalization happens on the way out).
96fn to_value<T: Serialize>(value: &T) -> Result<Value, CanonicalError> {
97    let mut buf = Vec::new();
98    ciborium::ser::into_writer(value, &mut buf)
99        .map_err(|e| CanonicalError::Serialize(e.to_string()))?;
100    ciborium::de::from_reader(buf.as_slice())
101        .map_err(|e| CanonicalError::Deserialize(e.to_string()))
102}
103
104#[cfg(test)]
105mod tests;