Skip to main content

capsule_core/cbor/
open_map.rs

1//! Decoding a signed CBOR map whose unknown keys must survive under the signature.
2//!
3//! [Versioning — invariant 2] requires every signed record to keep the keys its reader does not
4//! know, re-emit them canonically, and cover them with the signature. A record does that by
5//! carrying a `#[serde(flatten)] unknown: BTreeMap<String, Value>` (wire-absent when empty, so no
6//! existing signature moves) and a hand-written `Deserialize` built on [`OpenMap`]: it takes each
7//! known field out by name and hands back whatever is left as the unknown map.
8//!
9//! The decoder is hand-written rather than `serde(flatten)` on the way in because flatten
10//! buffers unknown values through serde's private content type, which cannot hold a CBOR tag or
11//! an integer wider than 64 bits — a future field carrying either would make the whole record
12//! undecodable instead of preserved.
13//!
14//! [Versioning — invariant 2]: https://docs/design/versioning/#system-invariants
15
16use std::collections::BTreeMap;
17
18use ciborium::value::Value;
19use serde::Deserialize;
20use serde::de::{DeserializeOwned, Error};
21
22/// A decoded text-keyed CBOR map, drained field by field into a signed record.
23#[derive(Debug)]
24pub struct OpenMap {
25    record: &'static str,
26    fields: BTreeMap<String, Value>,
27}
28
29impl OpenMap {
30    /// Decode `d` as a map with only text keys and no duplicate key. `record` names the record
31    /// in every error and log line.
32    ///
33    /// # Errors
34    ///
35    /// When the input is not a map, holds a non-text key, or repeats a key.
36    pub fn deserialize<'de, D: serde::Deserializer<'de>>(
37        record: &'static str,
38        d: D,
39    ) -> Result<Self, D::Error> {
40        let Value::Map(entries) = Value::deserialize(d)? else {
41            return Err(D::Error::custom(format!("{record} must be a map")));
42        };
43        let mut fields = BTreeMap::new();
44        for (key, value) in entries {
45            let Value::Text(key) = key else {
46                return Err(D::Error::custom(format!("{record} has only text keys")));
47            };
48            if fields.contains_key(&key) {
49                return Err(D::Error::custom(format!("duplicate {record} field {key}")));
50            }
51            fields.insert(key, value);
52        }
53        Ok(Self { record, fields })
54    }
55
56    /// Take a required field.
57    ///
58    /// # Errors
59    ///
60    /// When the key is absent or its value does not decode as `T`.
61    pub fn take<T: DeserializeOwned, E: Error>(&mut self, key: &'static str) -> Result<T, E> {
62        let value = self
63            .fields
64            .remove(key)
65            .ok_or_else(|| E::missing_field(key))?;
66        self.decode(key, value)
67    }
68
69    /// Take an optional field: an absent key and a present `null` both read as `None`.
70    ///
71    /// # Errors
72    ///
73    /// When a present, non-null value does not decode as `T`.
74    pub fn take_opt<T: DeserializeOwned, E: Error>(
75        &mut self,
76        key: &'static str,
77    ) -> Result<Option<T>, E> {
78        match self.fields.remove(key) {
79            None | Some(Value::Null) => Ok(None),
80            Some(value) => self.decode(key, value).map(Some),
81        }
82    }
83
84    /// The keys no `take` claimed: the record's unknown map, preserved verbatim.
85    #[must_use]
86    pub fn into_unknown(self) -> BTreeMap<String, Value> {
87        if !self.fields.is_empty() {
88            tracing::debug!(
89                record = self.record,
90                unknown_keys = ?self.fields.keys().collect::<Vec<_>>(),
91                "cbor: preserving keys this build does not know"
92            );
93        }
94        self.fields
95    }
96
97    fn decode<T: DeserializeOwned, E: Error>(&self, key: &str, value: Value) -> Result<T, E> {
98        value
99            .deserialized()
100            .map_err(|e| E::custom(format!("{} field {key}: {e}", self.record)))
101    }
102}
103
104#[cfg(test)]
105mod tests;