Skip to main content

capsule_core/sidecar/
signed_doc.rs

1//! What the signed organization documents ([`StackDocV1`](super::StackDocV1) and
2//! [`AlbumDocV1`](super::AlbumDocV1)) share with the sidecar (SSoT: [Organization — Labels]):
3//! the schema version as integer **field 0**, every other field under a text key, unknown keys
4//! preserved verbatim under the signature, and sealing under the album's AMK in the
5//! [metadata-blob wire format] with the document's own id as the blob id.
6//!
7//! A sealed document and an asset's metadata blob derive their keys the same way. What stops one
8//! being presented as the other is the payload itself: each decodes only as its own schema and
9//! verifies only under its own signature.
10//!
11//! [Organization — Labels]: https://docs/design/organization/#labels
12//! [metadata-blob wire format]: https://docs/design/cryptography/encryption/#metadata-blob-wire-format
13
14use std::collections::BTreeMap;
15
16use ciborium::value::Value;
17use serde::{Deserialize, Serialize};
18use thiserror::Error;
19use uuid::Uuid;
20
21use crate::cbor;
22use crate::crypto::CryptoError;
23use crate::crypto::encryption::{blob_nonce, open_blob, seal_metadata_blob};
24use crate::crypto::keys::Amk;
25
26/// Why a signed organization document could not be decoded or opened.
27#[derive(Debug, Error)]
28pub enum DocError {
29    /// The bytes are not a well-formed document.
30    #[error("document decode: {0}")]
31    Decode(String),
32    /// The document's schema is newer than this build knows; it is refused rather than
33    /// stripped and re-signed.
34    #[error("document schema {found} is newer than max known {max_known}; refusing")]
35    SchemaTooNew {
36        /// The schema the document declares.
37        found: u16,
38        /// The newest schema this build implements.
39        max_known: u16,
40    },
41    /// The document speaks for another id than the one it was filed or sealed under.
42    #[error("document is for {found}, expected {expected}")]
43    IdMismatch {
44        /// The id the caller expected.
45        expected: Uuid,
46        /// The id the document carries.
47        found: Uuid,
48    },
49    /// Sealing or opening failed.
50    #[error(transparent)]
51    Crypto(#[from] CryptoError),
52}
53
54pub(crate) fn to_value<T: Serialize>(v: &T) -> Value {
55    let mut buf = Vec::new();
56    ciborium::ser::into_writer(v, &mut buf).expect("document field serializes");
57    ciborium::de::from_reader(buf.as_slice()).expect("document field re-reads")
58}
59
60pub(crate) fn from_value<T: for<'de> Deserialize<'de>>(v: Value) -> Result<T, DocError> {
61    let mut buf = Vec::new();
62    ciborium::ser::into_writer(&v, &mut buf).map_err(|e| DocError::Decode(e.to_string()))?;
63    ciborium::de::from_reader(buf.as_slice()).map_err(|e| DocError::Decode(e.to_string()))
64}
65
66/// Split a document into its field-0 schema and its text-keyed fields, refusing a schema newer
67/// than `max_known` before anything else is parsed.
68pub(crate) fn split_fields(
69    bytes: &[u8],
70    max_known: u16,
71) -> Result<(u16, BTreeMap<String, Value>), DocError> {
72    let value: Value = ciborium::de::from_reader(bytes)
73        .map_err(|e| DocError::Decode(format!("cbor decode: {e}")))?;
74    let Value::Map(entries) = value else {
75        return Err(DocError::Decode("document must be a CBOR map".into()));
76    };
77    let mut schema: Option<u16> = None;
78    let mut text = BTreeMap::new();
79    for (k, v) in entries {
80        match k {
81            Value::Integer(i) if i128::from(i) == 0 => schema = Some(from_value(v)?),
82            Value::Text(key) => {
83                text.insert(key, v);
84            }
85            _ => return Err(DocError::Decode("unexpected document map key".into())),
86        }
87    }
88    let schema = schema.ok_or_else(|| DocError::Decode("missing schema (field 0)".into()))?;
89    if schema > max_known {
90        return Err(DocError::SchemaTooNew {
91            found: schema,
92            max_known,
93        });
94    }
95    Ok((schema, text))
96}
97
98/// Remove and decode a required field.
99pub(crate) fn take<T: for<'de> Deserialize<'de>>(
100    fields: &mut BTreeMap<String, Value>,
101    key: &str,
102) -> Result<T, DocError> {
103    from_value(
104        fields
105            .remove(key)
106            .ok_or_else(|| DocError::Decode(format!("missing field: {key}")))?,
107    )
108}
109
110/// Remove and decode an optional field (absent or `null` is `None`).
111pub(crate) fn take_opt<T: for<'de> Deserialize<'de>>(
112    fields: &mut BTreeMap<String, Value>,
113    key: &str,
114) -> Result<Option<T>, DocError> {
115    match fields.remove(key) {
116        None | Some(Value::Null) => Ok(None),
117        Some(v) => from_value(v).map(Some),
118    }
119}
120
121/// Canonical encoding of a document's ordered entries.
122pub(crate) fn encode(entries: Vec<(Value, Value)>) -> Vec<u8> {
123    cbor::value_to_canonical_vec(&Value::Map(entries))
124}
125
126/// Fold `other`'s preserved unknown keys into `local`. Keys only one side holds are kept; where
127/// both hold a key with different values, the value with the greater canonical encoding wins,
128/// so the fold is commutative, associative and idempotent like the CRDT fields beside it.
129pub(crate) fn merge_unknown(local: &mut BTreeMap<String, Value>, other: &BTreeMap<String, Value>) {
130    for (key, theirs) in other {
131        match local.get(key) {
132            None => {
133                local.insert(key.clone(), theirs.clone());
134            }
135            Some(ours) => {
136                if cbor::value_to_canonical_vec(theirs) > cbor::value_to_canonical_vec(ours) {
137                    local.insert(key.clone(), theirs.clone());
138                }
139            }
140        }
141    }
142}
143
144/// Seal `plaintext` under `amk` with a fresh nonce, `id` as the blob id.
145pub(crate) fn seal(amk: &Amk, id: &Uuid, plaintext: &[u8]) -> Result<Vec<u8>, DocError> {
146    let (wire, _key) = seal_metadata_blob(amk, id, plaintext, None)?;
147    Ok(wire)
148}
149
150/// Open a document sealed by [`seal`].
151pub(crate) fn open(amk: &Amk, id: &Uuid, wire: &[u8]) -> Result<Vec<u8>, DocError> {
152    let nonce =
153        blob_nonce(wire).ok_or_else(|| DocError::Decode("sealed document too short".into()))?;
154    Ok(open_blob(&amk.derive_blob_key(id, &nonce), wire)?)
155}