capsule_library/lifecycle/groups.rs
1//! Aggregated federated albums — album-group assertions, their AMK-sealed op path,
2//! and the local constituent view. The only `lifecycle` file that reaches [`capsule_core::federation`].
3
4use capsule_core::cbor;
5use capsule_core::crypto::encryption::{blob_nonce, open_blob, seal_metadata_blob};
6use capsule_core::crypto::keys::Amk;
7use capsule_core::federation::{
8 AggregateAsset, AlbumGroupAssertion, AlbumGroupInvite, Constituent, MemberHint, mint_group_id,
9};
10use uuid::Uuid;
11
12use super::{LifecycleError, Result, Workspace, asset_is_deleted, now_rfc3339};
13
14impl Workspace {
15 // ── Aggregated federated albums ──────────────────────────────────────
16 //
17 // An album-group assertion is written into *this* workspace's own container album's
18 // collaborative-metadata stream — a device-signed operation, AMK-sealed so no server ever
19 // learns a group exists (zero new server surface). Reading the *other* constituents rides
20 // the existing per-album feed/pull; the aggregate itself is a computed view.
21 // SSoT: [Federation — Federated Shared Albums].
22 //
23 // [Federation — Federated Shared Albums]: https://docs/design/federation/#federated-shared-albums-aggregated-albums
24
25 /// Create an aggregated album by minting a fresh `group_id` and writing this workspace's own
26 /// `album_id` constituent's [`AlbumGroupAssertion`] (device-signed, stamped for LWW
27 /// convergence). Returns the [`AlbumGroupInvite`] the creator hands to contributors — the
28 /// `group_id` plus the creator's own constituent as a sibling hint. The interactive
29 /// membership ceremony is not performed here; this produces the invite *data*.
30 /// `home_server` is this constituent's origin identity.
31 #[tracing::instrument(skip(self), fields(album_id = %album_id))]
32 pub fn create_album_group(
33 &mut self,
34 album_id: Uuid,
35 group_name: &str,
36 home_server: &str,
37 ) -> Result<AlbumGroupInvite> {
38 self.album(&album_id)?; // must be an album this workspace holds keys for.
39 let group_id = mint_group_id(crate::ambient::system_ids());
40 let mut assertion = AlbumGroupAssertion::new(
41 group_id,
42 group_name,
43 now_rfc3339(),
44 self.account.device.device_id,
45 vec![MemberHint {
46 album_id,
47 home_server: home_server.to_string(),
48 }],
49 );
50 assertion.sign(&self.account.user_ik);
51 self.group_assertions.insert(album_id, assertion);
52 tracing::info!(%group_id, "album-group: created");
53 Ok(AlbumGroupInvite {
54 group_id,
55 group_name: group_name.to_string(),
56 siblings: vec![MemberHint {
57 album_id,
58 home_server: home_server.to_string(),
59 }],
60 })
61 }
62
63 /// Join an existing group as a contributor: write this workspace's own `album_id` constituent's
64 /// assertion (asserting the invite's `group_id`, seeded with the invite's siblings + this
65 /// constituent), device-signed. Rides the existing album invite as data; the
66 /// membership ceremony itself is not performed here. `home_server` is this constituent's
67 /// origin.
68 #[tracing::instrument(skip(self, invite), fields(album_id = %album_id, group_id = %invite.group_id))]
69 pub fn join_album_group(
70 &mut self,
71 album_id: Uuid,
72 invite: &AlbumGroupInvite,
73 home_server: &str,
74 ) -> Result<()> {
75 self.album(&album_id)?;
76 let mut assertion = invite.to_assertion(
77 album_id,
78 home_server,
79 now_rfc3339(),
80 self.account.device.device_id,
81 );
82 assertion.sign(&self.account.user_ik);
83 self.group_assertions.insert(album_id, assertion);
84 tracing::info!("album-group: joined");
85 Ok(())
86 }
87
88 /// LWW-rename the group on this workspace's own `album_id` constituent (a fresh stamped write),
89 /// re-signing the assertion. Concurrent renames on sibling constituents converge by LWW.
90 pub fn rename_album_group(&mut self, album_id: Uuid, new_name: &str) -> Result<()> {
91 let device = self.account.device.device_id;
92 let ts = now_rfc3339();
93 let assertion = self.group_assertions.get_mut(&album_id).ok_or_else(|| {
94 LifecycleError::NotFound(format!("group assertion for album {album_id}"))
95 })?;
96 assertion.rename(new_name, ts, device);
97 let assertion = self
98 .group_assertions
99 .get_mut(&album_id)
100 .expect("assertion present above");
101 assertion.sign(&self.account.user_ik);
102 Ok(())
103 }
104
105 /// Fold a peer constituent's assertion (read from the feed for `their_album_id`) into the
106 /// reconciled local view: LWW-converges the group name and unions the advisory hints. If the
107 /// local user already holds a reconciled assertion for that album it merges in place; otherwise
108 /// the peer assertion is adopted verbatim. A peer assertion for a *different* group than an
109 /// existing local one is refused (no cross-talk). Returns whether it was applied.
110 pub fn merge_album_group_assertion(
111 &mut self,
112 their_album_id: Uuid,
113 remote: &AlbumGroupAssertion,
114 ) -> bool {
115 if let Some(local) = self.group_assertions.get_mut(&their_album_id) {
116 local.merge(remote)
117 } else {
118 self.group_assertions.insert(their_album_id, remote.clone());
119 true
120 }
121 }
122
123 /// Leave the group from this workspace's `album_id` constituent: **remove the assertion**, so
124 /// the constituent drops out of every participant's aggregate on their next sync. Optionally
125 /// `unshare` (bump the AMK epoch + rotate the write tier) to cut read access to the historical
126 /// photos too — the honest limitation being that this only stops others from seeing *your*
127 /// photos, never removes anyone else's constituent (a true group kick is the v2 problem).
128 /// Returns whether an assertion was present to remove.
129 #[tracing::instrument(skip(self), fields(album_id = %album_id, unshare))]
130 pub fn leave_album_group(&mut self, album_id: Uuid, unshare: bool) -> Result<bool> {
131 let removed = self.group_assertions.remove(&album_id).is_some();
132 if unshare {
133 self.rotate_epoch(album_id)?;
134 }
135 tracing::info!(removed, "album-group: left");
136 Ok(removed)
137 }
138
139 /// The reconciled group assertion for `album_id`, if the workspace holds one.
140 pub fn album_group_assertion(&self, album_id: &Uuid) -> Option<&AlbumGroupAssertion> {
141 self.group_assertions.get(album_id)
142 }
143
144 /// Seal `album_id`'s current group assertion into the AMK-sealed operation the op path carries
145 /// — the wire bytes a server stores. AEAD-encrypted under the album's current-epoch AMK, so the
146 /// server (and any non-member) learns nothing of the group: the plaintext `group_id`/name never
147 /// appears in these bytes. This is the write half of the op path.
148 pub fn seal_album_group_op(&self, album_id: &Uuid) -> Result<Vec<u8>> {
149 let assertion = self.group_assertions.get(album_id).ok_or_else(|| {
150 LifecycleError::NotFound(format!("group assertion for album {album_id}"))
151 })?;
152 let album = self.album(album_id)?;
153 let amk = Amk::from_bytes(album.amks[&album.current_epoch]);
154 let plaintext =
155 cbor::to_canonical_vec(assertion).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
156 let (wire, _key) = seal_metadata_blob(&amk, album_id, &plaintext, None)?;
157 Ok(wire)
158 }
159
160 /// Open an AMK-sealed group-assertion operation for `album_id` — the read half. Requires the
161 /// album's AMK: a non-member (no AMK) physically cannot decrypt, which is exactly why a
162 /// stranger's assertion can never inject itself into the view. Restricted to the current epoch.
163 pub fn open_album_group_op(&self, album_id: &Uuid, wire: &[u8]) -> Result<AlbumGroupAssertion> {
164 let album = self.album(album_id)?;
165 let amk = Amk::from_bytes(album.amks[&album.current_epoch]);
166 let nonce = blob_nonce(wire)
167 .ok_or_else(|| LifecycleError::Cbor("group-op wire too short".into()))?;
168 let blob_key = amk.derive_blob_key(album_id, &nonce);
169 let plaintext = open_blob(&blob_key, wire)?;
170 cbor::from_slice(&plaintext).map_err(|e| LifecycleError::Cbor(e.to_string()))
171 }
172
173 /// Build the [`Constituent`] view of one of this workspace's own albums for the aggregate
174 /// renderer: it is a member (holds the AMK), carries its reconciled assertion (if any), and
175 /// contributes its non-trashed assets keyed by capture time. `reachable` / `blocked` are the
176 /// per-origin flags the caller supplies (own albums are normally reachable + unblocked).
177 pub fn local_constituent(
178 &self,
179 album_id: Uuid,
180 home_server: &str,
181 reachable: bool,
182 blocked: bool,
183 ) -> Constituent {
184 let assets = self
185 .assets
186 .values()
187 .filter(|a| a.album_id == album_id && !asset_is_deleted(a))
188 .map(|a| AggregateAsset {
189 asset_id: a.asset_id,
190 capture_timestamp: a.capture_utc,
191 })
192 .collect();
193 Constituent {
194 album_id,
195 home_server: home_server.to_string(),
196 is_member: true,
197 assertion: self.group_assertions.get(&album_id).cloned(),
198 reachable,
199 blocked,
200 assets,
201 }
202 }
203}
204
205#[cfg(test)]
206mod tests;