Skip to main content

capsule_core/federation/
mod.rs

1//! Aggregated federated albums — the album-group **view** (SSoT: [Federation — Federated Shared
2//! Albums] and [Organization — views]).
3//!
4//! An *aggregated album* is N ordinary container albums — one per contributor, each homed on
5//! its contributor's own server and single-writer-domain as always — that clients present as
6//! **one logical album**. There is **zero new server surface**: servers never learn a group
7//! exists. The group is client-side metadata, asserted per constituent:
8//!
9//! - The creator mints a `group_id` (UUIDv7) and shares it in the invite ([`AlbumGroupInvite`]).
10//! - Each contributor's client writes an [`AlbumGroupAssertion`] into *their own* container
11//!   album's encrypted collaborative-metadata stream (the [operation path]) — a device-signed,
12//!   AMK-sealed operation, so the assertion is never legible to any server.
13//!
14//! There is deliberately **no shared mutable group object**: a union of per-album assertions
15//! needs no cross-server consensus. The aggregate is a **computed view** ([`render_aggregate`]),
16//! holding no keys and forming no access-control boundary, exactly like every [view album].
17//!
18//! # Inclusion is injection-proof by construction
19//!
20//! A constituent appears in the local aggregate **only if** the local user is a *member* of that
21//! album (holds its AMK) **and** it asserts the `group_id` ([`Constituent::admits`]). A stranger's
22//! album cannot inject itself into anyone's view: without an invite its assertion is never even
23//! decryptable, so it is never a member; `member_hint` only tells the client where to *ask*,
24//! membership does the admitting.
25//!
26//! [Federation — Federated Shared Albums]: https://docs/design/federation/#federated-shared-albums-aggregated-albums
27//! [Organization — views]: https://docs/design/organization/#system--smart-albums-views
28//! [operation path]: https://docs/design/metadata/#how-operations-travel
29//! [view album]: https://docs/design/organization/#system--smart-albums-views
30
31use serde::{Deserialize, Serialize};
32use uuid::Uuid;
33
34use crate::ambient::IdSource;
35use crate::cbor;
36use crate::crypto::keys::{HybridSignature, HybridSigningKey, HybridVerifyingKey};
37use crate::metadata::crdt::Lww;
38
39/// A sibling/member hint: where a constituent of the group is *claimed* to live. **Advisory
40/// discovery only, never trusted** — it tells a client where to *ask* for an album, but
41/// membership (holding the AMK) is what admits a constituent into the view. A hint can name an
42/// album a stranger controls and it changes nothing: without an invite that album is not a
43/// member, so it is never rendered.
44#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
45pub struct MemberHint {
46    /// The constituent album id the hint points at.
47    pub album_id: Uuid,
48    /// The home server that album is claimed to live on.
49    pub home_server: String,
50}
51
52/// The album-group assertion — client-side group metadata, asserted **per constituent** and
53/// written into that album's collaborative-metadata stream. This type owns the schema (SSoT:
54/// [Federation — The Album-Group Assertion]).
55///
56/// The union of per-album assertions *is* the group; there is no shared mutable group object.
57/// `group_name` converges across participants by LWW exactly like `caption_lww`, so a concurrent
58/// rename on two constituents reconciles to one name regardless of arrival order.
59///
60/// [Federation — The Album-Group Assertion]: https://docs/design/federation/#the-album-group-assertion
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct AlbumGroupAssertion {
63    /// The group this constituent asserts membership of (UUIDv7, minted by the creator).
64    pub group_id: Uuid,
65    /// The group's display name — an LWW register that converges across every participant's
66    /// assertion, like `caption_lww` (SSoT: Metadata — Collaborative Metadata).
67    pub group_name: Lww<String>,
68    /// Advisory sibling hints — where the *other* constituents are claimed to live. Never
69    /// trusted for admission; only used to know where to ask.
70    pub member_hint: Vec<MemberHint>,
71    /// Device signature over the assertion's canonical bytes — the assertion is a device-signed
72    /// operation on the collaborative-metadata op path, provenance-tracked like a
73    /// `metadata-update`. `None` until [`sign`](Self::sign) is called.
74    pub signature: Option<HybridSignature>,
75}
76
77/// The signature-excluded canonical view of an assertion (what [`AlbumGroupAssertion::sign`]
78/// covers). A separate struct keeps the covered bytes byte-stable and independent of the
79/// `signature` field's presence.
80#[derive(Serialize)]
81struct AssertionSigningView<'a> {
82    group_id: &'a Uuid,
83    group_name: &'a Lww<String>,
84    member_hint: &'a [MemberHint],
85}
86
87impl AlbumGroupAssertion {
88    /// A fresh assertion for `group_id` naming the group `name` (stamped by `(ts, device)` for
89    /// LWW convergence) with the given advisory sibling hints. Unsigned — the caller
90    /// [`sign`](Self::sign)s it.
91    pub fn new(
92        group_id: Uuid,
93        name: impl Into<String>,
94        ts: impl Into<String>,
95        device: Uuid,
96        member_hint: Vec<MemberHint>,
97    ) -> Self {
98        let mut group_name = Lww::new();
99        group_name.set(name.into(), ts, device);
100        Self {
101            group_id,
102            group_name,
103            member_hint: sorted_dedup(member_hint),
104            signature: None,
105        }
106    }
107
108    /// The canonical bytes the signature covers (everything except `signature`).
109    pub fn signing_bytes(&self) -> Vec<u8> {
110        cbor::to_canonical_vec(&AssertionSigningView {
111            group_id: &self.group_id,
112            group_name: &self.group_name,
113            member_hint: &self.member_hint,
114        })
115        .expect("assertion signing view serializes")
116    }
117
118    /// Sign the assertion with the author's identity key, setting `signature`. Re-signable after
119    /// a mutation (a rename or hint merge) — the caller clears and re-signs.
120    pub fn sign(&mut self, ik: &HybridSigningKey) {
121        self.signature = None;
122        self.signature = Some(ik.sign(&self.signing_bytes()));
123    }
124
125    /// Verify the assertion's signature against the author's identity public key.
126    pub fn verify(&self, ik_public: &HybridVerifyingKey) -> bool {
127        match &self.signature {
128            Some(sig) => ik_public.verify(&self.signing_bytes(), sig),
129            None => false,
130        }
131    }
132
133    /// The converged group name, if any writer has set one.
134    pub fn name(&self) -> Option<&str> {
135        self.group_name.get().map(String::as_str)
136    }
137
138    /// Whether this assertion asserts `group_id` — the *asserts-group* half of the inclusion
139    /// rule. An assertion for a different group id (or none) never pulls its album into `group_id`'s
140    /// view.
141    pub fn asserts(&self, group_id: Uuid) -> bool {
142        self.group_id == group_id
143    }
144
145    /// Merge another constituent's assertion **for the same group** into this one: LWW-merge the
146    /// group name (rename convergence) and union the advisory sibling hints. A mismatched
147    /// `group_id` is ignored (returns `false`) — assertions for different groups never cross-talk.
148    /// The result is unsigned (the merged value is this reader's reconciled local state, not a new
149    /// authored write); [`sign`](Self::sign) before re-emitting it as an operation.
150    pub fn merge(&mut self, other: &Self) -> bool {
151        if self.group_id != other.group_id {
152            return false;
153        }
154        self.group_name.merge(&other.group_name);
155        let mut hints = std::mem::take(&mut self.member_hint);
156        hints.extend(other.member_hint.iter().cloned());
157        self.member_hint = sorted_dedup(hints);
158        self.signature = None;
159        true
160    }
161
162    /// LWW-rename the group, stamped `(ts, device)`. Clears the signature (the caller re-signs).
163    pub fn rename(&mut self, name: impl Into<String>, ts: impl Into<String>, device: Uuid) {
164        self.group_name.set(name.into(), ts, device);
165        self.signature = None;
166    }
167}
168
169/// Mint a fresh `group_id` — a UUIDv7 from `ids`, per the assertion schema. The creator mints it
170/// once and carries it in the [`AlbumGroupInvite`].
171pub fn mint_group_id(ids: IdSource<'_>) -> Uuid {
172    ids.uuid_v7()
173}
174
175/// Group-aware invite **data** riding the existing album invite: the `group_id` plus the sibling
176/// hints a joiner seeds its own assertion from. This carries the group facts as data; the
177/// interactive membership ceremony (delivering the AMK, the MLS `Welcome`) belongs to the
178/// MLS authority's membership layer and is blocked — same caveat as the organization doc's
179/// invitation surface. A joiner turns this into its own constituent's [`AlbumGroupAssertion`] with [`to_assertion`](Self::to_assertion).
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181pub struct AlbumGroupInvite {
182    /// The group being joined.
183    pub group_id: Uuid,
184    /// The group name at invite time (seeds the joiner's LWW register; later renames converge).
185    pub group_name: String,
186    /// The sibling constituents the joiner should try to read (advisory; membership still admits).
187    pub siblings: Vec<MemberHint>,
188}
189
190impl AlbumGroupInvite {
191    /// Build the assertion a joining contributor writes into **their own** constituent
192    /// (`own_album` / `own_server`): asserts the invited `group_id`, seeds the group name, and
193    /// carries the invite's siblings plus the joiner's own constituent as advisory hints. Unsigned
194    /// — the caller signs it before sealing it onto the op path.
195    pub fn to_assertion(
196        &self,
197        own_album: Uuid,
198        own_server: impl Into<String>,
199        ts: impl Into<String>,
200        device: Uuid,
201    ) -> AlbumGroupAssertion {
202        let mut hints = self.siblings.clone();
203        hints.push(MemberHint {
204            album_id: own_album,
205            home_server: own_server.into(),
206        });
207        AlbumGroupAssertion::new(self.group_id, self.group_name.clone(), ts, device, hints)
208    }
209}
210
211fn sorted_dedup(mut hints: Vec<MemberHint>) -> Vec<MemberHint> {
212    hints.sort();
213    hints.dedup();
214    hints
215}
216
217// ── The aggregate view renderer ─────────────────────────────────────────────────────────────
218//
219// The aggregate is a *computed view*: merged ordering is `capture_timestamp` with `asset_id` as
220// the tiebreak, computed at render, nothing stored — so it is idempotent under the
221// grouping-convergence requirement by definition. It holds no keys and is no access-control
222// boundary, exactly like every view album.
223
224/// One asset a constituent contributes, as the local index (or federated breadcrumb index) holds
225/// it. `capture_timestamp` is the merge-ordering key; `asset_id` breaks ties.
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct AggregateAsset {
228    /// The asset id.
229    pub asset_id: Uuid,
230    /// Capture time (Unix seconds) — the primary merge-ordering key.
231    pub capture_timestamp: i64,
232}
233
234/// One constituent album's contribution to an aggregate, as the local client sees it. Built from
235/// the local library for own albums and from a federated read for remote ones; the renderer
236/// applies the inclusion rule uniformly.
237#[derive(Debug, Clone)]
238pub struct Constituent {
239    /// The constituent album id.
240    pub album_id: Uuid,
241    /// The home server this constituent lives on (the per-origin identity).
242    pub home_server: String,
243    /// Whether the local user is a **member** (holds this album's AMK) — the admitting fact.
244    /// A non-member's assertion is undecryptable, so this is `false` and the album is dropped.
245    pub is_member: bool,
246    /// The reconciled assertion this constituent carries, if the local user can read it.
247    pub assertion: Option<AlbumGroupAssertion>,
248    /// Whether the constituent's origin is currently reachable. When `false` its entries still
249    /// render (from the local index) but are flagged degraded — nothing is removed.
250    pub reachable: bool,
251    /// Whether the viewer has moderation-**blocked** this origin. A blocked origin's constituent
252    /// is dropped from the viewer's aggregate (per-origin moderation), independently of others.
253    pub blocked: bool,
254    /// This constituent's assets, from the local index / breadcrumb index.
255    pub assets: Vec<AggregateAsset>,
256}
257
258impl Constituent {
259    /// Whether this constituent is admitted into `group_id`'s aggregate: the local user is a
260    /// member (holds the AMK) **and** the origin is not moderation-blocked **and** the constituent
261    /// asserts `group_id`. This is the injection-proof `member-of ∧ asserts-group` rule (with the
262    /// per-origin moderation drop folded in): a stranger's album — not a member — can never inject
263    /// itself, and an album that does not assert the group cannot be pulled into the view.
264    pub fn admits(&self, group_id: Uuid) -> bool {
265        self.is_member
266            && !self.blocked
267            && self.assertion.as_ref().is_some_and(|a| a.asserts(group_id))
268    }
269}
270
271/// One merged entry in the rendered aggregate. Carries its origin so a client can group by
272/// server and honor the per-origin degraded indicator.
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct AggregateEntry {
275    /// The asset id.
276    pub asset_id: Uuid,
277    /// The constituent album the asset lives in.
278    pub album_id: Uuid,
279    /// The origin server the asset is homed on.
280    pub home_server: String,
281    /// Capture time (Unix seconds) — the merge-ordering key.
282    pub capture_timestamp: i64,
283    /// `true` when this entry's origin is currently unreachable: it renders from the local index
284    /// but the client shows the per-origin "currently unavailable" indicator. Never removed.
285    pub degraded: bool,
286}
287
288/// The per-origin partial-view indicator for one included constituent. Structured data — the
289/// client formats the localized "photos from {home_server} currently unavailable" string from an
290/// i18n key; the core never carries the user-facing string.
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct OriginStatus {
293    /// The origin server.
294    pub home_server: String,
295    /// The constituent album on that origin.
296    pub album_id: Uuid,
297    /// Whether the origin is currently reachable.
298    pub reachable: bool,
299}
300
301/// The computed aggregate view over the constituents of one group. Nothing here is stored: it is
302/// recomputed at render and is identical across devices given the same inputs.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct AggregateView {
305    /// The group rendered.
306    pub group_id: Uuid,
307    /// The LWW-converged group name across every included constituent's assertion.
308    pub group_name: Option<String>,
309    /// Merged, capture-time-ordered entries (`asset_id` tiebreak) from every included
310    /// constituent — including unreachable origins, whose entries are flagged `degraded`.
311    pub entries: Vec<AggregateEntry>,
312    /// Per-origin reachability for the included constituents (the partial-view indicator).
313    pub origins: Vec<OriginStatus>,
314    /// The cover asset: the per-viewer override when it names an included asset, else the newest
315    /// included asset (max `(capture_timestamp, asset_id)`); `None` for an empty aggregate.
316    pub cover: Option<Uuid>,
317    /// `true` when at least one included origin is currently unreachable — the aggregate is a
318    /// partial view.
319    pub partial: bool,
320}
321
322/// Render the aggregate for `group_id` over `constituents`, honoring the per-viewer `cover_override`
323/// (a `group_id → asset_id` choice from the library-settings document; `None` falls back to the
324/// newest included asset).
325///
326/// Pure and deterministic: membership + assertion admit each constituent, entries merge by
327/// `(capture_timestamp, asset_id)`, and the group name is the LWW-convergence of the included
328/// assertions. Recomputation is idempotent and identical across devices (grouping-convergence).
329#[tracing::instrument(skip(constituents), fields(group_id = %group_id, constituents = constituents.len()))]
330pub fn render_aggregate(
331    group_id: Uuid,
332    constituents: &[Constituent],
333    cover_override: Option<Uuid>,
334) -> AggregateView {
335    let included: Vec<&Constituent> = constituents.iter().filter(|c| c.admits(group_id)).collect();
336
337    // LWW-converge the group name across every included assertion (rename convergence).
338    let mut name_reg: Lww<String> = Lww::new();
339    for c in &included {
340        if let Some(a) = &c.assertion {
341            name_reg.merge(&a.group_name);
342        }
343    }
344    let group_name = name_reg.get().cloned();
345
346    // Merge entries; an unreachable origin's entries render degraded, never removed.
347    let mut entries: Vec<AggregateEntry> = included
348        .iter()
349        .flat_map(|c| {
350            c.assets.iter().map(move |asset| AggregateEntry {
351                asset_id: asset.asset_id,
352                album_id: c.album_id,
353                home_server: c.home_server.clone(),
354                capture_timestamp: asset.capture_timestamp,
355                degraded: !c.reachable,
356            })
357        })
358        .collect();
359    entries.sort_by_key(|e| (e.capture_timestamp, e.asset_id));
360
361    let mut origins: Vec<OriginStatus> = included
362        .iter()
363        .map(|c| OriginStatus {
364            home_server: c.home_server.clone(),
365            album_id: c.album_id,
366            reachable: c.reachable,
367        })
368        .collect();
369    // Sort so the view is identical regardless of constituent arrival order (grouping-convergence).
370    origins.sort_by(|a, b| (&a.home_server, a.album_id).cmp(&(&b.home_server, b.album_id)));
371    let partial = origins.iter().any(|o| !o.reachable);
372
373    // Cover: the per-viewer override iff it names an included asset, else the newest included one.
374    let cover = cover_override
375        .filter(|id| entries.iter().any(|e| e.asset_id == *id))
376        .or_else(|| {
377            entries
378                .iter()
379                .max_by_key(|e| (e.capture_timestamp, e.asset_id))
380                .map(|e| e.asset_id)
381        });
382
383    AggregateView {
384        group_id,
385        group_name,
386        entries,
387        origins,
388        cover,
389        partial,
390    }
391}
392
393#[cfg(test)]
394mod tests;