1use 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
38pub const PROTOCOL_HEADER: &str = "x-capsule-protocol";
40pub const PROTOCOL_MIN_HEADER: &str = "x-capsule-protocol-min";
42pub const PROTOCOL_MAX_HEADER: &str = "x-capsule-protocol-max";
44pub const MIN_CLIENT_BUILD_HEADER: &str = "x-capsule-min-client-build";
46
47pub const PROTOCOL_VERSION: &str = capsule_core::crypto::primitives::PROTOCOL_VERSION;
49
50pub const CLIENT_BUILD: &str = env!("CARGO_PKG_VERSION");
53
54#[derive(Debug, Clone, Default, PartialEq, Eq)]
56pub struct ServerWindow {
57 pub protocol_min: Option<String>,
59 pub protocol_max: Option<String>,
61 pub min_client_build: Option<String>,
63}
64
65impl ServerWindow {
66 #[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 #[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum UpgradeReason {
118 Refused,
120 ProtocolBelowWindow,
122 ProtocolAboveWindow,
124 BuildBelowFloor,
126}
127
128#[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 pub reason: UpgradeReason,
142 pub window: Box<ServerWindow>,
144 pub protocol: String,
147 pub message: String,
149}
150
151impl UpgradeRequired {
152 #[must_use]
154 pub fn error_code(&self) -> &'static str {
155 error_codes::PROTOCOL_VERSION_UNSUPPORTED
156 }
157
158 #[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#[must_use]
176pub fn is_write(method: &Method) -> bool {
177 !matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
178}
179
180#[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
191pub 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#[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#[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
231pub 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
255pub 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
278pub fn forget(url: &Url) {
282 latch()
283 .lock()
284 .unwrap_or_else(PoisonError::into_inner)
285 .remove(&origin_of(url));
286}
287
288#[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#[derive(Debug)]
299pub(crate) enum SendError {
300 Upgrade(UpgradeRequired),
302 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
318pub(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
332pub(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#[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
377pub(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
390fn 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;