Skip to main content

capsule_sdk/net/
negotiation.rs

1//! The response half of the protocol handshake, read on every call (issue #674).
2//!
3//! # The contract
4//!
5//! [Versioning — Update Policy] has the server advertise its accepted `protocol_version`
6//! window (`X-Capsule-Protocol-Min`/`-Max`) and an advisory client-build floor
7//! (`X-Capsule-Min-Client-Build`) on every response, and has a native app refuse to *write* —
8//! telling the user to update — when the server answers `426` or advertises a floor above its
9//! own build. Reads keep working against any server: "reads of any past version succeed", and
10//! "reads are never affected" by either rule. System invariant 8 makes the protocol date one
11//! value per binary.
12//!
13//! # What this module does with that
14//!
15//! - [`ServerWindow`] is the three headers, parsed leniently: a header that is absent or does
16//!   not parse is no bound, never a refusal (apps stay lenient).
17//! - [`UpgradeRequired`] is the **one** typed refusal every SDK surface maps to: a `426` the
18//!   server answered ([`UpgradeReason::Refused`]), or a window or floor this build is outside.
19//! - The window each server advertised is latched per origin ([`observe`]) from every
20//!   response the SDK's seams see — reads, writes and uploads alike — so a later write is
21//!   refused **before** it leaves ([`preflight`]) instead of after the server acted on it.
22//!   [`advertised`] and [`upgrade_required_for`] expose the latch, which is how a read that
23//!   was served surfaces "this build is too old" to a UI without being refused.
24//!
25//! A write whose own response first reveals the floor has already landed; it is returned as
26//! the server answered (it cannot be unsent, and reporting a landed write as failed invites
27//! a duplicate), and the latch refuses the next one.
28//!
29//! [Versioning — Update Policy]: https://docs/design/versioning/#update-policy
30
31use std::collections::HashMap;
32use std::sync::{Mutex, OnceLock, PoisonError};
33
34use capsule_i18n::error_codes;
35use reqwest::header::HeaderMap;
36use reqwest::{Method, StatusCode, Url};
37
38/// The request header carrying the protocol date a request is written against.
39pub const PROTOCOL_HEADER: &str = "x-capsule-protocol";
40/// The response header carrying the oldest protocol date the server accepts.
41pub const PROTOCOL_MIN_HEADER: &str = "x-capsule-protocol-min";
42/// The response header carrying the newest protocol date the server accepts.
43pub const PROTOCOL_MAX_HEADER: &str = "x-capsule-protocol-max";
44/// The response header carrying the server's advisory client-build floor (`MAJOR.MINOR.PATCH`).
45pub const MIN_CLIENT_BUILD_HEADER: &str = "x-capsule-min-client-build";
46
47/// The protocol date this binary speaks — `capsule-core`'s, and nothing else (invariant 8).
48pub const PROTOCOL_VERSION: &str = capsule_core::crypto::primitives::PROTOCOL_VERSION;
49
50/// The client build compared against `X-Capsule-Min-Client-Build`: this SDK's own version,
51/// which every Capsule client on this tree ships as its network path.
52pub const CLIENT_BUILD: &str = env!("CARGO_PKG_VERSION");
53
54/// What a server advertised about the clients it accepts.
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
56pub struct ServerWindow {
57    /// `X-Capsule-Protocol-Min`, verbatim.
58    pub protocol_min: Option<String>,
59    /// `X-Capsule-Protocol-Max`, verbatim.
60    pub protocol_max: Option<String>,
61    /// `X-Capsule-Min-Client-Build`, verbatim.
62    pub min_client_build: Option<String>,
63}
64
65impl ServerWindow {
66    /// Read the three advertised headers off a response.
67    #[must_use]
68    pub fn from_headers(headers: &HeaderMap) -> Self {
69        let read = |name: &str| {
70            headers
71                .get(name)
72                .and_then(|value| value.to_str().ok())
73                .map(|value| value.trim().to_owned())
74                .filter(|value| !value.is_empty())
75        };
76        Self {
77            protocol_min: read(PROTOCOL_MIN_HEADER),
78            protocol_max: read(PROTOCOL_MAX_HEADER),
79            min_client_build: read(MIN_CLIENT_BUILD_HEADER),
80        }
81    }
82
83    /// Whether the response advertised anything at all.
84    #[must_use]
85    pub fn is_advertised(&self) -> bool {
86        self.protocol_min.is_some()
87            || self.protocol_max.is_some()
88            || self.min_client_build.is_some()
89    }
90
91    /// Why a client speaking `protocol` at `build` is outside this window, or `None` when it is
92    /// inside (or when no bound that parses says otherwise).
93    #[must_use]
94    pub fn verdict(&self, protocol: &str, build: &str) -> Option<UpgradeReason> {
95        if is_protocol_date(protocol) {
96            if let Some(min) = self.protocol_min.as_deref().filter(|v| is_protocol_date(v))
97                && protocol < min
98            {
99                return Some(UpgradeReason::ProtocolBelowWindow);
100            }
101            if let Some(max) = self.protocol_max.as_deref().filter(|v| is_protocol_date(v))
102                && protocol > max
103            {
104                return Some(UpgradeReason::ProtocolAboveWindow);
105            }
106        }
107        let floor = self.min_client_build.as_deref().and_then(parse_build);
108        match (floor, parse_build(build)) {
109            (Some(floor), Some(build)) if build < floor => Some(UpgradeReason::BuildBelowFloor),
110            _ => None,
111        }
112    }
113}
114
115/// Why a server will not take this client's writes.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum UpgradeReason {
118    /// The server answered `426 Upgrade Required`.
119    Refused,
120    /// This client's protocol date is older than `X-Capsule-Protocol-Min`: update the app.
121    ProtocolBelowWindow,
122    /// This client's protocol date is newer than `X-Capsule-Protocol-Max`: the server is behind.
123    ProtocolAboveWindow,
124    /// This client's build is below `X-Capsule-Min-Client-Build`: update the app.
125    BuildBelowFloor,
126}
127
128/// The one typed refusal for "this client and this server cannot write together", whichever
129/// SDK surface met it. Carries the advertised window so a UI can say what to update.
130#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
131#[error(
132    "upgrade required ({reason:?}): server accepts protocol {min:?}..={max:?} and client build \
133     >= {floor:?}; this client speaks {protocol} at build {build}: {message}",
134    min = window.protocol_min,
135    max = window.protocol_max,
136    floor = window.min_client_build,
137    build = CLIENT_BUILD
138)]
139pub struct UpgradeRequired {
140    /// Which rule refused.
141    pub reason: UpgradeReason,
142    /// What the server advertised.
143    pub window: Box<ServerWindow>,
144    /// The protocol date the refused request carried. The build compared against the floor is
145    /// always [`CLIENT_BUILD`].
146    pub protocol: String,
147    /// The English detail: the server's, for a `426`; this module's, for a local refusal.
148    pub message: String,
149}
150
151impl UpgradeRequired {
152    /// The stable `error.*` catalog code a client localizes.
153    #[must_use]
154    pub fn error_code(&self) -> &'static str {
155        error_codes::PROTOCOL_VERSION_UNSUPPORTED
156    }
157
158    /// A `426` the server answered, carrying whatever window it advertised beside it. The
159    /// reason is the rule that window names for `protocol`, else [`UpgradeReason::Refused`].
160    #[must_use]
161    pub fn refused(headers: &HeaderMap, protocol: &str, message: impl Into<String>) -> Self {
162        let window = ServerWindow::from_headers(headers);
163        Self {
164            reason: window
165                .verdict(protocol, CLIENT_BUILD)
166                .unwrap_or(UpgradeReason::Refused),
167            window: Box::new(window),
168            protocol: protocol.to_owned(),
169            message: message.into(),
170        }
171    }
172}
173
174/// Whether a request with this method writes. Only a write is ever refused here.
175#[must_use]
176pub fn is_write(method: &Method) -> bool {
177    !matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
178}
179
180/// The protocol date a prepared request carries — its own header when it set one (the
181/// upload transport's pin), else the build's, which the transport adds as a default header.
182#[must_use]
183pub fn protocol_of(headers: &HeaderMap) -> String {
184    headers
185        .get(PROTOCOL_HEADER)
186        .and_then(|value| value.to_str().ok())
187        .unwrap_or(PROTOCOL_VERSION)
188        .to_owned()
189}
190
191/// Latch the window `url`'s server advertised on a response. A response that advertises
192/// nothing (an unrouted `404`, a proxy's error page) leaves the latch as it was.
193pub fn observe(url: &Url, headers: &HeaderMap) {
194    let window = ServerWindow::from_headers(headers);
195    if !window.is_advertised() {
196        return;
197    }
198    let origin = origin_of(url);
199    let mut latch = latch().lock().unwrap_or_else(PoisonError::into_inner);
200    if latch.get(&origin) != Some(&window) {
201        tracing::debug!(
202            %origin,
203            protocol_min = ?window.protocol_min,
204            protocol_max = ?window.protocol_max,
205            min_client_build = ?window.min_client_build,
206            "server window observed"
207        );
208        latch.insert(origin, window);
209    }
210}
211
212/// The window `url`'s server last advertised to this process, if any.
213#[must_use]
214pub fn advertised(url: &Url) -> Option<ServerWindow> {
215    latch()
216        .lock()
217        .unwrap_or_else(PoisonError::into_inner)
218        .get(&origin_of(url))
219        .cloned()
220}
221
222/// Whether this build is outside the window `url`'s server last advertised — the read-side
223/// signal: a read is served regardless, and this is what tells the UI to ask for an update.
224#[must_use]
225pub fn upgrade_required_for(url: &Url) -> Option<UpgradeRequired> {
226    let window = advertised(url)?;
227    let reason = window.verdict(PROTOCOL_VERSION, CLIENT_BUILD)?;
228    Some(local_refusal(reason, window, PROTOCOL_VERSION))
229}
230
231/// Refuse a write the latched window already says the server will not take, before it leaves.
232/// Reads are never refused.
233///
234/// # Errors
235///
236/// [`UpgradeRequired`] when `method` writes and `protocol`/[`CLIENT_BUILD`] is outside the
237/// window `url`'s server last advertised.
238pub fn preflight(method: &Method, url: &Url, protocol: &str) -> Result<(), UpgradeRequired> {
239    if !is_write(method) {
240        return Ok(());
241    }
242    let Some(window) = advertised(url) else {
243        return Ok(());
244    };
245    match window.verdict(protocol, CLIENT_BUILD) {
246        None => Ok(()),
247        Some(reason) => {
248            let refusal = local_refusal(reason, window, protocol);
249            tracing::warn!(%method, %url, ?reason, "write refused before sending: {refusal}");
250            Err(refusal)
251        }
252    }
253}
254
255/// Latch a response's window and map a `426` to [`UpgradeRequired`]; every other response is
256/// returned untouched for its caller to read.
257///
258/// # Errors
259///
260/// [`UpgradeRequired`] for a `426`, with the problem's `detail` (or the body as text) as its
261/// message.
262pub async fn screen(
263    protocol: &str,
264    response: reqwest::Response,
265) -> Result<reqwest::Response, UpgradeRequired> {
266    observe(response.url(), response.headers());
267    if response.status() != StatusCode::UPGRADE_REQUIRED {
268        return Ok(response);
269    }
270    let headers = response.headers().clone();
271    let url = response.url().clone();
272    let text = response.text().await.unwrap_or_default();
273    let refusal = UpgradeRequired::refused(&headers, protocol, problem_detail(&text));
274    tracing::warn!(%url, "server refused this client's protocol: {refusal}");
275    Err(refusal)
276}
277
278/// Drop whatever window `url`'s origin latched. A server that comes back on a reused address
279/// (a test's ephemeral port, a redeployed host) starts from nothing rather than from the window
280/// a previous server there advertised.
281pub fn forget(url: &Url) {
282    latch()
283        .lock()
284        .unwrap_or_else(PoisonError::into_inner)
285        .remove(&origin_of(url));
286}
287
288/// [`forget`] for a mock server bound at `addr`: every in-crate mock calls this as it binds,
289/// so a window a previous test's server latched on the same ephemeral port never leaks in.
290#[cfg(test)]
291pub(crate) fn forget_addr(addr: std::net::SocketAddr) {
292    if let Ok(url) = Url::parse(&format!("http://{addr}")) {
293        forget(&url);
294    }
295}
296
297/// Why a [`send_negotiated`] or [`send_screened`] did not yield a response to read.
298#[derive(Debug)]
299pub(crate) enum SendError {
300    /// The window refused it, before it left or with the server's `426`.
301    Upgrade(UpgradeRequired),
302    /// The request could not be built or did not reach an answer.
303    Transport(reqwest::Error),
304}
305
306impl From<reqwest::Error> for SendError {
307    fn from(error: reqwest::Error) -> Self {
308        Self::Transport(error)
309    }
310}
311
312impl From<UpgradeRequired> for SendError {
313    fn from(refusal: UpgradeRequired) -> Self {
314        Self::Upgrade(refusal)
315    }
316}
317
318/// Send a data request through the window: a write the latched window refuses never leaves,
319/// the response's window is latched, and a `426` is [`SendError::Upgrade`]. Every hand-written
320/// data path's send goes through here.
321pub(crate) async fn send_negotiated(
322    builder: reqwest::RequestBuilder,
323) -> Result<reqwest::Response, SendError> {
324    let (client, request) = builder.build_split();
325    let request = request?;
326    let protocol = protocol_of(request.headers());
327    preflight(request.method(), request.url(), &protocol)?;
328    let response = super::execute(&client, request).await?;
329    Ok(screen(&protocol, response).await?)
330}
331
332/// [`send_negotiated`] without the pre-flight: for session upkeep, which only the server's own
333/// `426` refuses (a read needs a live session, and reads keep working against any server).
334pub(crate) async fn send_screened(
335    builder: reqwest::RequestBuilder,
336) -> Result<reqwest::Response, SendError> {
337    let (client, request) = builder.build_split();
338    let request = request?;
339    let protocol = protocol_of(request.headers());
340    let response = super::execute(&client, request).await?;
341    Ok(screen(&protocol, response).await?)
342}
343
344/// The English detail of a problem body: `detail`, else the legacy `error`, else the text.
345#[must_use]
346pub fn problem_detail(text: &str) -> String {
347    serde_json::from_str::<serde_json::Value>(text)
348        .ok()
349        .and_then(|body| {
350            ["detail", "error", "title"]
351                .iter()
352                .find_map(|key| body.get(key)?.as_str().map(str::to_owned))
353        })
354        .unwrap_or_else(|| text.to_owned())
355}
356
357fn local_refusal(reason: UpgradeReason, window: ServerWindow, protocol: &str) -> UpgradeRequired {
358    UpgradeRequired {
359        reason,
360        window: Box::new(window),
361        protocol: protocol.to_owned(),
362        message: "the server's advertised window does not admit this client's writes; \
363                  update Capsule"
364            .to_owned(),
365    }
366}
367
368fn latch() -> &'static Mutex<HashMap<String, ServerWindow>> {
369    static LATCH: OnceLock<Mutex<HashMap<String, ServerWindow>>> = OnceLock::new();
370    LATCH.get_or_init(|| Mutex::new(HashMap::new()))
371}
372
373fn origin_of(url: &Url) -> String {
374    url.origin().ascii_serialization()
375}
376
377/// `YYYY-MM-DD`, the grammar in which lexical order is date order.
378pub(crate) fn is_protocol_date(value: &str) -> bool {
379    let bytes = value.as_bytes();
380    bytes.len() == 10
381        && bytes.iter().enumerate().all(|(index, byte)| {
382            if index == 4 || index == 7 {
383                *byte == b'-'
384            } else {
385                byte.is_ascii_digit()
386            }
387        })
388}
389
390/// `MAJOR.MINOR.PATCH`, compared numerically. Anything after a `-` or `+` is ignored; a value
391/// that is not three numbers is no floor.
392fn parse_build(value: &str) -> Option<(u64, u64, u64)> {
393    let core = value.split(['-', '+']).next()?;
394    let mut parts = core.split('.').map(|part| part.parse::<u64>().ok());
395    let parsed = (parts.next()??, parts.next()??, parts.next()??);
396    parts.next().is_none().then_some(parsed)
397}
398
399#[cfg(test)]
400mod tests;