capsule_core/sidecar/sidecar_v1.rs
1//! The CBOR sidecar schema v1 — the canonical, plaintext-local-only, **signed** metadata
2//! record for an asset (SSoT: [Metadata — Sidecar Schema v1]).
3//!
4//! It is self-describing: `sidecar_schema` is **CBOR field 0** (an integer map key, which
5//! sorts before every text key in canonical order), so a reader detects a schema it does
6//! not implement before parsing the rest. The signature covers every byte including the
7//! preserved `_unknown` map, so stripping unknown fields invalidates it.
8//!
9//! [Metadata — Sidecar Schema v1]: https://docs/design/metadata/#sidecar-schema-v1
10
11use std::collections::BTreeMap;
12
13use ciborium::value::Value;
14use serde::{Deserialize, Serialize};
15use uuid::Uuid;
16
17use super::region::Regions;
18use crate::cbor;
19use crate::crypto::hash::Hash32;
20use crate::crypto::keys::{HybridSignature, HybridSigningKey, HybridVerifyingKey};
21use crate::domain::{GpsDatum, StackType};
22use crate::metadata::crdt::{Lww, OrSet};
23
24/// The current sidecar schema version.
25pub const SIDECAR_SCHEMA_V1: u16 = 1;
26
27/// Pixel dimensions.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct Dimensions {
30 /// Width in pixels.
31 pub width: u32,
32 /// Height in pixels.
33 pub height: u32,
34}
35
36/// Low-quality image placeholder (image-derived; lives in the encrypted sidecar).
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct Lqip {
39 /// Chromahash bytes.
40 #[serde(with = "serde_bytes")]
41 pub chromahash: Vec<u8>,
42 /// LQIP format version.
43 pub format_version: u16,
44 /// Dominant color (RGB).
45 pub dominant_color: [u8; 3],
46}
47
48/// Camera identifier (fingerprinting surface — stripped on export by default).
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub struct CameraId {
51 /// Camera model.
52 pub model: String,
53 /// Per-device serial number.
54 pub serial: String,
55}
56
57/// The source of a GPS fix (closed enum per protocol version).
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "kebab-case")]
60pub enum GpsSource {
61 /// From the file's EXIF.
62 Exif,
63 /// User-entered.
64 Manual,
65 /// Derived (e.g. from a nearby asset).
66 Derived,
67}
68
69/// Geolocation, stored **verbatim in the datum the source supplied** (SSoT:
70/// [Metadata — Geolocation]). Never converted at rest; datum-tagged by [`datum`](Gps::datum).
71///
72/// [Metadata — Geolocation]: https://docs/design/metadata/#geolocation
73#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
74pub struct Gps {
75 /// Latitude, in [`datum`](Gps::datum).
76 pub lat: f64,
77 /// Longitude, in [`datum`](Gps::datum).
78 pub lon: f64,
79 /// Provenance of the fix.
80 pub source: GpsSource,
81 /// The coordinate datum `lat`/`lon` are expressed in. **Wire-absent when
82 /// [`Wgs84`](GpsDatum::Wgs84)** (the default): a `Wgs84` fix omits this key so every
83 /// pre-`datum` sidecar and known-answer vector stays byte-identical, and a `gps` value
84 /// with no `datum` key decodes back to `Wgs84`. Additive optional key within sidecar
85 /// schema v1 — no `sidecar_schema` bump. `datum` travels with `lat`/`lon` in one
86 /// atomic `gps` write, so no CRDT merge rule changes.
87 #[serde(default, skip_serializing_if = "GpsDatum::is_wgs84")]
88 pub datum: GpsDatum,
89}
90
91/// An AI-suggested tag (kept in a structurally separate OR-set from user tags).
92#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
93pub struct AiTag {
94 /// The tag text.
95 pub tag: String,
96 /// The model that produced it.
97 pub model_id: String,
98 /// The model version.
99 pub model_version: String,
100}
101
102/// Role of an asset within a stack.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(rename_all = "kebab-case")]
105pub enum StackRole {
106 /// The stack's representative ("best photo").
107 Primary,
108 /// An ordinary member.
109 Member,
110 /// A proxy/optimized variant.
111 Proxy,
112}
113
114/// Stack grouping for this asset (metadata-only; never touches asset bytes).
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116pub struct StackMembership {
117 /// The stack id (UUIDv7).
118 pub stack_id: Uuid,
119 /// Closed stack-type enum.
120 pub stack_type: StackType,
121 /// This asset's role in the stack.
122 pub role: StackRole,
123 /// Ordering within the stack (burst sequence, chapter index).
124 pub member_index: Option<u32>,
125}
126
127/// Trinary culling flag (owner: Asset Organization — Culling). `Neutral` is the
128/// never-flagged state and the wire-absent default.
129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "kebab-case")]
131pub enum CullFlag {
132 /// Marked as a keeper.
133 Pick,
134 /// Not yet culled either way (default).
135 #[default]
136 Neutral,
137 /// Marked for rejection (filtered out, candidate for batch delete).
138 Reject,
139}
140
141/// The signed CBOR sidecar v1.
142#[derive(Debug, Clone, PartialEq)]
143pub struct SidecarV1 {
144 /// Schema version — serialized as integer **field 0** (sorts first canonically).
145 pub sidecar_schema: u16,
146 /// Matches the asset's manifest.
147 pub crypto_suite_id: u16,
148 /// Asset id (UUIDv7).
149 pub uuid: Uuid,
150 /// Canonical plaintext digest.
151 pub hash: Hash32,
152 /// RFC3339 capture time **as imported**: what the original's own metadata (or the
153 /// exporter's record it was folded with) said when the asset entered the library. A
154 /// user's correction never overwrites it; it lands in
155 /// [`capture_timestamp_user`](Self::capture_timestamp_user), and
156 /// [`effective_capture_timestamp`](Self::effective_capture_timestamp) is the instant the
157 /// asset is dated by.
158 pub capture_timestamp: String,
159 /// The user's capture-time correction: an LWW register over an RFC3339 instant, written by
160 /// `Workspace::set_capture_timestamp`. Wire-absent when never written, so every sidecar
161 /// without a correction encodes byte-identically to before the field existed; an older
162 /// reader keeps it verbatim as an unknown key.
163 pub capture_timestamp_user: Lww<String>,
164 /// RFC3339 import time.
165 pub import_timestamp: String,
166 /// Closed content-type string per protocol version.
167 pub content_type: String,
168 /// Pixel dimensions, if known.
169 pub dimensions: Option<Dimensions>,
170 /// Display placeholder.
171 pub lqip: Option<Lqip>,
172 /// User tags (OR-set).
173 pub tags_user: OrSet<String>,
174 /// AI tags (separate OR-set; cannot overwrite user tags).
175 pub tags_ai: OrSet<AiTag>,
176 /// Caption LWW register (with superseded log).
177 pub caption: Lww<String>,
178 /// Rating LWW register.
179 pub rating: Lww<u8>,
180 /// Stack membership: an LWW register over `Option<StackMembership>` so stack
181 /// edits (join, move, leave = `None`) converge order-independently under the
182 /// same `(ts, device_id)` rule as caption/rating — grouping is convergent by
183 /// construction, not convention. Wire-absent default = the never-written
184 /// register (distinct from an explicit removal, which is a stamped `None`).
185 pub stack_membership: Lww<Option<StackMembership>>,
186 /// Labelled image regions: region id (UUIDv7) to its register, a stamped `None` being a
187 /// deleted region (owner: [Organization — Labels]). Merged by
188 /// [`merge_regions`](super::merge_regions), not as plain LWW. Wire-absent when empty, so
189 /// every sidecar without regions encodes byte-identically to before the field existed; an
190 /// older reader keeps it verbatim as an unknown key.
191 ///
192 /// [Organization — Labels]: https://docs/design/organization/#labels
193 pub regions: Regions,
194 /// Culling flag: LWW register over the trinary [`CullFlag`]. Wire-absent
195 /// default = never flagged (`Neutral`).
196 pub cull: Lww<CullFlag>,
197 /// Hidden flag: LWW register; hidden assets are excluded from default views
198 /// (owner: Asset Organization — Hidden Assets). Wire-absent default = visible.
199 pub hidden: Lww<bool>,
200 /// Camera identifier (export-stripped).
201 pub camera_id: Option<CameraId>,
202 /// Importing device id (UUIDv4; export-stripped).
203 pub device_id: Uuid,
204 /// Importing session id (UUIDv7; export-stripped).
205 pub session_id: Uuid,
206 /// Geolocation **as imported** (export-rounded). A user's location edit never overwrites
207 /// it; it lands in [`gps_user`](Self::gps_user), and
208 /// [`effective_gps`](Self::effective_gps) is the location the asset is placed at.
209 pub gps: Option<Gps>,
210 /// The user's location edit: an LWW register over `Option<Gps>`, written by
211 /// `Workspace::set_location` with [`GpsSource::Manual`]. A stamped `None` is an explicit
212 /// "no location", which hides an as-imported fix without erasing it. Wire-absent when never
213 /// written (export-rounded like `gps`).
214 pub gps_user: Lww<Option<Gps>>,
215 /// The **prior** provenance head — the record *preceding* the write that seals this sidecar,
216 /// always equal to that write's manifest `prior_provenance_hash` (SSoT:
217 /// [Metadata — Provenance Binding and Sealing Order]). Referencing the prior head (not the
218 /// sealing write's own record) keeps the binding well-founded — the manifest commits to this
219 /// sidecar's `metadata_blob_hash`, so a sidecar referencing that manifest would be a cycle.
220 /// Wire-absent (`None`) exactly on the initial `create`.
221 ///
222 /// [Metadata — Provenance Binding and Sealing Order]: https://docs/design/metadata/#provenance-binding-and-sealing-order
223 pub provenance_chain_hash: Option<Hash32>,
224 /// Unknown CBOR keys preserved verbatim (re-sorted canonically; covered by signature).
225 pub unknown: BTreeMap<String, Value>,
226 /// Hybrid signature over every byte above (the canonical map minus this field).
227 pub signature: Option<HybridSignature>,
228}
229
230fn to_value<T: Serialize>(v: &T) -> Value {
231 let mut buf = Vec::new();
232 ciborium::ser::into_writer(v, &mut buf).expect("sidecar field serializes");
233 ciborium::de::from_reader(buf.as_slice()).expect("sidecar field re-reads")
234}
235
236fn from_value<T: for<'de> Deserialize<'de>>(v: Value) -> Result<T, String> {
237 let mut buf = Vec::new();
238 ciborium::ser::into_writer(&v, &mut buf).map_err(|e| e.to_string())?;
239 ciborium::de::from_reader(buf.as_slice()).map_err(|e| e.to_string())
240}
241
242impl SidecarV1 {
243 /// Build the CBOR map (as ordered entries) with `sidecar_schema` at integer key 0 and
244 /// every other field under a text key. If `include_signature`, the `signature` entry is
245 /// appended (used for the full record; excluded for signing bytes).
246 fn to_entries(&self, include_signature: bool) -> Vec<(Value, Value)> {
247 let mut m: Vec<(Value, Value)> = Vec::new();
248 // Field 0: schema version (integer key — sorts before all text keys).
249 m.push((
250 Value::Integer(0u8.into()),
251 Value::Integer(self.sidecar_schema.into()),
252 ));
253
254 macro_rules! put {
255 ($k:literal, $v:expr) => {
256 m.push((Value::Text($k.to_string()), to_value(&$v)));
257 };
258 }
259 macro_rules! put_opt {
260 ($k:literal, $v:expr) => {
261 if let Some(inner) = &$v {
262 m.push((Value::Text($k.to_string()), to_value(inner)));
263 }
264 };
265 }
266 put!("crypto_suite_id", self.crypto_suite_id);
267 put!("uuid", self.uuid);
268 put!("hash", self.hash);
269 put!("capture_timestamp", self.capture_timestamp);
270 if self.capture_timestamp_user != Lww::default() {
271 put!("capture_timestamp_user", self.capture_timestamp_user);
272 }
273 put!("import_timestamp", self.import_timestamp);
274 put!("content_type", self.content_type);
275 put_opt!("dimensions", self.dimensions);
276 put_opt!("lqip", self.lqip);
277 put!("tags_user", self.tags_user);
278 put!("tags_ai", self.tags_ai);
279 put!("caption", self.caption);
280 put!("rating", self.rating);
281 // Wire-absent default: a never-written register is omitted so pre-existing
282 // sidecars (and stackless assets) encode byte-identically.
283 if self.stack_membership != Lww::default() {
284 put!("stack_membership", self.stack_membership);
285 }
286 if !self.regions.is_empty() {
287 put!("regions", self.regions);
288 }
289 if self.cull != Lww::default() {
290 put!("cull", self.cull);
291 }
292 if self.hidden != Lww::default() {
293 put!("hidden", self.hidden);
294 }
295 put_opt!("camera_id", self.camera_id);
296 put!("device_id", self.device_id);
297 put!("session_id", self.session_id);
298 put_opt!("gps", self.gps);
299 if self.gps_user != Lww::default() {
300 put!("gps_user", self.gps_user);
301 }
302 // Wire-absent on the initial create (no prior head); present on every later write.
303 put_opt!("provenance_chain_hash", self.provenance_chain_hash);
304
305 // Merge preserved unknown fields (canonical encode re-sorts everything).
306 for (k, v) in &self.unknown {
307 m.push((Value::Text(k.clone()), v.clone()));
308 }
309 if include_signature && let Some(sig) = &self.signature {
310 m.push((Value::Text("signature".to_string()), to_value(sig)));
311 }
312 m
313 }
314
315 /// The capture instant the asset is dated by: the user's correction when one was ever
316 /// written, else the as-imported [`capture_timestamp`](Self::capture_timestamp).
317 pub fn effective_capture_timestamp(&self) -> &str {
318 self.capture_timestamp_user
319 .get()
320 .map_or(self.capture_timestamp.as_str(), String::as_str)
321 }
322
323 /// The location the asset is placed at: the user's edit when one was ever written (a
324 /// stamped `None` meaning "no location"), else the as-imported [`gps`](Self::gps).
325 pub fn effective_gps(&self) -> Option<&Gps> {
326 match self.gps_user.get() {
327 Some(user) => user.as_ref(),
328 None => self.gps.as_ref(),
329 }
330 }
331
332 /// The canonical bytes the signature covers (everything except `signature`).
333 pub fn signing_bytes(&self) -> Vec<u8> {
334 cbor::value_to_canonical_vec(&Value::Map(self.to_entries(false)))
335 }
336
337 /// The full canonical CBOR encoding (including the signature, if present).
338 pub fn to_canonical_vec(&self) -> Vec<u8> {
339 cbor::value_to_canonical_vec(&Value::Map(self.to_entries(true)))
340 }
341
342 /// Sign the sidecar with the user IK, setting `signature`.
343 pub fn sign(&mut self, ik: &HybridSigningKey) {
344 self.signature = Some(ik.sign(&self.signing_bytes()));
345 }
346
347 /// Verify the sidecar's signature against the user IK public key.
348 pub fn verify(&self, ik_public: &HybridVerifyingKey) -> bool {
349 match &self.signature {
350 Some(sig) => ik_public.verify(&self.signing_bytes(), sig),
351 None => false,
352 }
353 }
354
355 /// The highest `add_id.counter` `device` has written into any `AddId`-bearing OR-set of this
356 /// sidecar — user tags, AI tags, and every region's labels, live or deleted — or `None` if it
357 /// wrote none. The floor a restarting device reseeds its counter from.
358 pub fn max_add_counter_for(&self, device: &Uuid) -> Option<u64> {
359 let regions = self.regions.values().flat_map(|register| {
360 register
361 .current
362 .iter()
363 .chain(register.superseded.iter())
364 .filter_map(|stamped| stamped.value.as_ref())
365 .filter_map(|region| region.labels.max_add_counter_for(device))
366 });
367 [
368 self.tags_user.max_add_counter_for(device),
369 self.tags_ai.max_add_counter_for(device),
370 ]
371 .into_iter()
372 .flatten()
373 .chain(regions)
374 .max()
375 }
376
377 /// Decode a sidecar from canonical CBOR bytes, refusing a schema newer than `max_known`
378 /// ([Schema Versioning Rules]: an old client must not strip-and-resign a newer sidecar).
379 ///
380 /// [Schema Versioning Rules]: https://docs/design/metadata/#schema-versioning-rules
381 pub fn from_canonical_slice(bytes: &[u8], max_known: u16) -> Result<Self, String> {
382 let value: Value =
383 ciborium::de::from_reader(bytes).map_err(|e| format!("cbor decode: {e}"))?;
384 let Value::Map(entries) = value else {
385 return Err("sidecar must be a CBOR map".into());
386 };
387
388 let mut schema: Option<u16> = None;
389 let mut text: BTreeMap<String, Value> = BTreeMap::new();
390 for (k, v) in entries {
391 match k {
392 Value::Integer(i) if i128::from(i) == 0 => {
393 schema = Some(from_value::<u16>(v)?);
394 }
395 Value::Text(key) => {
396 text.insert(key, v);
397 }
398 _ => return Err("unexpected sidecar map key".into()),
399 }
400 }
401 let sidecar_schema = schema.ok_or("missing sidecar_schema (field 0)")?;
402 if sidecar_schema > max_known {
403 return Err(format!(
404 "sidecar_schema {sidecar_schema} newer than max known {max_known}; refusing"
405 ));
406 }
407
408 macro_rules! req {
409 ($k:literal, $t:ty) => {
410 from_value::<$t>(text.remove($k).ok_or(concat!("missing field: ", $k))?)?
411 };
412 }
413 macro_rules! opt {
414 ($k:literal, $t:ty) => {
415 match text.remove($k) {
416 None | Some(Value::Null) => None,
417 Some(v) => Some(from_value::<$t>(v)?),
418 }
419 };
420 }
421
422 let crypto_suite_id = req!("crypto_suite_id", u16);
423 let uuid = req!("uuid", Uuid);
424 let hash = req!("hash", Hash32);
425 let capture_timestamp = req!("capture_timestamp", String);
426 let capture_timestamp_user = match text.remove("capture_timestamp_user") {
427 None | Some(Value::Null) => Lww::new(),
428 Some(v) => from_value::<Lww<String>>(v)?,
429 };
430 let import_timestamp = req!("import_timestamp", String);
431 let content_type = req!("content_type", String);
432 let dimensions = opt!("dimensions", Dimensions);
433 let lqip = opt!("lqip", Lqip);
434 let tags_user = req!("tags_user", OrSet<String>);
435 let tags_ai = req!("tags_ai", OrSet<AiTag>);
436 let caption = req!("caption", Lww<String>);
437 let rating = req!("rating", Lww<u8>);
438 let stack_membership = match text.remove("stack_membership") {
439 None | Some(Value::Null) => Lww::new(),
440 Some(v) => from_value::<Lww<Option<StackMembership>>>(v)?,
441 };
442 let regions = match text.remove("regions") {
443 None | Some(Value::Null) => Regions::new(),
444 Some(v) => from_value::<Regions>(v)?,
445 };
446 let cull = match text.remove("cull") {
447 None | Some(Value::Null) => Lww::new(),
448 Some(v) => from_value::<Lww<CullFlag>>(v)?,
449 };
450 let hidden = match text.remove("hidden") {
451 None | Some(Value::Null) => Lww::new(),
452 Some(v) => from_value::<Lww<bool>>(v)?,
453 };
454 let camera_id = opt!("camera_id", CameraId);
455 let device_id = req!("device_id", Uuid);
456 let session_id = req!("session_id", Uuid);
457 let gps = opt!("gps", Gps);
458 let gps_user = match text.remove("gps_user") {
459 None | Some(Value::Null) => Lww::new(),
460 Some(v) => from_value::<Lww<Option<Gps>>>(v)?,
461 };
462 let provenance_chain_hash = opt!("provenance_chain_hash", Hash32);
463 let signature = opt!("signature", HybridSignature);
464
465 Ok(SidecarV1 {
466 sidecar_schema,
467 crypto_suite_id,
468 uuid,
469 hash,
470 capture_timestamp,
471 capture_timestamp_user,
472 import_timestamp,
473 content_type,
474 dimensions,
475 lqip,
476 tags_user,
477 tags_ai,
478 caption,
479 rating,
480 stack_membership,
481 regions,
482 cull,
483 hidden,
484 camera_id,
485 device_id,
486 session_id,
487 gps,
488 gps_user,
489 provenance_chain_hash,
490 unknown: text, // whatever remains is unknown — preserved verbatim
491 signature,
492 })
493 }
494}
495
496#[cfg(test)]
497mod tests;