Skip to main content

rings_node/onion/https/
client.rs

1//! Client half of the HTTPS onion protocol, shared by native and browser callers.
2//!
3//! One request is one session. Route selection is the caller's platform decision (a browser must
4//! start at a direct peer and may read a remote directory); everything after it is target
5//! independent:
6//!
7//! ```text
8//! url ──OnionHttpsCall::from_url──▶ (target, call)
9//!     ──route(target)───────────▶ OnionProxyRoute                      [caller]
10//!     ──open(route, https, t, b)▶ session                              [exit answers the open]
11//!     ──data(enc(request)) · fin─▶ h                                    [the exit fetches]
12//!     ◀──data(enc(outcome)) · fin─ h ──▶ response | exit failure       [within the deadline]
13//! ```
14//!
15//! Laws:
16//! - Target binding: an [`OnionHttpsCall`] names no target; the session is opened for
17//!   `route.target`, whose digest `h` binds, so the request cannot disagree with its route.
18//! - Ownership: the session lives as long as the request's future; dropping it (caller
19//!   cancellation, the deadline) ends the session's driver and releases its tags.
20//! - Authentication: the response arrives in replies that open under the session's reply keys,
21//!   which only the client and the exit's process hold (#834 Prop. Reply authentication).
22
23use std::time::Duration;
24
25use bytes::Bytes;
26use futures::future::Either;
27use futures::FutureExt;
28use rings_runtime::sleep;
29use serde::Deserialize;
30
31use super::decode_outcome;
32use super::default_method;
33use super::encode_request;
34use super::normalize_method;
35use super::normalize_path;
36use super::OnionHttpsOutcome;
37use super::OnionHttpsRequest;
38use super::OnionHttpsResponse;
39use crate::error::Error;
40use crate::error::Result;
41use crate::onion::proxy::OnionProxyRoute;
42use crate::onion::proxy::OnionProxyTarget;
43use crate::onion::runtime::OnionRuntime;
44use crate::onion::session::client::OnionCreditWindow;
45use crate::onion::session::dial::OnionSessionRequest;
46use crate::onion::session::dial::OnionStreamEvent;
47use crate::onion::sphinx::class::OnionLoopClass;
48use crate::onion::OnionRouteError;
49use crate::onion::OnionServiceName;
50
51/// Longest wait for the exit's whole response once the session has opened.
52pub(crate) const ONION_HTTPS_RESPONSE_TIMEOUT: Duration = Duration::from_secs(30);
53
54/// The largest encoded response the client collects: the exit's body limit and its framing.
55const MAX_HTTPS_OUTCOME_BYTES: usize = 9 * 1024 * 1024;
56
57/// Caller-facing request fields for one HTTPS proxy request.
58#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
59pub struct OnionHttpsClientRequest {
60    /// HTTP method. Defaults to `GET`.
61    #[serde(default = "default_method")]
62    pub method: String,
63    /// Optional path and query override. Defaults to the request URL path, then `/`.
64    #[serde(default)]
65    pub path: Option<String>,
66    /// Request headers.
67    #[serde(default)]
68    pub headers: Vec<(String, String)>,
69    /// Request body bytes.
70    #[serde(default, deserialize_with = "deserialize_request_body")]
71    pub body: Vec<u8>,
72    /// Optional loop class `b` for the request's session. Defaults to
73    /// [`OnionLoopClass::DEFAULT`] (`16 KiB`) when `None`.
74    ///
75    /// Every hop on the loop sees `b` (#834 leakage table), and each cell of the loop costs
76    /// `b / 16 KiB` admission units ([`OnionLoopClass::units`]).
77    #[serde(default)]
78    pub class: Option<OnionLoopClass>,
79}
80
81/// Deserialize a request body from either raw byte buffers (`Uint8Array` / `&[u8]`) or a sequence
82/// of `u8` values (`Array` / JSON `[1, 2, 3]`).
83fn deserialize_request_body<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error>
84where D: serde::Deserializer<'de> {
85    struct RequestBodyVisitor;
86
87    impl<'de> serde::de::Visitor<'de> for RequestBodyVisitor {
88        type Value = Vec<u8>;
89
90        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91            f.write_str("a byte buffer or byte array")
92        }
93
94        fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E> {
95            Ok(v.to_vec())
96        }
97
98        fn visit_byte_buf<E>(self, v: Vec<u8>) -> std::result::Result<Self::Value, E> {
99            Ok(v)
100        }
101
102        fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
103        where A: serde::de::SeqAccess<'de> {
104            let mut bytes = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(4096));
105            while let Some(byte) = seq.next_element::<u8>()? {
106                bytes.push(byte);
107            }
108            Ok(bytes)
109        }
110    }
111
112    deserializer.deserialize_bytes(RequestBodyVisitor)
113}
114
115/// Normalized HTTPS request that names no target.
116///
117/// Constructing a call is the proof that its method and path are normalized. A call is addressed
118/// only when it is sent, to the target of the route it is sent over, so a request cannot disagree
119/// with its route.
120#[derive(Debug)]
121pub struct OnionHttpsCall {
122    method: String,
123    path: String,
124    headers: Vec<(String, String)>,
125    body: Vec<u8>,
126    class: OnionLoopClass,
127}
128
129impl OnionHttpsCall {
130    /// Split an absolute `https://` URL into the target to route to and the normalized call.
131    ///
132    /// The URL path is the default; `request.path` overrides it, and `request.class` selects the
133    /// session's loop class `b` (defaulting to [`OnionLoopClass::DEFAULT`], `16 KiB`).
134    pub fn from_url(
135        url: &str,
136        request: OnionHttpsClientRequest,
137    ) -> Result<(OnionProxyTarget, Self)> {
138        let (target, path) = parse_https_url(url)?;
139        Ok((target, Self::with_default_path(request, path)?))
140    }
141
142    /// Set the loop class `b` for the session that sends this call.
143    ///
144    /// Every hop on the loop sees `b` (#834 leakage table), and each cell of the loop costs
145    /// `b / 16 KiB` admission units ([`OnionLoopClass::units`]).
146    pub const fn with_class(mut self, class: OnionLoopClass) -> Self {
147        self.class = class;
148        self
149    }
150
151    /// Return the loop class `b` selected for this call's session.
152    pub const fn class(&self) -> OnionLoopClass {
153        self.class
154    }
155
156    /// Normalize `request`, using `default_path` when it carries no path override.
157    pub(super) fn with_default_path(
158        request: OnionHttpsClientRequest,
159        default_path: &str,
160    ) -> Result<Self> {
161        Ok(Self {
162            method: normalize_method(&request.method),
163            path: normalize_path(request.path.as_deref().unwrap_or(default_path))?,
164            headers: request.headers,
165            body: request.body,
166            class: request.class.unwrap_or(OnionLoopClass::DEFAULT),
167        })
168    }
169
170    /// The wire request this call becomes; its authority is the session's target, and its loop
171    /// class `b` is a session parameter rather than a wire field of the request.
172    pub(super) fn into_request(self) -> OnionHttpsRequest {
173        OnionHttpsRequest {
174            method: self.method,
175            path: self.path,
176            headers: self.headers,
177            body: self.body,
178        }
179    }
180}
181
182/// The HTTPS onion client of one node: every request is a session over the node's runtime.
183#[derive(Clone)]
184pub(crate) struct OnionHttpsClient {
185    /// The node's onion runtime.
186    runtime: OnionRuntime,
187}
188
189impl OnionHttpsClient {
190    /// The client over `runtime`.
191    pub(crate) const fn new(runtime: OnionRuntime) -> Self {
192        Self { runtime }
193    }
194
195    /// Send `call` to `route.target` over `route` in a session of [`OnionHttpsCall::class`] and
196    /// wait for the exit's response.
197    ///
198    /// Dropping the returned future ends the session; an exit that does not answer within
199    /// [`ONION_HTTPS_RESPONSE_TIMEOUT`] of the open yields [`Error::OnionProxyRequestTimedOut`].
200    ///
201    /// # Errors
202    ///
203    /// The session's refusal or failure, the exit's reported failure, or the timeout.
204    pub(crate) async fn request(
205        &self,
206        route: &OnionProxyRoute,
207        call: OnionHttpsCall,
208    ) -> Result<OnionHttpsResponse> {
209        let class = call.class();
210        self.request_with_class(route, call, class).await
211    }
212
213    /// Send `call` to `route.target` over `route` in a session of loop class `class` (`b`) and
214    /// wait for the exit's response.
215    ///
216    /// Every hop on the loop sees `b` (#834 leakage table), and each cell of the loop costs
217    /// `b / 16 KiB` admission units ([`OnionLoopClass::units`]).
218    /// Dropping the returned future ends the session; an exit that does not answer within
219    /// [`ONION_HTTPS_RESPONSE_TIMEOUT`] of the open yields [`Error::OnionProxyRequestTimedOut`].
220    ///
221    /// # Errors
222    ///
223    /// The session's refusal or failure, the exit's reported failure, or the timeout.
224    pub(crate) async fn request_with_class(
225        &self,
226        route: &OnionProxyRoute,
227        call: OnionHttpsCall,
228        class: OnionLoopClass,
229    ) -> Result<OnionHttpsResponse> {
230        let request = encode_request(&call.into_request())?;
231        let (mut sender, mut receiver) = self
232            .runtime
233            .open(OnionSessionRequest {
234                route: route.route.clone(),
235                symbol: OnionServiceName::https(),
236                target: route.target.clone(),
237                class,
238                window: OnionCreditWindow::DEFAULT,
239            })
240            .await?
241            .split();
242        sender.send(Bytes::from(request)).await?;
243        sender.fin().await?;
244        let collect = async {
245            let mut outcome = Vec::new();
246            loop {
247                match receiver.next().await {
248                    Some(OnionStreamEvent::Data(bytes)) => {
249                        if outcome.len().saturating_add(bytes.len()) > MAX_HTTPS_OUTCOME_BYTES {
250                            return Err(Error::NoPermission);
251                        }
252                        outcome.extend_from_slice(&bytes);
253                    }
254                    Some(OnionStreamEvent::Fin) => return client_outcome(&outcome),
255                    Some(OnionStreamEvent::Failed) | None => {
256                        return Err(Error::OnionRouteError(OnionRouteError::HttpsResponseClosed))
257                    }
258                }
259            }
260        };
261        let deadline = sleep(ONION_HTTPS_RESPONSE_TIMEOUT).fuse();
262        futures::pin_mut!(collect, deadline);
263        match futures::future::select(collect, deadline).await {
264            Either::Left((outcome, _)) => outcome,
265            Either::Right(_) => Err(Error::OnionProxyRequestTimedOut),
266        }
267    }
268}
269
270/// Interpret the world-to-client stream of a fetch as the client's result.
271fn client_outcome(bytes: &[u8]) -> Result<OnionHttpsResponse> {
272    match decode_outcome(bytes)? {
273        OnionHttpsOutcome::Response(response) => Ok(response),
274        OnionHttpsOutcome::Error(failure) => Err(Error::OnionRouteError(
275            OnionRouteError::ExitFailure(failure),
276        )),
277    }
278}
279
280/// Split an absolute `https://` URL into its canonical target and its path-and-query.
281fn parse_https_url(url: &str) -> Result<(OnionProxyTarget, &str)> {
282    let url = url.trim();
283    let (scheme, rest) = url.split_once("://").ok_or_else(|| {
284        Error::HttpRequestError("HTTPS onion proxy request URL must be absolute".to_string())
285    })?;
286    if !scheme.eq_ignore_ascii_case("https") {
287        return Err(Error::HttpRequestError(format!(
288            "HTTPS onion proxy only supports https URLs, got scheme {scheme:?}"
289        )));
290    }
291    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
292    let (authority, suffix) = rest.split_at(authority_end);
293    if authority.contains('@') {
294        return Err(Error::HttpRequestError(
295            "HTTPS onion proxy URLs must not contain userinfo".to_string(),
296        ));
297    }
298    let authority = https_authority_with_default_port(authority)?;
299    let target = OnionProxyTarget::parse_authority(authority.as_str())?;
300    Ok((target, url_path(suffix)))
301}
302
303/// Validate a URL authority and make its port explicit, defaulting to 443.
304fn https_authority_with_default_port(authority: &str) -> Result<String> {
305    let authority = authority.trim();
306    if authority.is_empty() {
307        return Err(Error::HttpRequestError(
308            "HTTPS onion proxy URL host must not be empty".to_string(),
309        ));
310    }
311
312    if let Some(rest) = authority.strip_prefix('[') {
313        let Some((host, suffix)) = rest.split_once(']') else {
314            return Err(Error::HttpRequestError(format!(
315                "invalid IPv6 HTTPS onion proxy authority {authority:?}"
316            )));
317        };
318        if host.is_empty() {
319            return Err(Error::HttpRequestError(
320                "HTTPS onion proxy URL host must not be empty".to_string(),
321            ));
322        }
323        return if suffix.is_empty() {
324            Ok(format!("[{host}]:443"))
325        } else if let Some(port) = suffix.strip_prefix(':') {
326            if port.is_empty() {
327                Err(Error::HttpRequestError(format!(
328                    "HTTPS onion proxy authority {authority:?} has an empty port"
329                )))
330            } else {
331                Ok(authority.to_string())
332            }
333        } else {
334            Err(Error::HttpRequestError(format!(
335                "invalid IPv6 HTTPS onion proxy authority {authority:?}"
336            )))
337        };
338    }
339
340    if authority.contains('[') || authority.contains(']') {
341        return Err(Error::HttpRequestError(format!(
342            "invalid HTTPS onion proxy authority {authority:?}"
343        )));
344    }
345    let colon_count = authority.chars().filter(|ch| *ch == ':').count();
346    if colon_count > 1 {
347        return Err(Error::HttpRequestError(
348            "IPv6 HTTPS onion proxy URLs must use bracketed hosts".to_string(),
349        ));
350    }
351    if colon_count == 1 {
352        let Some((host, port)) = authority.rsplit_once(':') else {
353            return Err(Error::HttpRequestError(format!(
354                "invalid HTTPS onion proxy authority {authority:?}"
355            )));
356        };
357        if host.is_empty() || port.is_empty() {
358            return Err(Error::HttpRequestError(format!(
359                "invalid HTTPS onion proxy authority {authority:?}"
360            )));
361        }
362        Ok(authority.to_string())
363    } else {
364        Ok(format!("{authority}:443"))
365    }
366}
367
368/// Path-and-query of the URL suffix after the authority, with the fragment removed. An empty
369/// path and a bare query are canonicalized by `normalize_path`, as every call's path is.
370fn url_path(suffix: &str) -> &str {
371    suffix
372        .split_once('#')
373        .map_or(suffix, |(before_fragment, _)| before_fragment)
374}