capsule_library/lifecycle/sharing.rs
1//! View-only share links — the [`ShareLinkIssuer`] half of the workspace and the scope
2//! material it encapsulates.
3
4use capsule_core::crypto::provenance::KeyMode;
5use capsule_core::sharing::{
6 LINK_SECRET_LEN, RevocationRecord, ScopeMaterial, ShareLink, ShareLinkId, ShareLinkIssuer,
7 ShareLinkRecord, SharePublication, ShareScope, SharedAsset, SharingError, encapsulate_scope,
8 generate_opaque_id, publish_share,
9};
10use capsule_core::sidecar::{ExportPrivacy, sidecar_for_export};
11use uuid::Uuid;
12
13use super::{AssetState, Workspace, asset_is_deleted, now_rfc3339};
14
15impl Workspace {
16 /// The issuer-held record for a share link, if this workspace issued it. Exposes the
17 /// authoritative scope / expiry / revocation state the serving endpoint consults.
18 pub fn share_link(&self, link: &ShareLinkId) -> Option<&ShareLinkRecord> {
19 self.share_links.get(link)
20 }
21
22 /// Resolve the scope's decryption material to encapsulate into a link. Fails with
23 /// [`SharingError::ScopeUnavailable`] if the scope is not managed by this workspace.
24 fn scope_material(
25 &self,
26 scope: ShareScope,
27 ) -> std::result::Result<ScopeMaterial, SharingError> {
28 match scope {
29 ShareScope::Asset(asset_id) => {
30 let asset = self
31 .assets
32 .get(&asset_id)
33 .ok_or(SharingError::ScopeUnavailable)?;
34 let album = self
35 .albums
36 .get(&asset.album_id)
37 .ok_or(SharingError::ScopeUnavailable)?;
38 let head = &asset
39 .chain
40 .records()
41 .last()
42 .expect("provenance chain is never empty")
43 .manifest
44 .core;
45 if !album.amks.contains_key(&head.amk_version.0) {
46 return Err(SharingError::ScopeUnavailable);
47 }
48 // Carry the head's file key, honouring its `key_mode`: a derived key is folded
49 // under the manifest's `nonce_prefix` (which the recipient re-uses to decrypt),
50 // and an adopted drop's is unwrapped from `wrapped_file_key`.
51 let file_key = self.original_file_key(album, head).map_err(|e| {
52 tracing::warn!(%asset_id, error = %e, "share link: asset file key recovery failed");
53 SharingError::Crypto("asset file key recovery failed")
54 })?;
55 Ok(ScopeMaterial::Asset {
56 file_id: asset_id,
57 file_key,
58 })
59 }
60 ShareScope::Album(album_id) => {
61 let album = self
62 .albums
63 .get(&album_id)
64 .ok_or(SharingError::ScopeUnavailable)?;
65 Ok(ScopeMaterial::Album {
66 album_id,
67 amks: album.amks.clone(),
68 })
69 }
70 }
71 }
72
73 /// The per-asset records a link over `scope` covers (#622): for each asset, the key-free
74 /// parameters a viewer needs to fetch its original's ciphertext and decrypt it under the
75 /// opened scope, read off the asset's **head** manifest and signed sidecar.
76 ///
77 /// - **Asset scope** covers that one asset. The scope material carries its file key
78 /// directly, so the record says `amk_version = 0`, `derived`, and no wrapped key, as
79 /// [`SharedAsset`] documents for an asset-scoped grant: the wrapped key would be a field the
80 /// viewer never reads.
81 /// - **Album scope** covers every asset in the album that is not in trash, in asset-id order
82 /// so the same album publishes the same record. Each keeps its manifest's epoch, key mode
83 /// and wrapped key, because the viewer recovers the file key from the grant's AMKs.
84 ///
85 /// An asset in trash is not shareable: asset scope refuses it with
86 /// [`SharingError::ScopeUnavailable`], and album scope leaves it out.
87 ///
88 /// Each record carries the asset's sidecar as it may cross the boundary: the
89 /// [Privacy on Export] strip ([`sidecar_for_export`]) under `privacy`, the per-export
90 /// choice the caller passes for this one link. The workspace never stores it, and its own
91 /// sidecar is untouched.
92 ///
93 /// # Errors
94 ///
95 /// [`SharingError::ScopeUnavailable`] when the scope is not managed by this workspace, or an
96 /// asset-scoped asset is in trash.
97 ///
98 /// [Privacy on Export]: https://docs/design/metadata/#privacy-on-export
99 pub fn shared_assets(
100 &self,
101 scope: ShareScope,
102 privacy: ExportPrivacy,
103 ) -> std::result::Result<Vec<SharedAsset>, SharingError> {
104 let record = |asset: &AssetState, grant: Grant| {
105 let head = &asset
106 .chain
107 .records()
108 .last()
109 .expect("provenance chain is never empty")
110 .manifest
111 .core;
112 let (amk_version, key_mode, wrapped_file_key) = match grant {
113 Grant::FileKey => (0, KeyMode::Derived, None),
114 Grant::Amks => (
115 head.amk_version.0,
116 head.key_mode,
117 head.wrapped_file_key.clone(),
118 ),
119 };
120 SharedAsset {
121 asset_id: asset.asset_id,
122 content_hash: head.ciphertext_hash,
123 content_type: asset.sidecar.content_type.clone(),
124 size: head.plaintext_size,
125 amk_version,
126 nonce_prefix: head.nonce_prefix,
127 key_mode,
128 wrapped_file_key,
129 sidecar: Some(sidecar_for_export(&asset.sidecar, privacy).to_canonical_vec()),
130 }
131 };
132 match scope {
133 ShareScope::Asset(asset_id) => {
134 let asset = self
135 .assets
136 .get(&asset_id)
137 .ok_or(SharingError::ScopeUnavailable)?;
138 if asset_is_deleted(asset) {
139 tracing::info!(%asset_id, "share link: an asset in trash is not shareable");
140 return Err(SharingError::ScopeUnavailable);
141 }
142 Ok(vec![record(asset, Grant::FileKey)])
143 }
144 ShareScope::Album(album_id) => {
145 if !self.albums.contains_key(&album_id) {
146 return Err(SharingError::ScopeUnavailable);
147 }
148 let mut covered: Vec<&AssetState> = self
149 .assets
150 .values()
151 .filter(|asset| asset.album_id == album_id && !asset_is_deleted(asset))
152 .collect();
153 covered.sort_by_key(|asset| asset.asset_id);
154 Ok(covered
155 .into_iter()
156 .map(|asset| record(asset, Grant::Amks))
157 .collect())
158 }
159 }
160 }
161
162 /// Everything the server needs to serve `link` (#622): the sealed `share-metadata/v1`
163 /// record over [`shared_assets`](Self::shared_assets), its content address, the `serves`
164 /// set, and for a passphrase link the wrapped secret — [`publish_share`] under the link's
165 /// own fragment, opaque id, scope encapsulation and expiry.
166 ///
167 /// The record is sealed with a fresh nonce on every call, so two calls for one link yield
168 /// two different `metadata_hash`es; publish once per link and register what that call
169 /// returned.
170 ///
171 /// `privacy` is this export's [Privacy on Export] choice: every covered sidecar is stripped
172 /// under it before the record is sealed, so the blob the server stores is already stripped.
173 /// [`ExportPrivacy::default`] strips every row; an opt-in applies to this link only and is
174 /// never stored.
175 ///
176 /// # Errors
177 ///
178 /// What [`shared_assets`](Self::shared_assets) and [`publish_share`] return.
179 ///
180 /// [Privacy on Export]: https://docs/design/metadata/#privacy-on-export
181 #[tracing::instrument(skip(self, link), fields(opaque_id = %link.opaque_id_hex()))]
182 pub fn publish_link(
183 &self,
184 link: &ShareLink,
185 privacy: ExportPrivacy,
186 ) -> std::result::Result<SharePublication, SharingError> {
187 if privacy != ExportPrivacy::default() {
188 tracing::info!(
189 ?privacy,
190 "share link: the issuer opted in to retain metadata"
191 );
192 }
193 let assets = self.shared_assets(link.scope, privacy)?;
194 let covered = assets.len();
195 let publication = publish_share(
196 &link.wrapped_scope,
197 &link.fragment_secret,
198 &link.opaque_id,
199 link.expires_at.clone(),
200 assets,
201 )?;
202 tracing::info!(
203 covered,
204 serves = publication.serves.len(),
205 passphrase = link.is_passphrase_protected(),
206 "share link: metadata record published"
207 );
208 Ok(publication)
209 }
210}
211
212/// How a link's scope material yields a covered asset's file key, which decides what that
213/// asset's [`SharedAsset`] record must carry.
214#[derive(Clone, Copy)]
215enum Grant {
216 /// The material is the file key itself (an asset-scoped grant).
217 FileKey,
218 /// The material is the album's AMK ledger, from which the viewer recovers the key.
219 Amks,
220}
221
222impl ShareLinkIssuer for Workspace {
223 /// Issue a view-only share link: resolve the scope's decryption material, encapsulate
224 /// it around a fresh CSPRNG link secret (and, if a passphrase is given, an Argon2id
225 /// layer on top), draw a 128-bit opaque id, and record the link for revocation. The
226 /// fragment secret is returned to the caller and never persisted server-side.
227 fn create_link(
228 &mut self,
229 scope: ShareScope,
230 expires_at: Option<String>,
231 passphrase: Option<&str>,
232 ) -> std::result::Result<ShareLink, SharingError> {
233 let material = self.scope_material(scope)?;
234 let fragment_secret = capsule_core::crypto::rng::random_array::<LINK_SECRET_LEN>();
235 let opaque_id = generate_opaque_id();
236 let wrapped_scope = encapsulate_scope(
237 &material,
238 &fragment_secret,
239 &opaque_id,
240 passphrase,
241 self.argon2_params,
242 )?;
243 let link_id = ShareLinkId(Uuid::now_v7());
244 let created_at = now_rfc3339();
245 self.share_links.insert(
246 link_id,
247 ShareLinkRecord {
248 link_id,
249 opaque_id,
250 scope,
251 wrapped_scope: wrapped_scope.clone(),
252 expires_at: expires_at.clone(),
253 created_at,
254 revocation: None,
255 },
256 );
257 Ok(ShareLink {
258 link_id,
259 opaque_id,
260 scope,
261 fragment_secret,
262 wrapped_scope,
263 expires_at,
264 })
265 }
266
267 /// Publish a revocation record for `link`; the serve path then refuses it. Revoking an
268 /// unknown link is [`SharingError::NotFound`]; revoking an already-revoked link is
269 /// idempotent (the original revocation timestamp is kept).
270 fn revoke_link(&mut self, link: ShareLinkId) -> std::result::Result<(), SharingError> {
271 let record = self
272 .share_links
273 .get_mut(&link)
274 .ok_or(SharingError::NotFound)?;
275 if record.revocation.is_none() {
276 record.revocation = Some(RevocationRecord {
277 link_id: link,
278 revoked_at: now_rfc3339(),
279 });
280 }
281 Ok(())
282 }
283}
284
285#[cfg(test)]
286mod tests;