Skip to main content

capsule_core/sidecar/
album_doc.rs

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