capsule_sdk/albums.rs
1//! Album provisioning — telling the server an album exists.
2//!
3//! A container album's id is **derived from the account master key**
4//! ([Organization — The Default Album]), so the client knows it before the server does. This
5//! module is the one call that closes that gap: `POST /v1/albums` binds the derived UUID to
6//! the authenticated owner, so [invariant 6] ("album exists; the caller has write capability
7//! on it") can pass for an album the client named. Every push runs it first —
8//! [`crate::push::ensure_album`] is the step, this module is the wire.
9//!
10//! **Idempotent, and that is the whole point.** The same id arrives from every device the
11//! user owns, and again after a passphrase recovery on a fresh one. Re-provisioning is a
12//! success that writes nothing (`created: false`), so a client needs no
13//! "have I registered this album yet?" flag — which is precisely the synced pointer the
14//! master-key derivation exists to avoid. Pushing twice therefore cannot error here.
15//!
16//! **No name crosses the wire.** The request body carries the id and nothing else; album
17//! titles live in the encrypted sidecar and the server is not entitled to them.
18//!
19//! **Lifecycle ops ride here too.** [`AlbumClient::apply_op`] sends one signed `delete`,
20//! `trash-restore` or other bytes-free lifecycle manifest to `POST /v1/albums/{album_id}/ops`
21//! and types the refusal ([`LifecycleOpError`]), so every client tells a closed retention window
22//! (`retention_elapsed`, final for the asset) from a stale chain or a transient fault the same
23//! way. The op's envelope ([`op_envelope`]), which records of a chain go to the server
24//! ([`chain_after`], [`stretch_after`]), and when they are held instead ([`plan_delivery`]) are
25//! defined here once, for every client that sends one.
26//!
27//! [Organization — The Default Album]: https://docs/design/organization/#the-default-album
28//! [invariant 6]: https://docs/design/threat-model/validation/#server-side-validation-invariants
29
30use serde::{Deserialize, Serialize};
31use tracing::instrument;
32use uuid::Uuid;
33
34mod op_wire;
35
36pub use op_wire::{
37 HeldDelivery, HoldReason, chain_after, judging_clock, op_envelope, plan_delivery, stretch_after,
38};
39
40pub use crate::upload::StaticToken;
41
42// ─── Errors ───────────────────────────────────────────────────────────────────
43
44/// A failure on the album surface: provisioning, or publishing a roster.
45#[derive(Debug, thiserror::Error)]
46pub enum AlbumError {
47 /// The HTTP request failed on the wire, or the session could not authorize it.
48 #[error("album request transport: {0}")]
49 Transport(String),
50 /// The server refused the request.
51 #[error("album request refused with status {status}")]
52 Status {
53 /// The HTTP status code.
54 status: u16,
55 /// The stable `error.*` code, when the server supplied one.
56 code: Option<String>,
57 /// On either roster-version refusal — the `409 error.album.roster_stale` that is behind
58 /// the server, and the `400 error.album.roster_version_leap` that is too far ahead of it
59 /// — the version the server holds, which is the one a caller re-signs above. Absent on
60 /// every other refusal.
61 current_version: Option<u64>,
62 },
63 /// The response body was missing a field or otherwise unparsable.
64 #[error("malformed album response: {0}")]
65 Malformed(String),
66 /// The server will not take this client's writes: its `426`, or a window it advertised
67 /// that already refuses this build (issue #674). Update the app.
68 #[error(transparent)]
69 UpgradeRequired(Box<crate::net::negotiation::UpgradeRequired>),
70}
71
72impl AlbumError {
73 /// The stable `error.*` code the server attached to a refusal, when there is one.
74 /// Callers switch on this, never on the bare status.
75 #[must_use]
76 pub fn error_code(&self) -> Option<&str> {
77 match self {
78 AlbumError::Status { code, .. } => code.as_deref(),
79 AlbumError::UpgradeRequired(refusal) => Some(refusal.error_code()),
80 _ => None,
81 }
82 }
83}
84
85impl From<crate::auth::AuthError> for AlbumError {
86 fn from(err: crate::auth::AuthError) -> Self {
87 match err {
88 crate::auth::AuthError::UpgradeRequired(refusal) => {
89 AlbumError::UpgradeRequired(refusal)
90 }
91 other => AlbumError::Transport(other.to_string()),
92 }
93 }
94}
95
96impl From<crate::net::negotiation::SendError> for AlbumError {
97 fn from(err: crate::net::negotiation::SendError) -> Self {
98 match err {
99 crate::net::negotiation::SendError::Upgrade(refusal) => {
100 AlbumError::UpgradeRequired(Box::new(refusal))
101 }
102 crate::net::negotiation::SendError::Transport(error) => {
103 AlbumError::Transport(error.to_string())
104 }
105 }
106 }
107}
108
109// ─── Authorized transport ─────────────────────────────────────────────────────
110
111#[derive(Clone)]
112enum AlbumAuth {
113 /// Drive requests through the SDK session (pre-flight refresh, single-flight, one
114 /// `401` refresh-and-replay).
115 Session(crate::auth::Session),
116 /// A fixed bearer over a plain client (tests).
117 Static {
118 http: reqwest::Client,
119 token: String,
120 },
121}
122
123/// The authorized HTTP transport for the album surface: the album endpoint root (no trailing
124/// slash — `POST {base}` provisions) plus the authorization seam.
125#[derive(Clone)]
126pub struct AlbumTransport {
127 base_url: String,
128 auth: AlbumAuth,
129}
130
131impl AlbumTransport {
132 /// Build a transport that authorizes through an authenticated
133 /// [`Session`](crate::auth::Session) — the sanctioned production path. `base_url` is the
134 /// album endpoint root (`{origin}/v1/albums`).
135 pub fn with_session(session: crate::auth::Session, base_url: impl Into<String>) -> Self {
136 Self {
137 base_url: base_url.into().trim_end_matches('/').to_string(),
138 auth: AlbumAuth::Session(session),
139 }
140 }
141
142 /// Build a transport over a fixed bearer token (tests; callers holding a live token).
143 /// Same URL layout as [`Self::with_session`].
144 ///
145 /// `http` **must** come from [`crate::net::http_builder`] or [`crate::net::http_client`]: a
146 /// client built any other way sends no protocol handshake, and every gated route refuses it.
147 pub fn with_static_token(
148 http: reqwest::Client,
149 base_url: impl Into<String>,
150 token: StaticToken,
151 ) -> Self {
152 Self {
153 base_url: base_url.into().trim_end_matches('/').to_string(),
154 auth: AlbumAuth::Static {
155 http,
156 token: token.0,
157 },
158 }
159 }
160
161 async fn send<F>(&self, build: F) -> Result<reqwest::Response, AlbumError>
162 where
163 F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
164 {
165 match &self.auth {
166 AlbumAuth::Session(session) => Ok(session.execute(build).await?),
167 AlbumAuth::Static { http, token } => Ok(crate::net::negotiation::send_negotiated(
168 build(http).bearer_auth(token),
169 )
170 .await?),
171 }
172 }
173
174 /// A `spargen`-generated client for the API root this transport's album endpoint hangs off,
175 /// carrying the same credential.
176 ///
177 /// The roster publish goes through this rather than through [`Self::send`]: everything that
178 /// parses or serializes in this repository is generated, and `publish_album_roster` is a
179 /// JSON operation the document fully describes — request body, success body, and the
180 /// `409`/`400` problem shapes with their extension members. Only `provision` still hand-writes
181 /// its DTOs, and only because `POST /v1/albums` predates this seam.
182 ///
183 /// The root is derived by trimming the endpoint's `/v1/albums` suffix, because the generated
184 /// operations carry their own absolute paths while this transport is constructed with the
185 /// album endpoint (`{origin}/v1/albums`) that `POST {base}` provisions against.
186 fn generated(&self) -> Result<crate::rest::Client, AlbumError> {
187 let root = self
188 .base_url
189 .strip_suffix("/v1/albums")
190 .unwrap_or(&self.base_url);
191 let (http, credential) = match &self.auth {
192 AlbumAuth::Session(session) => {
193 let session = session.clone();
194 // The session's own pre-flight refresh and single-flight coalescing, consulted
195 // per request; the reactive `401` replay is the caller's, below.
196 let provider: crate::rest::TokenProvider = std::sync::Arc::new(move || {
197 let session = session.clone();
198 Box::pin(async move {
199 session
200 .bearer()
201 .await
202 .map_err(|error| crate::rest::AuthError::new(error.to_string()))
203 })
204 });
205 (
206 crate::net::http_client()
207 .map_err(|error| AlbumError::Transport(error.to_string()))?,
208 crate::client::Bearer::Provider(provider),
209 )
210 }
211 AlbumAuth::Static { http, token } => {
212 (http.clone(), crate::client::Bearer::Token(token.clone()))
213 }
214 };
215 Ok(credential
216 .attach(crate::client::negotiated_client(http, root).map_err(AlbumError::Transport)?))
217 }
218}
219
220// ─── Wire DTOs (mirror the server's transport JSON) ───────────────────────────
221
222/// The `POST /v1/albums` request body. One field, deliberately: the server's body is strict,
223/// and an album *name* is not something it is entitled to.
224#[derive(Debug, Clone, Serialize)]
225struct ProvisionAlbumRequestWire {
226 album_id: String,
227}
228
229#[derive(Debug, Clone, Deserialize)]
230struct ProvisionAlbumResponseWire {
231 album_id: String,
232 created: bool,
233}
234
235/// The one field `provision` reads off a refusal. The roster publish reads its problems through
236/// the generated client's typed error instead, which is why nothing here describes extensions.
237#[derive(Deserialize)]
238struct ApiErrorWire {
239 #[serde(default)]
240 code: Option<String>,
241}
242
243/// What provisioning an album resolved to. Both cases are successes; `created` is
244/// informational — a caller treats a fresh binding and an existing one identically.
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct ProvisionedAlbum {
247 /// The album id the server bound, echoed back.
248 pub album_id: Uuid,
249 /// `true` when this call created the binding, `false` when it already existed.
250 pub created: bool,
251}
252
253/// What the server holds for an album after a roster publish.
254///
255/// `replayed` is informational: the same bytes again are a success that wrote nothing, exactly
256/// as re-provisioning is, so a client that lost an acknowledgement re-PUTs without branching.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct PublishedRoster {
259 /// The album, echoed.
260 pub album_id: Uuid,
261 /// The roster version the server holds after this call.
262 pub roster_version: u64,
263 /// The AMK epoch that roster reflects.
264 pub amk_epoch: u64,
265 /// How many members it names, the owner excluded.
266 pub member_count: u64,
267 /// Whether this call replayed the roster already held.
268 pub replayed: bool,
269}
270
271// ─── Client ───────────────────────────────────────────────────────────────────
272
273/// The album-provisioning client.
274pub struct AlbumClient {
275 transport: AlbumTransport,
276}
277
278impl AlbumClient {
279 /// Build a client over an authorized [`AlbumTransport`].
280 #[must_use]
281 pub fn new(transport: AlbumTransport) -> Self {
282 Self { transport }
283 }
284
285 /// Register `album_id` with the server, binding it to the authenticated caller.
286 ///
287 /// Idempotent: calling it again with the same id succeeds and writes nothing. The id is
288 /// sent in its canonical lowercase hyphenated form, which is the only spelling the server
289 /// stores, so two devices can never produce two rows for one album.
290 #[instrument(skip(self), fields(album_id = %album_id))]
291 pub async fn provision(&self, album_id: Uuid) -> Result<ProvisionedAlbum, AlbumError> {
292 let body = ProvisionAlbumRequestWire {
293 album_id: album_id.hyphenated().to_string(),
294 };
295 let url = self.transport.base_url.clone();
296 let response = self
297 .transport
298 .send(|http| http.post(&url).json(&body))
299 .await?;
300
301 let status = response.status();
302 if !status.is_success() {
303 let code = response
304 .json::<ApiErrorWire>()
305 .await
306 .ok()
307 .and_then(|e| e.code);
308 tracing::warn!(
309 status = status.as_u16(),
310 ?code,
311 "album provisioning refused"
312 );
313 return Err(AlbumError::Status {
314 status: status.as_u16(),
315 code,
316 current_version: None,
317 });
318 }
319
320 let wire: ProvisionAlbumResponseWire = response
321 .json()
322 .await
323 .map_err(|e| AlbumError::Malformed(e.to_string()))?;
324 let echoed = Uuid::parse_str(&wire.album_id)
325 .map_err(|e| AlbumError::Malformed(format!("response album_id: {e}")))?;
326 if echoed != album_id {
327 return Err(AlbumError::Malformed(format!(
328 "server echoed album {echoed}, not the requested {album_id}"
329 )));
330 }
331 tracing::info!(created = wire.created, "album provisioned");
332 Ok(ProvisionedAlbum {
333 album_id: echoed,
334 created: wire.created,
335 })
336 }
337
338 /// Publish `signed` as the roster of the album it names.
339 ///
340 /// Orchestration only, and deliberately thin: the roster is signed in
341 /// `capsule_core::crypto::membership` by one of the owner's devices, base64-encoded, and
342 /// handed to the **generated** `publish_album_roster` operation, so every byte that is
343 /// parsed or serialized on this path comes from the committed OpenAPI document. Idempotent
344 /// under `(album_id, roster_version)`: the same bytes again succeed with `replayed`.
345 ///
346 /// Two refusals a caller acts on: a `409` (`error.album.roster_stale`) means the server holds
347 /// a roster this one does not supersede, and a `400 error.album.roster_version_leap` means
348 /// the version is too far *ahead* of the held one. Both carry
349 /// [`current_version`](AlbumError::Status), and the repair for both is the same — re-sign the
350 /// roster one above it.
351 ///
352 /// Under a session, a `401` is refreshed once and replayed, exactly as the sync feed does:
353 /// the credential provider's pre-flight refresh cannot cover a token revoked mid-flight.
354 ///
355 /// # Errors
356 ///
357 /// [`AlbumError::Transport`] when the request did not complete, [`AlbumError::Status`] with
358 /// the server's `error.*` code when it was refused, [`AlbumError::Malformed`] when the roster
359 /// could not be encoded or the response could not be read.
360 #[instrument(skip(self, signed), fields(album_id = %signed.roster.album_id, roster_version = signed.roster.roster_version))]
361 pub async fn publish_roster(
362 &self,
363 signed: &capsule_core::crypto::membership::SignedAlbumRoster,
364 ) -> Result<PublishedRoster, AlbumError> {
365 use base64::Engine as _;
366
367 let album_id = signed.roster.album_id;
368 let bytes = capsule_core::cbor::to_canonical_vec(signed)
369 .map_err(|e| AlbumError::Malformed(format!("roster encoding: {e}")))?;
370 let body = crate::rest::types::RosterRequest {
371 roster_cbor: base64::engine::general_purpose::STANDARD.encode(bytes),
372 };
373
374 let client = self.transport.generated()?;
375 let wire = match publish(&client, album_id, &body).await {
376 Ok(wire) => wire,
377 Err(error) if is_unauthenticated(&error) => match &self.transport.auth {
378 AlbumAuth::Session(session) => {
379 tracing::info!("the roster publish answered 401; refreshing once and retrying");
380 session.refresh().await?;
381 publish(&client, album_id, &body)
382 .await
383 .map_err(publish_refusal)?
384 }
385 // A fixed token cannot be refreshed, so retrying would ask the same question
386 // twice.
387 AlbumAuth::Static { .. } => return Err(publish_refusal(error)),
388 },
389 Err(error) => return Err(publish_refusal(error)),
390 };
391
392 let echoed = Uuid::parse_str(&wire.album_id)
393 .map_err(|e| AlbumError::Malformed(format!("response album_id: {e}")))?;
394 if echoed != album_id {
395 return Err(AlbumError::Malformed(format!(
396 "server echoed album {echoed}, not the requested {album_id}"
397 )));
398 }
399 tracing::info!(
400 roster_version = wire.roster_version,
401 replayed = wire.replayed,
402 "album roster published"
403 );
404 Ok(PublishedRoster {
405 album_id: echoed,
406 roster_version: wire.roster_version,
407 amk_epoch: wire.amk_epoch,
408 member_count: wire.member_count,
409 replayed: wire.replayed,
410 })
411 }
412}
413
414/// One call of the generated roster operation.
415///
416/// The protocol date is a required parameter of every gated operation in the document, so the
417/// generated signature asks for it; the value is this build's own, the same one the transport
418/// sends as a default header.
419async fn publish(
420 client: &crate::rest::Client,
421 album_id: Uuid,
422 body: &crate::rest::types::RosterRequest,
423) -> Result<
424 crate::rest::types::RosterResponse,
425 crate::rest::Error<crate::rest::PublishAlbumRosterError>,
426> {
427 Ok(client
428 .publish_album_roster(
429 album_id.hyphenated().to_string(),
430 crate::rest::PublishAlbumRosterParamsRequired {
431 x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
432 },
433 body.clone(),
434 )
435 .await?
436 .into_inner())
437}
438
439/// Whether the refusal was the credential's.
440fn is_unauthenticated(error: &crate::rest::Error<crate::rest::PublishAlbumRosterError>) -> bool {
441 matches!(
442 error,
443 crate::rest::Error::Api(response)
444 if matches!(
445 response.inner(),
446 crate::rest::PublishAlbumRosterError::Status401(_)
447 )
448 )
449}
450
451/// Map the generated operation's typed error onto this module's.
452///
453/// The `code` is what a caller switches on, and `current_version` is what the two version
454/// refusals — the `409` that is behind and the `400` that is too far ahead — both carry so the
455/// caller can re-sign one above what the server holds.
456fn publish_refusal(error: crate::rest::Error<crate::rest::PublishAlbumRosterError>) -> AlbumError {
457 use crate::rest::PublishAlbumRosterError as Refusal;
458
459 // The gate's `426`, or the typed transport's local one, is the SDK's one upgrade refusal
460 // (issue #674), not a status a caller has to recognise.
461 if let Some(refusal) = crate::client::upgrade_required_of(&error) {
462 tracing::warn!("roster publish refused: {refusal}");
463 return AlbumError::UpgradeRequired(Box::new(refusal));
464 }
465
466 // A body the generated decoder refuses (a counter out of its unsigned range, among others)
467 // is the server's answer being unreadable, not the wire failing.
468 if let crate::rest::Error::Decode { path, .. } = &error {
469 return AlbumError::Malformed(format!("roster publish answer: {path}"));
470 }
471 let crate::rest::Error::Api(response) = error else {
472 return AlbumError::Transport(error.to_string());
473 };
474 let status = response.status().as_u16();
475 let (code, current_version) = match response.into_inner() {
476 Refusal::Status400(problem) => (Some(problem.code.clone()), problem.current_version),
477 Refusal::Status409(problem) => (Some(problem.code.clone()), problem.current_version),
478 Refusal::Status401(problem)
479 | Refusal::Status403(problem)
480 | Refusal::Status404(problem)
481 | Refusal::Status408(problem)
482 | Refusal::Status413(problem)
483 | Refusal::Status415(problem)
484 | Refusal::Status422(problem)
485 | Refusal::Status425(problem)
486 | Refusal::Status426(problem)
487 | Refusal::Status500(problem) => (Some(problem.code.clone()), None),
488 };
489 tracing::warn!(status, ?code, ?current_version, "roster publish refused");
490 AlbumError::Status {
491 status,
492 code,
493 current_version,
494 }
495}
496
497// ─── Lifecycle ops ────────────────────────────────────────────────────────────
498
499/// What the server did with one lifecycle op (`POST /v1/albums/{album_id}/ops`).
500///
501/// A replay is a success: the server answers a manifest it already applied with the response
502/// it gave the first time, so a client that lost an acknowledgement resends without branching.
503#[derive(Debug, Clone, PartialEq, Eq)]
504pub struct AppliedOp {
505 /// The asset the op chained onto.
506 pub asset_id: String,
507 /// The action the server applied (`delete`, `trash-restore`, …).
508 pub action: String,
509 /// The feed position the op occupies; on a replay, the one the first application took.
510 pub sync_seq: u64,
511 /// Whether the server had applied this manifest already.
512 pub replayed: bool,
513}
514
515/// Why a lifecycle op was not applied.
516#[derive(Debug, thiserror::Error)]
517pub enum LifecycleOpError {
518 /// The request did not complete: the server could not be reached, the session could not
519 /// authorize it, or the response was not one the contract describes.
520 #[error("lifecycle op transport: {0}")]
521 Transport(String),
522 /// The server refused the op with one of the problems the contract declares.
523 #[error("lifecycle op refused with status {status} ({code})")]
524 Refused {
525 /// The HTTP status code.
526 status: u16,
527 /// The stable `error.*` code the server attached.
528 code: String,
529 /// On a `409 error.upload.stale_revival`, the chain head the manifest must name, so a
530 /// caller can re-read and rebase rather than resend a losing manifest.
531 chain_head: Option<String>,
532 /// On a `409 error.upload.retention_elapsed`, the signed retention floor (RFC 3339) the
533 /// trash-restore came too late for, as the server judged it — so a caller that never
534 /// held the delete can still say when the window closed.
535 retention_until: Option<String>,
536 },
537 /// The response could not be read as the contract describes it.
538 #[error("malformed lifecycle op response: {0}")]
539 Malformed(String),
540 /// The server will not take this client's writes: its `426`, or a window it advertised
541 /// that already refuses this build (issue #674). Update the app.
542 #[error(transparent)]
543 UpgradeRequired(Box<crate::net::negotiation::UpgradeRequired>),
544}
545
546impl LifecycleOpError {
547 /// The stable `error.*` code the server attached to a refusal, when there is one.
548 #[must_use]
549 pub fn error_code(&self) -> Option<&str> {
550 match self {
551 Self::Refused { code, .. } => Some(code),
552 Self::UpgradeRequired(refusal) => Some(refusal.error_code()),
553 Self::Transport(_) | Self::Malformed(_) => None,
554 }
555 }
556
557 /// A stable, machine-readable name for the failure — the `kind` a `--json` report carries.
558 ///
559 /// - `retention_elapsed` — a `trash-restore` after the asset's signed retention floor
560 /// (`409 error.upload.retention_elapsed`). The asset stays in the trash for good.
561 /// - `stale_revival` — the manifest does not chain onto the asset's stored head (`409`).
562 /// - `refused` — the server judged the op itself malformed (`400`, `413`, `415`, `422`).
563 /// - `forbidden` — the caller may not write this album or asset, or is suspended (`403`).
564 /// - `unauthenticated` — the session was not accepted (`401`).
565 /// - `upgrade_required` — the server will not take this build's writes (`426`).
566 /// - `unavailable` — the server could not answer (`500`) or could not be reached.
567 /// - `malformed` — the response could not be read.
568 #[must_use]
569 pub fn kind(&self) -> &'static str {
570 match self {
571 Self::Refused { code, .. }
572 if code == capsule_i18n::error_codes::UPLOAD_RETENTION_ELAPSED =>
573 {
574 "retention_elapsed"
575 }
576 Self::Refused { status: 409, .. } => "stale_revival",
577 Self::Refused { status: 401, .. } => "unauthenticated",
578 Self::Refused { status: 403, .. } => "forbidden",
579 Self::Refused { status: 500.., .. } | Self::Transport(_) => "unavailable",
580 Self::Refused { .. } => "refused",
581 Self::UpgradeRequired(_) => "upgrade_required",
582 Self::Malformed(_) => "malformed",
583 }
584 }
585
586 /// Whether sending the same op again can only be refused again: the server judged the op
587 /// itself (`400`, `409`, `413`, `415`, `422` — a stale chain, a regressed epoch, a closed
588 /// retention window, a malformed op). An unreachable server, a session it did not accept,
589 /// a permission it did not grant, an upgrade it asked for and a server fault are not: the
590 /// same bytes may be applied once that changes.
591 ///
592 /// A permanent refusal is never retried. A `retention_elapsed` one in particular is final
593 /// for the asset: no rebase or resend reopens a retention window.
594 #[must_use]
595 pub fn is_permanent(&self) -> bool {
596 matches!(
597 self,
598 Self::Refused {
599 status: 400 | 409 | 413 | 415 | 422,
600 ..
601 }
602 )
603 }
604}
605
606impl From<crate::auth::AuthError> for LifecycleOpError {
607 fn from(err: crate::auth::AuthError) -> Self {
608 match err {
609 crate::auth::AuthError::UpgradeRequired(refusal) => Self::UpgradeRequired(refusal),
610 other => Self::Transport(other.to_string()),
611 }
612 }
613}
614
615impl From<AlbumError> for LifecycleOpError {
616 fn from(err: AlbumError) -> Self {
617 match err {
618 AlbumError::UpgradeRequired(refusal) => Self::UpgradeRequired(refusal),
619 other => Self::Transport(other.to_string()),
620 }
621 }
622}
623
624impl AlbumClient {
625 /// Apply one signed lifecycle op to the album its envelope names, through the generated
626 /// `album_lifecycle_op` operation.
627 ///
628 /// Orchestration only, as [`Self::publish_roster`] is: the manifest was signed by the
629 /// library and the request is the generated type, so nothing on this path hand-writes a
630 /// wire shape. Idempotent under the manifest: a replay answers the first application's
631 /// response with `replayed` set.
632 ///
633 /// Under a session, a `401` is refreshed once and replayed. Nothing else is retried here,
634 /// and a [`permanent`](LifecycleOpError::is_permanent) refusal must not be retried by the
635 /// caller either.
636 ///
637 /// # Errors
638 ///
639 /// [`LifecycleOpError::Refused`] with the server's `error.*` code when the server refused
640 /// the op, [`LifecycleOpError::Malformed`] when the envelope names no album or the response
641 /// could not be read, [`LifecycleOpError::Transport`] when the request did not complete, and
642 /// [`LifecycleOpError::UpgradeRequired`] when the server will not take this build's writes.
643 #[instrument(skip_all, fields(asset_id = %request.manifest_envelope.file_id, action = %request.manifest_envelope.action))]
644 pub async fn apply_op(
645 &self,
646 request: &crate::rest::types::OpRequest,
647 ) -> Result<AppliedOp, LifecycleOpError> {
648 let album_id = request
649 .manifest_envelope
650 .album_id
651 .clone()
652 .into_option()
653 .ok_or_else(|| LifecycleOpError::Malformed("the op names no album".to_owned()))?;
654 let client = self.transport.generated()?;
655 let wire = match apply(&client, &album_id, request).await {
656 Ok(wire) => wire,
657 Err(error) if is_op_unauthenticated(&error) => match &self.transport.auth {
658 AlbumAuth::Session(session) => {
659 tracing::info!("the lifecycle op answered 401; refreshing once and retrying");
660 session.refresh().await?;
661 apply(&client, &album_id, request)
662 .await
663 .map_err(op_refusal)?
664 }
665 AlbumAuth::Static { .. } => return Err(op_refusal(error)),
666 },
667 Err(error) => return Err(op_refusal(error)),
668 };
669 let sync_seq = wire.sync_seq;
670 tracing::info!(
671 sync_seq,
672 replayed = wire.replayed,
673 applied = %wire.action,
674 "lifecycle op applied"
675 );
676 Ok(AppliedOp {
677 asset_id: wire.asset_id,
678 action: wire.action,
679 sync_seq,
680 replayed: wire.replayed,
681 })
682 }
683}
684
685/// One call of the generated lifecycle operation, at this build's protocol date.
686async fn apply(
687 client: &crate::rest::Client,
688 album_id: &str,
689 body: &crate::rest::types::OpRequest,
690) -> Result<crate::rest::types::OpResponse, crate::rest::Error<crate::rest::AlbumLifecycleOpError>>
691{
692 Ok(client
693 .album_lifecycle_op(
694 album_id.to_owned(),
695 crate::rest::AlbumLifecycleOpParamsRequired {
696 x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
697 },
698 body.clone(),
699 )
700 .await?
701 .into_inner())
702}
703
704/// Whether the lifecycle op's refusal was the credential's.
705fn is_op_unauthenticated(error: &crate::rest::Error<crate::rest::AlbumLifecycleOpError>) -> bool {
706 matches!(
707 error,
708 crate::rest::Error::Api(response)
709 if matches!(
710 response.inner(),
711 crate::rest::AlbumLifecycleOpError::Status401(_)
712 )
713 )
714}
715
716/// Map the generated lifecycle operation's typed error onto [`LifecycleOpError`].
717fn op_refusal(error: crate::rest::Error<crate::rest::AlbumLifecycleOpError>) -> LifecycleOpError {
718 use crate::rest::AlbumLifecycleOpError as Refusal;
719
720 if let Some(refusal) = crate::client::upgrade_required_of(&error) {
721 tracing::warn!("lifecycle op refused: {refusal}");
722 return LifecycleOpError::UpgradeRequired(Box::new(refusal));
723 }
724 let crate::rest::Error::Api(response) = error else {
725 tracing::warn!(%error, "lifecycle op did not complete");
726 return LifecycleOpError::Transport(error.to_string());
727 };
728 let status = response.status().as_u16();
729 let (code, chain_head, retention_until) = match response.into_inner() {
730 Refusal::Status409(problem) => (
731 problem.code,
732 problem.chain_head.into_option(),
733 problem.retention_until.into_option(),
734 ),
735 Refusal::Status400(problem)
736 | Refusal::Status401(problem)
737 | Refusal::Status403(problem)
738 | Refusal::Status408(problem)
739 | Refusal::Status413(problem)
740 | Refusal::Status415(problem)
741 | Refusal::Status422(problem)
742 | Refusal::Status425(problem)
743 | Refusal::Status500(problem) => (problem.code, None, None),
744 Refusal::Status426(problem) => (problem.code, None, None),
745 };
746 let logged_until = retention_until.clone();
747 let refusal = LifecycleOpError::Refused {
748 status,
749 code,
750 chain_head,
751 retention_until,
752 };
753 tracing::warn!(
754 status,
755 code = refusal.error_code(),
756 retention_until = ?logged_until,
757 kind = refusal.kind(),
758 permanent = refusal.is_permanent(),
759 "lifecycle op refused"
760 );
761 refusal
762}
763
764#[cfg(test)]
765mod tests;