Skip to main content

capsule_core/sidecar/
stack_doc.rs

1//! `StackDocV1` — a stack's signed, versioned label record (SSoT: [Organization — Labels]).
2//!
3//! Keyed by `stack_id` and sealed under the AMK of the stack's container album — every member
4//! of a stack belongs to that one album, and the record names it so a holder knows which AMK
5//! seals it. It carries the stack's labels as an OR-set. Like the sidecar, it is CRDT fields
6//! only, its schema is field 0, and unknown keys survive under the signature.
7//!
8//! [Organization — Labels]: https://docs/design/organization/#labels
9
10use std::collections::BTreeMap;
11
12use ciborium::value::Value;
13use uuid::Uuid;
14
15use super::signed_doc::{self, DocError};
16use crate::crypto::keys::{Amk, HybridSignature, HybridSigningKey, HybridVerifyingKey};
17use crate::metadata::crdt::OrSet;
18
19/// The current stack-document schema version.
20pub const STACK_DOC_SCHEMA_V1: u16 = 1;
21
22/// A stack's signed label record.
23#[derive(Debug, Clone, PartialEq)]
24pub struct StackDocV1 {
25    /// Schema version — integer **field 0**.
26    pub stack_doc_schema: u16,
27    /// The stack this record speaks for (UUIDv7).
28    pub stack_id: Uuid,
29    /// The container album every member of the stack belongs to; its AMK seals this record.
30    pub album_id: Uuid,
31    /// The stack's labels.
32    pub labels: OrSet<String>,
33    /// Unknown CBOR keys preserved verbatim (covered by the signature).
34    pub unknown: BTreeMap<String, Value>,
35    /// Hybrid signature over every other field.
36    pub signature: Option<HybridSignature>,
37}
38
39impl StackDocV1 {
40    /// An empty, unsigned record for `stack_id` in `album_id`.
41    pub fn new(stack_id: Uuid, album_id: Uuid) -> Self {
42        Self {
43            stack_doc_schema: STACK_DOC_SCHEMA_V1,
44            stack_id,
45            album_id,
46            labels: OrSet::new(),
47            unknown: BTreeMap::new(),
48            signature: None,
49        }
50    }
51
52    fn to_entries(&self, include_signature: bool) -> Vec<(Value, Value)> {
53        let mut m = vec![
54            (
55                Value::Integer(0u8.into()),
56                Value::Integer(self.stack_doc_schema.into()),
57            ),
58            ("stack_id".into(), signed_doc::to_value(&self.stack_id)),
59            ("album_id".into(), signed_doc::to_value(&self.album_id)),
60            ("labels".into(), signed_doc::to_value(&self.labels)),
61        ];
62        for (k, v) in &self.unknown {
63            m.push((Value::Text(k.clone()), v.clone()));
64        }
65        if include_signature && let Some(sig) = &self.signature {
66            m.push(("signature".into(), signed_doc::to_value(sig)));
67        }
68        m
69    }
70
71    /// The canonical bytes the signature covers (everything except `signature`).
72    pub fn signing_bytes(&self) -> Vec<u8> {
73        signed_doc::encode(self.to_entries(false))
74    }
75
76    /// The full canonical encoding, signature included.
77    pub fn to_canonical_vec(&self) -> Vec<u8> {
78        signed_doc::encode(self.to_entries(true))
79    }
80
81    /// Sign with the user identity key.
82    pub fn sign(&mut self, ik: &HybridSigningKey) {
83        self.signature = Some(ik.sign(&self.signing_bytes()));
84    }
85
86    /// Verify against the user identity key. An unsigned record never verifies.
87    pub fn verify(&self, ik_public: &HybridVerifyingKey) -> bool {
88        self.signature
89            .as_ref()
90            .is_some_and(|sig| ik_public.verify(&self.signing_bytes(), sig))
91    }
92
93    /// Decode from canonical CBOR, refusing a schema newer than `max_known`.
94    ///
95    /// # Errors
96    ///
97    /// [`DocError::SchemaTooNew`] or [`DocError::Decode`].
98    pub fn from_canonical_slice(bytes: &[u8], max_known: u16) -> Result<Self, DocError> {
99        let (stack_doc_schema, mut fields) = signed_doc::split_fields(bytes, max_known)?;
100        let stack_id = signed_doc::take(&mut fields, "stack_id")?;
101        let album_id = signed_doc::take(&mut fields, "album_id")?;
102        let labels = signed_doc::take(&mut fields, "labels")?;
103        let signature = signed_doc::take_opt(&mut fields, "signature")?;
104        Ok(Self {
105            stack_doc_schema,
106            stack_id,
107            album_id,
108            labels,
109            unknown: fields,
110            signature,
111        })
112    }
113
114    /// Merge another replica of the same stack's record: labels by OR-set union, unknown keys
115    /// by a deterministic fold. The signature is dropped when the merge changed anything.
116    ///
117    /// # Errors
118    ///
119    /// [`DocError::IdMismatch`] when `other` speaks for another stack, or places the stack in
120    /// another album; nothing is merged.
121    pub fn merge(&mut self, other: &Self) -> Result<(), DocError> {
122        if other.stack_id != self.stack_id {
123            return Err(DocError::IdMismatch {
124                expected: self.stack_id,
125                found: other.stack_id,
126            });
127        }
128        if other.album_id != self.album_id {
129            return Err(DocError::IdMismatch {
130                expected: self.album_id,
131                found: other.album_id,
132            });
133        }
134        let before = self.signing_bytes();
135        self.labels.merge(&other.labels);
136        signed_doc::merge_unknown(&mut self.unknown, &other.unknown);
137        if self.signing_bytes() != before {
138            self.signature = None;
139        }
140        Ok(())
141    }
142
143    /// Seal the full record under `amk` (its album's current epoch) with a fresh nonce.
144    ///
145    /// # Errors
146    ///
147    /// [`DocError::Crypto`] if sealing fails.
148    pub fn seal(&self, amk: &Amk) -> Result<Vec<u8>, DocError> {
149        signed_doc::seal(amk, &self.stack_id, &self.to_canonical_vec())
150    }
151
152    /// Open a record sealed by [`seal`](Self::seal) for `stack_id`. The signature is **not**
153    /// checked here; the caller verifies against the signer it trusts.
154    ///
155    /// # Errors
156    ///
157    /// [`DocError::Crypto`] when `amk` does not open it, [`DocError::IdMismatch`] when it speaks
158    /// for another stack, and the decode errors of
159    /// [`from_canonical_slice`](Self::from_canonical_slice).
160    pub fn open_sealed(
161        wire: &[u8],
162        amk: &Amk,
163        stack_id: &Uuid,
164        max_known: u16,
165    ) -> Result<Self, DocError> {
166        let plaintext = signed_doc::open(amk, stack_id, wire)?;
167        let doc = Self::from_canonical_slice(&plaintext, max_known)?;
168        if doc.stack_id != *stack_id {
169            return Err(DocError::IdMismatch {
170                expected: *stack_id,
171                found: doc.stack_id,
172            });
173        }
174        Ok(doc)
175    }
176}
177
178#[cfg(test)]
179mod tests;