Skip to main content

capsule_sdk/share/
mod.rs

1//! The owner's two share-link operations over the generated client (#622): register a link
2//! the issuing client published (`POST /v1/shares`), and revoke one (`DELETE
3//! /v1/shares/{opaque_id}`).
4//!
5//! Orchestration only. The link and everything it serves are built in `capsule-core`:
6//! [`ShareLinkIssuer::create_link`](capsule_core::sharing::ShareLinkIssuer::create_link) mints
7//! the opaque id, the fragment secret and the scope encapsulation, and
8//! `Workspace::publish_link` seals the `share-metadata/v1` record into a
9//! [`SharePublication`]. This module maps the two onto the generated `issue_share` request,
10//! calls the generated operations through [`AuthenticatedClient`] (so the bearer, the
11//! pre-flight refresh and the one `401` replay are the SDK's), and maps the generated typed
12//! refusals onto [`ShareError`]. Nothing here parses or serializes by hand.
13//!
14//! The sealed metadata record travels in the same request, as `metadata_blob`: the server checks
15//! that it hashes to `metadata_hash`, stores it before it records the link, and keeps it from the
16//! collector for as long as the link is live (#653). So a link this module registers is
17//! servable as soon as `issue` returns, provided every covered ciphertext is already held.
18//!
19//! The fragment secret never reaches this module's requests: [`issue_request`] reads the opaque
20//! id, the publication and the expiry, and the URL is assembled locally by [`share_url`].
21
22use base64::Engine as _;
23use base64::engine::general_purpose::STANDARD as BASE64;
24use capsule_core::sharing::{ShareLink, SharePublication};
25use tracing::instrument;
26
27use crate::auth::Session;
28use crate::client::{
29    AuthenticatedClient, ClientError, absent_unless, describe_error, is_token_failure,
30};
31use crate::rest;
32
33/// Why a share-link operation did not complete.
34#[derive(Debug, thiserror::Error)]
35pub enum ShareError {
36    /// The configured API root is not a URL operation paths can hang off.
37    #[error("invalid base URL {url:?}: {reason}")]
38    InvalidBaseUrl {
39        /// The offending URL.
40        url: String,
41        /// Why it was refused.
42        reason: String,
43    },
44    /// The server refused the link record (`400 error.share.malformed`, `415`, `422`): sending
45    /// the same request again will not help.
46    #[error("the share link was refused: {detail}")]
47    Malformed {
48        /// The server's stable `error.*` code.
49        code: Option<String>,
50        /// The server's English detail.
51        detail: String,
52    },
53    /// The credential was refused (`401`/`403`), or the session could not produce one.
54    #[error("the share request was not authorized")]
55    Unauthorized {
56        /// The server's stable `error.*` code, when it answered.
57        code: Option<String>,
58    },
59    /// The server could not answer (`500 error.share.unavailable`); retrying later may work.
60    #[error("the share store is unavailable")]
61    Unavailable {
62        /// The server's stable `error.*` code.
63        code: Option<String>,
64    },
65    /// The server will not take this client's writes: the protocol gate's `426`, or a window
66    /// it advertised that already refuses this build, so the write never left (issue #674).
67    #[error(transparent)]
68    UpgradeRequired(Box<crate::net::negotiation::UpgradeRequired>),
69    /// The server answered with a status this client does not model, such as the transport
70    /// backstop's `413`.
71    #[error("the share request was answered {status}")]
72    Unexpected {
73        /// The HTTP status.
74        status: u16,
75        /// The server's stable `error.*` code, when the body carried one.
76        code: Option<String>,
77    },
78    /// The server answered `201` for a different link than the one registered.
79    #[error("the server echoed link {echoed}, not {requested}")]
80    WrongEcho {
81        /// The opaque id this client registered.
82        requested: String,
83        /// The opaque id the server echoed.
84        echoed: String,
85    },
86    /// The request did not complete.
87    #[error("the share request did not complete: {0}")]
88    Transport(String),
89}
90
91impl ShareError {
92    /// The stable `error.*` catalog code a client localizes, when the server sent one.
93    #[must_use]
94    pub fn error_code(&self) -> Option<&str> {
95        match self {
96            Self::Malformed { code, .. }
97            | Self::Unauthorized { code }
98            | Self::Unavailable { code }
99            | Self::Unexpected { code, .. } => code.as_deref(),
100            Self::UpgradeRequired(refusal) => Some(refusal.error_code()),
101            Self::InvalidBaseUrl { .. } | Self::WrongEcho { .. } | Self::Transport(_) => None,
102        }
103    }
104}
105
106/// The `POST /v1/shares` body for `link`, from what `Workspace::publish_link` returned for it.
107///
108/// The record's `metadata_hash` and `serves` (record first, then each covered ciphertext) are
109/// carried as lowercase hex, the sealed record itself and the passphrase-wrapped scope as
110/// base64, and the expiry as the link's own RFC 3339 string. The fragment secret is not read.
111#[must_use]
112pub fn issue_request(
113    link: &ShareLink,
114    publication: &SharePublication,
115) -> rest::types::IssueShareRequest {
116    rest::types::IssueShareRequest {
117        opaque_id: link.opaque_id_hex(),
118        metadata_hash: publication.metadata_hash.to_hex(),
119        serves: publication
120            .serves
121            .iter()
122            .map(capsule_core::crypto::hash::Hash32::to_hex)
123            .collect(),
124        wrapped_secret: absent_unless(
125            publication
126                .wrapped_secret
127                .as_ref()
128                .map(|secret| BASE64.encode(secret)),
129        ),
130        expires_at: absent_unless(link.expires_at.clone()),
131        metadata_blob: rest::Nullable::Value(BASE64.encode(&publication.metadata_blob)),
132    }
133}
134
135/// The URL a recipient opens: `{origin}/s/{opaque_id}#{fragment}`.
136///
137/// `origin` is the server's public origin (`https://capsule.example.com`); a trailing `/` is
138/// dropped so the path is not doubled. The fragment is what makes the link work and is never
139/// sent to the server by a browser, which is why it rides after the `#`.
140#[must_use]
141pub fn share_url(origin: &str, link: &ShareLink) -> String {
142    format!(
143        "{}/s/{}#{}",
144        origin.trim_end_matches('/'),
145        link.opaque_id_hex(),
146        link.fragment_hex()
147    )
148}
149
150/// Registers and revokes the caller's share links.
151pub struct ShareClient {
152    client: AuthenticatedClient,
153}
154
155impl ShareClient {
156    /// Build a share client against the **API root** (e.g. `https://api.example.com`), the
157    /// origin the generated operation paths hang off.
158    ///
159    /// # Errors
160    ///
161    /// [`ShareError::InvalidBaseUrl`] when `api_base_url` does not parse.
162    pub fn new(session: Session, api_base_url: &str) -> Result<Self, ShareError> {
163        let client =
164            AuthenticatedClient::new(api_base_url, session).map_err(|error| match error {
165                ClientError::InvalidBaseUrl { url, reason } => {
166                    ShareError::InvalidBaseUrl { url, reason }
167                }
168            })?;
169        Ok(Self { client })
170    }
171
172    /// Register `link` with the server, so its public path serves what `publication` names.
173    ///
174    /// An opaque id registers once. The server refuses any id it already holds, the caller's
175    /// own included, with the same `400 error.share.malformed` it gives a malformed record
176    /// (#553), so re-sending a request whose first attempt landed surfaces as
177    /// [`ShareError::Malformed`], not as success. That refusal is not read as success here: it
178    /// is also the answer for an id the caller revoked, and its English detail is not a stable
179    /// discriminator. A caller whose request timed out recovers by revoking the id (revoke
180    /// answers `204` whether or not the first attempt landed) and issuing a freshly minted
181    /// link.
182    ///
183    /// # Errors
184    ///
185    /// The refusals [`ShareError`] names, and [`ShareError::WrongEcho`] when the server
186    /// confirms a different link.
187    #[instrument(skip_all, fields(opaque_id = %link.opaque_id_hex(), serves = publication.serves.len()))]
188    pub async fn issue(
189        &self,
190        link: &ShareLink,
191        publication: &SharePublication,
192    ) -> Result<(), ShareError> {
193        let body = issue_request(link, publication);
194        let echoed = self
195            .client
196            .issue_share(
197                crate::rest::IssueShareParamsRequired {
198                    x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
199                },
200                body.clone(),
201            )
202            .await
203            .map_err(|error| refusal(error, issue_refusal))?
204            .into_inner()
205            .opaque_id;
206        if echoed != body.opaque_id {
207            return Err(ShareError::WrongEcho {
208                requested: body.opaque_id,
209                echoed,
210            });
211        }
212        tracing::info!(
213            passphrase = body.wrapped_secret.is_value(),
214            expires = body.expires_at.is_value(),
215            "share link registered"
216        );
217        Ok(())
218    }
219
220    /// Revoke the caller's link `opaque_id` (lowercase hex).
221    ///
222    /// The server answers `204` whether the link was the caller's, was already revoked, or never
223    /// existed, so success says the link is not live for this caller, not that one was revoked.
224    ///
225    /// # Errors
226    ///
227    /// The refusals [`ShareError`] names.
228    #[instrument(skip(self))]
229    pub async fn revoke(&self, opaque_id: &str) -> Result<(), ShareError> {
230        self.client
231            .revoke_share(
232                opaque_id.to_owned(),
233                crate::rest::RevokeShareParamsRequired {
234                    x_capsule_protocol: capsule_core::crypto::primitives::PROTOCOL_VERSION.into(),
235                },
236            )
237            .await
238            .map_err(|error| refusal(error, revoke_refusal))?;
239        tracing::info!("share link revocation accepted");
240        Ok(())
241    }
242}
243
244/// Map a generated-client failure: a declared refusal through `declared`, everything else to a
245/// wire class.
246fn refusal<E>(error: rest::Error<E>, declared: fn(u16, E) -> ShareError) -> ShareError
247where
248    E: std::error::Error + 'static,
249{
250    // The gate's `426`, or the typed transport's local one (issue #674).
251    if let Some(refusal) = crate::client::upgrade_required_of(&error) {
252        tracing::warn!("share request refused: {refusal}");
253        return ShareError::UpgradeRequired(Box::new(refusal));
254    }
255    match error {
256        rest::Error::Api(response) => {
257            let status = response.status().as_u16();
258            let mapped = declared(status, response.into_inner());
259            tracing::warn!(status, code = ?mapped.error_code(), "share request refused");
260            mapped
261        }
262        rest::Error::UnexpectedStatus { status, .. } => ShareError::Unexpected {
263            status: status.as_u16(),
264            code: None,
265        },
266        rest::Error::RequestConstruction(_) if is_token_failure(&error) => {
267            ShareError::Unauthorized { code: None }
268        }
269        other => ShareError::Transport(describe_error(&other)),
270    }
271}
272
273fn coded(problem: &rest::types::CodedProblem) -> (Option<String>, String) {
274    (
275        Some(problem.code.clone()),
276        problem.detail.clone().unwrap_or_default(),
277    )
278}
279
280fn issue_refusal(status: u16, error: rest::IssueShareError) -> ShareError {
281    use rest::IssueShareError as Refusal;
282    match error {
283        Refusal::Status400(problem) | Refusal::Status415(problem) | Refusal::Status422(problem) => {
284            let (code, detail) = coded(&problem);
285            ShareError::Malformed { code, detail }
286        }
287        Refusal::Status401(problem) | Refusal::Status403(problem) => ShareError::Unauthorized {
288            code: Some(problem.code.clone()),
289        },
290        // A `425` is a write that reached the server as TLS early data, and a `408` one whose
291        // body stalled before it arrived whole: re-sent later, either lands.
292        Refusal::Status408(problem) | Refusal::Status425(problem) | Refusal::Status500(problem) => {
293            ShareError::Unavailable {
294                code: Some(problem.code.clone()),
295            }
296        }
297        // `426` is unreachable: `refusal` takes every one as `UpgradeRequired` first.
298        Refusal::Status426(problem) | Refusal::Status413(problem) => ShareError::Unexpected {
299            status,
300            code: Some(problem.code.clone()),
301        },
302    }
303}
304
305fn revoke_refusal(status: u16, error: rest::RevokeShareError) -> ShareError {
306    use rest::RevokeShareError as Refusal;
307    match error {
308        Refusal::Status400(problem) => {
309            let (code, detail) = coded(&problem);
310            ShareError::Malformed { code, detail }
311        }
312        Refusal::Status401(problem) | Refusal::Status403(problem) => ShareError::Unauthorized {
313            code: Some(problem.code.clone()),
314        },
315        Refusal::Status425(problem) | Refusal::Status500(problem) => ShareError::Unavailable {
316            code: Some(problem.code.clone()),
317        },
318        // `426` is unreachable: `refusal` takes every one as `UpgradeRequired` first.
319        Refusal::Status426(problem) | Refusal::Status413(problem) => ShareError::Unexpected {
320            status,
321            code: Some(problem.code.clone()),
322        },
323    }
324}
325
326#[cfg(test)]
327mod tests;