Skip to main content

capsule_sdk/
upgrade.rs

1//! Proposing an **album upgrade** — the client half of the ceremony's one server-side step
2//! (over the server's album-upgrade wire).
3//!
4//! [Versioning — Album Upgrade Ceremony] is a client ceremony carried on MLS application
5//! messages the server cannot read. Four of its steps are the server's, and the first is the
6//! one this module drives: `POST /v1/albums/{album_id}/upgrade` hands the server a **signed
7//! `UpgradeIntent`**, which quiesces the album (a v_old client that never saw the proposal is
8//! precisely the party that will not stop writing on its own) and starts the deadline on the
9//! server's own clock (so a skewed member clock can neither extend nor shorten the window).
10//!
11//! Two rules shape this module, and both are the directory client's rules for the same reason:
12//!
13//! - **The signed bytes travel verbatim.** `intent_cbor` is the canonical CBOR
14//!   `capsule_core::crypto::upgrade::SignedUpgradeIntent` produced, and it is written to the
15//!   body unchanged. Re-encoding it here would detach it from the signature the server checks
16//!   against the proposing device's DSK in the account's published directory, and the failure
17//!   would look like a forged proposal.
18//! - **Nothing cryptographic happens here.** The intent is built and signed in `capsule-core`;
19//!   this module is the wire and its refusals.
20//!
21//! # What is hand-written, and what would retire it
22//!
23//! The request body is `application/cbor`, and `spargen` 0.5's `classify_media` does not know
24//! that media type, so `capsule-sdk/build.rs` narrows the operation out of the generated client
25//! — the *surface* is narrowed, the document is never mutilated. Only the **request**
26//! is hand-written: the path, the media type, and the verbatim CBOR body. Every JSON document
27//! the operation answers with decodes into the generated types — the phase into
28//! [`crate::rest::types::UpgradePhaseResponse`], every refusal into
29//! [`crate::rest::types::CodedProblem`] — so this module carries no second parser for a shape
30//! the contract already declares. ADR 0002 records the exception; teaching spargen the media
31//! type (issue #440) retires it, and nothing in this repository can.
32//!
33//! The **other two** operations on this path — `GET` (read the phase) and `DELETE` (end the
34//! ceremony) — are plain JSON and *are* generated. Call them through
35//! [`crate::client::AuthenticatedClient`]; this module deliberately does not duplicate them.
36//!
37//! [Versioning — Album Upgrade Ceremony]: https://docs/design/versioning/#album-upgrade-ceremony
38
39use jiff::Timestamp;
40use tracing::instrument;
41use uuid::Uuid;
42
43use crate::auth::{AuthError, Session};
44use crate::rest::types::{CodedProblem, UpgradePhaseResponse};
45
46/// The media type the intent is *signed* in, and therefore the only one it may be sent as.
47const CBOR: &str = "application/cbor";
48
49/// The phase response's media type — the answer is a plain JSON document.
50const JSON: &str = "application/json";
51
52// ─── Errors ───────────────────────────────────────────────────────────────────
53
54/// Everything a proposal can fail with. Callers switch on the typed variant, or on its stable
55/// `error.*` code, and never on a bare status.
56///
57/// Every refusal carries the code the **server** stamped rather than one this module inferred
58/// from the status, because the ceremony's refusals are the ones a user actually reads: "the
59/// album is already upgrading" and "your device is not an admin" are different sentences.
60#[derive(Debug, thiserror::Error)]
61pub enum UpgradeError {
62    /// The authenticated request itself failed (transport, session expiry, refresh).
63    #[error(transparent)]
64    Auth(#[from] AuthError),
65    /// The server refused the body as one it cannot read as a signed intent (`400`), refused
66    /// the media type (`415`), or refused its size (`413`). Retrying the same bytes changes
67    /// nothing — rebuild and re-sign the intent.
68    #[error("the server rejected the upgrade intent: {detail}")]
69    Malformed {
70        /// The stable `error.*` catalog code the refusal carried.
71        code: Option<String>,
72        /// English detail from the problem body.
73        detail: String,
74    },
75    /// The credential was refused (`401`).
76    #[error("the upgrade surface refused the credential: {detail}")]
77    Unauthorized {
78        /// The stable `error.*` catalog code the refusal carried.
79        code: Option<String>,
80        /// English detail from the problem body.
81        detail: String,
82    },
83    /// The intent is not signed by a device in the caller's **published** directory (`403`),
84    /// so the server cannot tell that an admin device really asked for this. Publish the
85    /// directory holding the proposing device first ([`crate::directory`]).
86    #[error("the upgrade intent's proposer could not be verified: {detail}")]
87    NotProposer {
88        /// The stable `error.*` catalog code the refusal carried.
89        code: Option<String>,
90        /// English detail from the problem body.
91        detail: String,
92    },
93    /// No such album, or not this caller's (`404`) — one answer for both, deliberately, so the
94    /// surface discloses nothing about albums the caller does not own.
95    #[error("no such album: {detail}")]
96    NotFound {
97        /// The stable `error.*` catalog code the refusal carried.
98        code: Option<String>,
99        /// English detail from the problem body.
100        detail: String,
101    },
102    /// A different ceremony already holds this album (`409`), and only one may. Read the phase
103    /// (the generated `GET` on the same path) and either join that ceremony or wait for its
104    /// deadline; a fresh proposal *replaces* an expired one rather than conflicting with it.
105    #[error("album is already upgrading under {intent_id:?}: {detail}")]
106    InFlight {
107        /// The ceremony that holds the album, as the server reported it.
108        intent_id: Option<String>,
109        /// The stable `error.*` catalog code the refusal carried.
110        code: Option<String>,
111        /// English detail from the problem body.
112        detail: String,
113    },
114    /// The server's protocol gate refused the request (`426`): this client speaks a protocol
115    /// version outside the server's window. Nothing about the intent is wrong — update the
116    /// client. The code is the server's own (`error.protocol.version_unsupported`).
117    #[error("the server does not accept this client's protocol version: {detail}")]
118    ProtocolUnsupported {
119        /// The stable `error.*` catalog code the refusal carried.
120        code: Option<String>,
121        /// English detail from the problem body.
122        detail: String,
123    },
124    /// A collaborator could not answer (`500`). Transient.
125    #[error("the upgrade could not be recorded: {detail}")]
126    Unavailable {
127        /// The stable `error.*` catalog code the refusal carried.
128        code: Option<String>,
129        /// English detail from the problem body.
130        detail: String,
131    },
132    /// The response body was not the phase document the contract declares.
133    #[error("malformed upgrade phase response: {0}")]
134    MalformedResponse(String),
135    /// The server returned an unmodeled status.
136    #[error("unexpected {status} response from the album-upgrade endpoint")]
137    Unexpected {
138        /// The HTTP status code the server returned.
139        status: u16,
140    },
141}
142
143impl UpgradeError {
144    /// The stable `error.*` catalog code a client localizes, when one applies. The English
145    /// [`Display`](std::fmt::Display) form stays the developer/log detail.
146    #[must_use]
147    pub fn error_code(&self) -> Option<&str> {
148        match self {
149            Self::Auth(auth) => auth.error_code(),
150            Self::Malformed { code, .. }
151            | Self::Unauthorized { code, .. }
152            | Self::NotProposer { code, .. }
153            | Self::NotFound { code, .. }
154            | Self::InFlight { code, .. }
155            | Self::ProtocolUnsupported { code, .. }
156            | Self::Unavailable { code, .. } => code.as_deref(),
157            _ => None,
158        }
159    }
160}
161
162// ─── Refusal bodies ───────────────────────────────────────────────────────────
163
164/// A refusal's body, read as the contract declares it: a generated [`CodedProblem`], plus the
165/// `409`'s `intent_id` extension member. The contract types that member only through
166/// `CodedProblem`'s `additionalProperties`, so the generated struct does not name it and it is
167/// read off the same document rather than through a second hand-written body type.
168///
169/// `problem` is `None` when there is no coded problem to read — the `413` backstop sends no body
170/// at all, and an unmodeled status may send anything.
171#[derive(Debug, Default)]
172struct Refusal {
173    problem: Option<CodedProblem>,
174    intent_id: Option<String>,
175}
176
177impl Refusal {
178    /// Read a refusal body. Never fails: a body that is not a coded problem is a refusal
179    /// without a code, and the status alone then picks the variant.
180    fn parse(body: &[u8]) -> Self {
181        let Ok(document) = serde_json::from_slice::<serde_json::Value>(body) else {
182            return Self::default();
183        };
184        let intent_id = document
185            .get("intent_id")
186            .and_then(serde_json::Value::as_str)
187            .map(str::to_owned);
188        let problem = serde_json::from_value::<CodedProblem>(document).ok();
189        Self { problem, intent_id }
190    }
191}
192
193/// The ceremony an album is in, as the proposal answered it.
194#[derive(Debug, Clone, PartialEq, Eq)]
195pub struct UpgradePhase {
196    /// The album, echoed by the server.
197    pub album_id: Uuid,
198    /// The ceremony now in flight, or `None` when the album is in normal operation.
199    pub intent_id: Option<Uuid>,
200    /// The protocol version the fork will be pinned to, when a ceremony is in flight.
201    pub to_protocol_version: Option<String>,
202    /// When the window closes, on the **server's** clock — never the client's.
203    pub expires_at: Option<Timestamp>,
204    /// How many upload sessions are still in flight against this album.
205    ///
206    /// The drain signal of the ceremony's step 3: the proposer waits for zero. A count and not
207    /// a listing, because the proposer needs to know *whether* to wait and has no business
208    /// seeing other members' upload identifiers to find out.
209    pub in_flight: u64,
210}
211
212// ─── Client ───────────────────────────────────────────────────────────────────
213
214/// The album-upgrade proposal client. Borrows an authenticated [`Session`], so every call
215/// rides the SDK's bearer/refresh machinery and no token is handled here.
216#[derive(Clone)]
217pub struct UpgradeClient {
218    session: Session,
219    base_url: String,
220}
221
222impl UpgradeClient {
223    /// Build a client against the **API root** — the origin the operation paths hang off (e.g.
224    /// `https://api.example.com`), the same base [`crate::client::AuthenticatedClient`],
225    /// [`crate::sync::SyncConsumer`] and [`crate::recovery::RecoveryClient`] take.
226    ///
227    /// Note that [`crate::directory`] and [`crate::verify`] take a *deeper* base instead. That
228    /// divergence is real and is noticed in `capsule-server/tests/sdk_client.rs`; it is not
229    /// this module's to close, and a new module choosing the root is how it narrows.
230    #[must_use]
231    pub fn new(session: Session, api_base_url: &str) -> Self {
232        Self {
233            session,
234            base_url: api_base_url.trim_end_matches('/').to_owned(),
235        }
236    }
237
238    /// Propose the upgrade `intent_cbor` describes for `album_id`, returning the ceremony the
239    /// server now holds.
240    ///
241    /// `intent_cbor` is the canonical CBOR of a signed `UpgradeIntent` and is sent **verbatim**
242    /// — this method never re-encodes it, because the signature is over exactly those bytes.
243    ///
244    /// # Errors
245    ///
246    /// [`UpgradeError::InFlight`] when another ceremony already holds the album (only one may),
247    /// [`UpgradeError::NotProposer`] when the signing device is not in the published directory,
248    /// and the rest of [`UpgradeError`] for the remaining refusals.
249    #[instrument(skip(self, intent_cbor), fields(album_id = %album_id, bytes = intent_cbor.len()))]
250    pub async fn begin(
251        &self,
252        album_id: Uuid,
253        intent_cbor: &[u8],
254    ) -> Result<UpgradePhase, UpgradeError> {
255        let url = format!(
256            "{}/v1/albums/{}/upgrade",
257            self.base_url,
258            album_id.hyphenated()
259        );
260        let body = intent_cbor.to_vec();
261        let response = self
262            .session
263            .execute(|http| {
264                http.post(&url)
265                    .header(reqwest::header::CONTENT_TYPE, CBOR)
266                    .header(reqwest::header::ACCEPT, JSON)
267                    .body(body.clone())
268            })
269            .await
270            .map_err(|error| match error {
271                // The session screens every send through the protocol window (issue #674), so
272                // the gate's `426` — or a write the advertised window already refuses — arrives
273                // here typed rather than as a status; it keeps this module's own variant.
274                AuthError::UpgradeRequired(refusal) => UpgradeError::ProtocolUnsupported {
275                    code: Some(refusal.error_code().to_owned()),
276                    detail: refusal.message,
277                },
278                other => UpgradeError::Auth(other),
279            })?;
280
281        let status = response.status();
282        if !status.is_success() {
283            // A body that cannot even be read is a refusal without a code, exactly like one
284            // that is not a coded problem: the status still picks the variant.
285            let body = response.bytes().await.unwrap_or_default();
286            let error = refusal(status.as_u16(), Refusal::parse(&body));
287            tracing::warn!(
288                status = status.as_u16(),
289                code = ?error.error_code(),
290                "album-upgrade proposal refused"
291            );
292            return Err(error);
293        }
294
295        let wire: UpgradePhaseResponse = response
296            .json()
297            .await
298            .map_err(|e| UpgradeError::MalformedResponse(e.to_string()))?;
299        let phase = decode_phase(wire)?;
300        tracing::info!(
301            intent_id = ?phase.intent_id,
302            in_flight = phase.in_flight,
303            expires_at = ?phase.expires_at,
304            "album upgrade proposed; the album is quiesced"
305        );
306        Ok(phase)
307    }
308}
309
310/// Map a refusal onto its typed variant, keeping the code the server stamped.
311///
312/// One readable status table rather than a match buried in the request path.
313///
314/// `413` is the transport's body backstop and carries no problem body at all, so it has no
315/// code — and this client does not mint one. Every code here is the code the *server* stamped;
316/// a code invented on this side would assert that the server said something it did not, and a
317/// client localizing it would read the SDK's guess as the server's judgement. The variant
318/// already carries the actionable half ("these bytes will not do"), and the English detail
319/// carries the reason.
320fn refusal(status: u16, refusal: Refusal) -> UpgradeError {
321    let Refusal { problem, intent_id } = refusal;
322    let (code, detail) = problem.map_or((None, String::new()), |problem| {
323        (Some(problem.code), problem.detail.unwrap_or_default())
324    });
325    match status {
326        400 | 415 => UpgradeError::Malformed { code, detail },
327        401 => UpgradeError::Unauthorized { code, detail },
328        403 => UpgradeError::NotProposer { code, detail },
329        404 => UpgradeError::NotFound { code, detail },
330        409 => UpgradeError::InFlight {
331            intent_id,
332            code,
333            detail,
334        },
335        413 => UpgradeError::Malformed {
336            code: None,
337            detail: "the signed upgrade intent exceeds the server's body limit".to_owned(),
338        },
339        426 => UpgradeError::ProtocolUnsupported { code, detail },
340        500 => UpgradeError::Unavailable { code, detail },
341        other => UpgradeError::Unexpected { status: other },
342    }
343}
344
345/// Parse the phase document into its typed shape.
346///
347/// The ids become [`Uuid`]s and the deadline a [`jiff::Timestamp`], so a caller compares
348/// instants rather than strings — the deadline is the one field in this ceremony where a
349/// string comparison would be a correctness bug rather than an inconvenience.
350fn decode_phase(wire: UpgradePhaseResponse) -> Result<UpgradePhase, UpgradeError> {
351    let album_id = Uuid::parse_str(&wire.album_id)
352        .map_err(|e| UpgradeError::MalformedResponse(format!("response album_id: {e}")))?;
353    let intent_id = wire
354        .intent_id
355        .as_option()
356        .map(|id| Uuid::parse_str(id))
357        .transpose()
358        .map_err(|e| UpgradeError::MalformedResponse(format!("response intent_id: {e}")))?;
359    let expires_at = wire
360        .expires_at
361        .as_option()
362        .map(|at| at.parse::<Timestamp>())
363        .transpose()
364        .map_err(|e| UpgradeError::MalformedResponse(format!("response expires_at: {e}")))?;
365    // The contract declares the count `uint64` and the generated type carries it unsigned, so a
366    // negative count never decodes.
367    let in_flight = wire.in_flight;
368    Ok(UpgradePhase {
369        album_id,
370        intent_id,
371        to_protocol_version: wire.to_protocol_version.into_option(),
372        expires_at,
373        in_flight,
374    })
375}
376
377#[cfg(test)]
378mod tests;