Skip to main content

capsule_core/sidecar/
export.rs

1//! [Metadata — Privacy on Export]: what leaves the library when a sidecar crosses a trust
2//! boundary.
3//!
4//! [`sidecar_for_export`] applies every row of the privacy table to a copy of the sidecar:
5//!
6//! - **Camera serial**: the serial of `camera_id` is emptied; the model stays.
7//! - **Device identifier**: `device_id` becomes the nil UUID, and so does every other place a
8//!   device id travels: the `by` stamp of every last-writer-wins register (superseded entries
9//!   included) and the add-ids of every OR-set, which are re-issued under the nil device. An
10//!   OR-set keeps only its live elements, so no tombstone carries a device id either.
11//! - **Session id**: `session_id` becomes the nil UUID.
12//! - **Edit history**: the `superseded` log of every last-writer-wins register (prior
13//!   captions, ratings, capture times, cull and hidden flags, stack memberships, locations and
14//!   region versions) is emptied; only each register's current value leaves. A caption the
15//!   user rewrote to remove a name must not reach the recipient in its old form.
16//! - **GPS**: the as-imported `gps` and every value in the user's `gps_user` register,
17//!   superseded ones included when the history is kept, is rounded to 2 decimal places (≈1 km).
18//! - **Personal contact tags and image regions**: a face is matched to a person only as a
19//!   labelled region, so `regions` is removed whole, and that one strip covers both rows.
20//!
21//! Each row is kept only when the user opts in for that one export through [`ExportPrivacy`],
22//! never through a sticky setting. Keys this reader does not know (`unknown`) are always
23//! dropped: a field a newer schema added may itself be a boundary-crossing field, and a copy
24//! that cannot tell must not carry it.
25//!
26//! Stripping produces a copy; the library's own sidecar is untouched.
27//!
28//! [Metadata — Privacy on Export]: https://docs/design/metadata/#privacy-on-export
29
30use uuid::Uuid;
31
32use super::{Gps, SidecarV1};
33use crate::metadata::crdt::{AddId, Lww, OrSet};
34
35/// The per-export privacy choices, one per row of the privacy table. [`Default`] is the strict
36/// choice: everything stripped.
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub struct ExportPrivacy {
39    /// Keep image regions and their labels, the personal contact tags among them.
40    pub retain_regions: bool,
41    /// Keep GPS coordinates at full precision instead of rounding them to 2 decimal places.
42    pub retain_full_gps: bool,
43    /// Keep the camera serial number.
44    pub retain_camera_serial: bool,
45    /// Keep the importing device id and the device of every register stamp and OR-set add.
46    pub retain_device_ids: bool,
47    /// Keep the import session id.
48    pub retain_session_id: bool,
49    /// Keep the superseded log of every last-writer-wins register: the values an edit
50    /// displaced.
51    pub retain_superseded: bool,
52}
53
54impl ExportPrivacy {
55    /// The opt-in that keeps every row: a copy that differs from the library's only in the
56    /// keys this reader does not know.
57    pub const RETAIN_ALL: Self = Self {
58        retain_regions: true,
59        retain_full_gps: true,
60        retain_camera_serial: true,
61        retain_device_ids: true,
62        retain_session_id: true,
63        retain_superseded: true,
64    };
65}
66
67/// Decimal places an exported coordinate keeps by default (≈1 km).
68const EXPORT_GPS_DECIMALS: i32 = 2;
69
70/// Round one coordinate to [`EXPORT_GPS_DECIMALS`] places.
71fn round_coordinate(value: f64) -> f64 {
72    let scale = 10f64.powi(EXPORT_GPS_DECIMALS);
73    (value * scale).round() / scale
74}
75
76/// Round `gps` in place; `true` when either coordinate changed.
77fn round_fix(gps: &mut Gps) -> bool {
78    let (lat, lon) = (round_coordinate(gps.lat), round_coordinate(gps.lon));
79    let changed = lat.to_bits() != gps.lat.to_bits() || lon.to_bits() != gps.lon.to_bits();
80    gps.lat = lat;
81    gps.lon = lon;
82    changed
83}
84
85/// Replace the writing device of every stamp in `register` with the nil UUID; `true` when one
86/// changed.
87fn anonymize_register<T: Clone + PartialEq>(register: &mut Lww<T>) -> bool {
88    let mut changed = false;
89    for stamped in register.current.iter_mut().chain(&mut register.superseded) {
90        if !stamped.by.is_nil() {
91            stamped.by = Uuid::nil();
92            changed = true;
93        }
94    }
95    changed
96}
97
98/// Re-issue the live elements of `set` under the nil device, dropping its tombstones; `true`
99/// when the copy differs from `set`.
100fn anonymize_or_set<T: Ord + Clone>(set: &mut OrSet<T>) -> bool {
101    let mut out = OrSet::new();
102    for (counter, (_, element)) in (0u64..).zip(set.entries()) {
103        out.add(
104            element,
105            AddId {
106                device: Uuid::nil(),
107                counter,
108            },
109        );
110    }
111    let changed = out != *set;
112    *set = out;
113    changed
114}
115
116/// Empty the superseded log of `register`; the number of entries removed.
117fn clear_history<T: Clone + PartialEq>(register: &mut Lww<T>) -> usize {
118    let removed = register.superseded.len();
119    register.superseded.clear();
120    removed
121}
122
123/// Empty the superseded log of every register `out` carries; the number of entries removed.
124fn clear_every_history(out: &mut SidecarV1) -> usize {
125    let mut removed = clear_history(&mut out.capture_timestamp_user);
126    removed += clear_history(&mut out.caption);
127    removed += clear_history(&mut out.rating);
128    removed += clear_history(&mut out.stack_membership);
129    removed += clear_history(&mut out.cull);
130    removed += clear_history(&mut out.hidden);
131    removed += clear_history(&mut out.gps_user);
132    for register in out.regions.values_mut() {
133        removed += clear_history(register);
134    }
135    removed
136}
137
138/// Strip every device id `out` carries; `true` when one was present.
139fn strip_device_ids(out: &mut SidecarV1) -> bool {
140    let mut changed = !out.device_id.is_nil();
141    out.device_id = Uuid::nil();
142    changed |= anonymize_register(&mut out.capture_timestamp_user);
143    changed |= anonymize_register(&mut out.caption);
144    changed |= anonymize_register(&mut out.rating);
145    changed |= anonymize_register(&mut out.stack_membership);
146    changed |= anonymize_register(&mut out.cull);
147    changed |= anonymize_register(&mut out.hidden);
148    changed |= anonymize_register(&mut out.gps_user);
149    changed |= anonymize_or_set(&mut out.tags_user);
150    changed |= anonymize_or_set(&mut out.tags_ai);
151    for register in out.regions.values_mut() {
152        changed |= anonymize_register(register);
153        let stamps = register.current.iter_mut().chain(&mut register.superseded);
154        for region in stamps.filter_map(|stamped| stamped.value.as_mut()) {
155            changed |= anonymize_or_set(&mut region.labels);
156        }
157    }
158    changed
159}
160
161/// Round every coordinate `out` carries; the number of fixes that changed.
162fn round_every_fix(out: &mut SidecarV1) -> usize {
163    let user = out
164        .gps_user
165        .current
166        .iter_mut()
167        .chain(&mut out.gps_user.superseded);
168    out.gps
169        .iter_mut()
170        .chain(user.filter_map(|stamped| stamped.value.as_mut()))
171        .map(round_fix)
172        .filter(|changed| *changed)
173        .count()
174}
175
176/// The copy of `sidecar` that may cross a trust boundary under `privacy`.
177///
178/// When anything is stripped the copy is returned **unsigned**: the library signature covered
179/// the removed fields, so it no longer verifies. When nothing is stripped the copy keeps its
180/// signature. Under the [`Default`] choice the device and session ids are always stripped, so
181/// a strict copy is always unsigned.
182#[tracing::instrument(level = "debug", skip_all, fields(asset_id = %sidecar.uuid))]
183pub fn sidecar_for_export(sidecar: &SidecarV1, privacy: ExportPrivacy) -> SidecarV1 {
184    let mut out = sidecar.clone();
185    let mut stripped = false;
186    if !out.unknown.is_empty() {
187        tracing::debug!(
188            keys = out.unknown.len(),
189            "export: unknown sidecar keys dropped"
190        );
191        out.unknown.clear();
192        stripped = true;
193    }
194    if !privacy.retain_regions && !out.regions.is_empty() {
195        tracing::debug!(
196            regions = out.regions.len(),
197            "export: image regions stripped"
198        );
199        out.regions.clear();
200        stripped = true;
201    }
202    if !privacy.retain_superseded {
203        let removed = clear_every_history(&mut out);
204        if removed > 0 {
205            tracing::debug!(removed, "export: superseded register values stripped");
206            stripped = true;
207        }
208    }
209    if !privacy.retain_full_gps {
210        let rounded = round_every_fix(&mut out);
211        if rounded > 0 {
212            tracing::debug!(rounded, "export: GPS coordinates rounded");
213            stripped = true;
214        }
215    }
216    if !privacy.retain_camera_serial
217        && let Some(camera) = out.camera_id.as_mut()
218        && !camera.serial.is_empty()
219    {
220        tracing::debug!("export: camera serial stripped");
221        camera.serial.clear();
222        stripped = true;
223    }
224    if !privacy.retain_device_ids && strip_device_ids(&mut out) {
225        tracing::debug!("export: device ids stripped");
226        stripped = true;
227    }
228    if !privacy.retain_session_id && !out.session_id.is_nil() {
229        tracing::debug!("export: session id stripped");
230        out.session_id = Uuid::nil();
231        stripped = true;
232    }
233    if stripped {
234        out.signature = None;
235    }
236    tracing::trace!(stripped, "export: sidecar copy prepared");
237    out
238}
239
240#[cfg(test)]
241mod tests;