capsule_core/sidecar/
signed_doc.rs1use 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#[derive(Debug, Error)]
28pub enum DocError {
29 #[error("document decode: {0}")]
31 Decode(String),
32 #[error("document schema {found} is newer than max known {max_known}; refusing")]
35 SchemaTooNew {
36 found: u16,
38 max_known: u16,
40 },
41 #[error("document is for {found}, expected {expected}")]
43 IdMismatch {
44 expected: Uuid,
46 found: Uuid,
48 },
49 #[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
66pub(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
98pub(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
110pub(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
121pub(crate) fn encode(entries: Vec<(Value, Value)>) -> Vec<u8> {
123 cbor::value_to_canonical_vec(&Value::Map(entries))
124}
125
126pub(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
144pub(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
150pub(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}