Skip to main content

rings_node/onion/https/
mod.rs

1//! `https`: one HTTPS request/response fetch over an onion session (#834 D1′, D2′).
2//!
3//! `https` is a fetch only; every byte tunnel, TLS included, is `tcp`. A fetch is a session whose
4//! client-to-world stream is one encoded request and whose world-to-client stream is one encoded
5//! outcome:
6//!
7//! ```text
8//! client ── data(…enc(OnionHttpsRequest)…) ── fin ──▶ h ── fetch(t, request) ──▶ world
9//! client ◀── data(…enc(OnionHttpsOutcome)…) ── fin ── h
10//! ```
11//!
12//! The session's target `t`, bound at `h` by its digest, is the fetch's authority, so the request
13//! names none and cannot disagree with it. The exit half is the fetch world
14//! (`OnionHttpsWorld`), interpreted by the session shell; the client half is in `client`.
15//!
16//! A browser page exit is constrained by the host browser's `fetch` capability: CORS, forbidden
17//! headers, credentials policy, and extension host permissions still apply. A full arbitrary HTTPS
18//! exit must run in a browser-extension or native context that grants those fetch permissions.
19
20use bytes::Bytes;
21use futures::channel::oneshot;
22use serde::Deserialize;
23use serde::Serialize;
24
25#[cfg(rings_browser)]
26use self::browser::execute_https_request;
27pub use self::client::OnionHttpsCall;
28pub(crate) use self::client::OnionHttpsClient;
29pub use self::client::OnionHttpsClientRequest;
30#[cfg(all(test, rings_native))]
31pub(crate) use self::client::ONION_HTTPS_RESPONSE_TIMEOUT;
32#[cfg(all(test, rings_native))]
33use self::limits::checked_status_code;
34#[cfg(all(test, rings_native))]
35use self::limits::drive_cancellable_https_fetch;
36use self::limits::https_response_body_limit;
37#[cfg(all(test, rings_native))]
38use self::limits::CancellableHttpsFetch;
39#[cfg(all(test, rings_native))]
40use self::limits::FetchCancelTarget;
41#[cfg(all(test, rings_native))]
42use self::limits::FetchCancellationGuard;
43#[cfg(rings_native)]
44use self::native::execute_https_request;
45#[cfg(all(test, rings_native))]
46use self::native::is_native_transport_managed_header;
47#[cfg(all(test, rings_native))]
48use self::native::native_fetch_with_timeout;
49#[cfg(all(test, rings_native))]
50use self::native::NativeHttpsEgress;
51use crate::error::Error;
52use crate::error::Result;
53use crate::onion::exit_accounting::OnionExitAccounting;
54use crate::onion::proxy::OnionProxyTarget;
55use crate::onion::session::serve::OnionWorld;
56use crate::onion::session::serve::OnionWorldReader;
57use crate::onion::session::serve::OnionWorldWriter;
58use crate::onion::OnionExitFailure;
59use crate::onion::OnionExitPolicy;
60
61/// The default and largest response body an exit fetches for one request.
62const DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES: u64 = 8 * 1024 * 1024;
63
64/// The largest encoded request an exit buffers for one session.
65const MAX_HTTPS_REQUEST_BYTES: usize = 8 * 1024 * 1024;
66
67/// One HTTPS request of a fetch session; its authority is the session's target.
68#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
69pub struct OnionHttpsRequest {
70    /// HTTP method.
71    pub method: String,
72    /// Path and query.
73    pub path: String,
74    /// Request headers.
75    pub headers: Vec<(String, String)>,
76    /// Request body bytes.
77    pub body: Vec<u8>,
78}
79
80/// One HTTPS response returned by an HTTPS exit.
81#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
82pub struct OnionHttpsResponse {
83    /// HTTP status code.
84    pub status: u16,
85    /// Response headers.
86    pub headers: Vec<(String, String)>,
87    /// Response body bytes.
88    pub body: Vec<u8>,
89}
90
91/// What a fetch session's world-to-client stream encodes: the response, or why there is none.
92#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
93pub(crate) enum OnionHttpsOutcome {
94    /// The exit fetched a response.
95    Response(OnionHttpsResponse),
96    /// The exit could not fetch one.
97    Error(OnionExitFailure),
98}
99
100/// Encode a request, the client-to-world stream of a fetch.
101pub(crate) fn encode_request(request: &OnionHttpsRequest) -> Result<Vec<u8>> {
102    rings_codec::serialize(request).map_err(|_| Error::EncodeError)
103}
104
105/// Encode an outcome, the world-to-client stream of a fetch.
106pub(crate) fn encode_outcome(outcome: &OnionHttpsOutcome) -> Result<Vec<u8>> {
107    rings_codec::serialize(outcome).map_err(|_| Error::EncodeError)
108}
109
110/// Decode the world-to-client stream of a fetch.
111pub(crate) fn decode_outcome(bytes: &[u8]) -> Result<OnionHttpsOutcome> {
112    rings_codec::deserialize(bytes).map_err(|_| Error::DecodeError)
113}
114
115/// Where a fetch world's requests leave: the platform's fetch, or a test's function of the
116/// target and the request.
117#[derive(Clone, Copy)]
118pub(crate) enum OnionHttpsEgress {
119    /// The platform's fetch (`native` or `browser`).
120    Platform,
121    /// A test egress answering every request in place of the network.
122    #[cfg(all(test, rings_native))]
123    Test(fn(&OnionProxyTarget, &OnionHttpsRequest) -> OnionHttpsResponse),
124}
125
126/// The fetch world of an `https` exit: a session's request, fetched once its stream ends.
127pub(crate) struct OnionHttpsWorld {
128    /// The exit policy targets are admitted under.
129    policy: OnionExitPolicy,
130    /// The node-wide exit accounting, which bounds the response bytes.
131    accounting: OnionExitAccounting,
132    /// Where the requests leave.
133    egress: OnionHttpsEgress,
134}
135
136impl OnionHttpsWorld {
137    /// The fetch world of an exit under `policy` and `accounting`, fetching through the platform.
138    pub(crate) const fn new(policy: OnionExitPolicy, accounting: OnionExitAccounting) -> Self {
139        Self::with_egress(policy, accounting, OnionHttpsEgress::Platform)
140    }
141
142    /// The fetch world of an exit whose requests leave through `egress`.
143    pub(crate) const fn with_egress(
144        policy: OnionExitPolicy,
145        accounting: OnionExitAccounting,
146        egress: OnionHttpsEgress,
147    ) -> Self {
148        Self {
149            policy,
150            accounting,
151            egress,
152        }
153    }
154}
155
156/// The write half of a fetch: it buffers the encoded request and hands it over at `fin`.
157pub(crate) struct OnionHttpsWriter {
158    /// The request bytes so far.
159    request: Vec<u8>,
160    /// Where the complete request goes; spent at `fin`.
161    complete: Option<oneshot::Sender<Vec<u8>>>,
162}
163
164/// The read half of a fetch: it waits for the request, fetches, and serves the encoded outcome.
165pub(crate) struct OnionHttpsReader {
166    /// The session's target, the fetch's authority.
167    target: OnionProxyTarget,
168    /// The policy, for the fetch's byte accounting.
169    policy: OnionExitPolicy,
170    /// The accounting.
171    accounting: OnionExitAccounting,
172    /// Where the request leaves.
173    egress: OnionHttpsEgress,
174    /// The complete request, until it arrives.
175    request: Option<oneshot::Receiver<Vec<u8>>>,
176    /// The encoded outcome not yet read.
177    outcome: Bytes,
178}
179
180#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
181#[cfg_attr(rings_native, async_trait::async_trait)]
182impl OnionWorld for OnionHttpsWorld {
183    type Reader = OnionHttpsReader;
184    type Writer = OnionHttpsWriter;
185
186    async fn open(&self, target: &OnionProxyTarget) -> Result<(Self::Reader, Self::Writer)> {
187        let (complete, request) = oneshot::channel();
188        Ok((
189            OnionHttpsReader {
190                target: target.clone(),
191                policy: self.policy.clone(),
192                accounting: self.accounting.clone(),
193                egress: self.egress,
194                request: Some(request),
195                outcome: Bytes::new(),
196            },
197            OnionHttpsWriter {
198                request: Vec::new(),
199                complete: Some(complete),
200            },
201        ))
202    }
203}
204
205#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
206#[cfg_attr(rings_native, async_trait::async_trait)]
207impl OnionWorldWriter for OnionHttpsWriter {
208    async fn write(&mut self, bytes: Bytes) -> Result<()> {
209        if self.request.len().saturating_add(bytes.len()) > MAX_HTTPS_REQUEST_BYTES {
210            return Err(Error::NoPermission);
211        }
212        self.request.extend_from_slice(&bytes);
213        Ok(())
214    }
215
216    async fn shutdown(&mut self) -> Result<()> {
217        if let Some(complete) = self.complete.take() {
218            let _ = complete.send(std::mem::take(&mut self.request));
219        }
220        Ok(())
221    }
222}
223
224#[cfg_attr(rings_browser, async_trait::async_trait(?Send))]
225#[cfg_attr(rings_native, async_trait::async_trait)]
226impl OnionWorldReader for OnionHttpsReader {
227    /// The first read waits for the whole request, fetches it and encodes the outcome; every read
228    /// then serves the next `max` bytes of it, and `None` after the last.
229    async fn read(&mut self, max: usize) -> Result<Option<Bytes>> {
230        if let Some(request) = self.request.take() {
231            // A session that closes before its `fin` has no request, and ends here.
232            let Ok(request) = request.await else {
233                return Ok(None);
234            };
235            let outcome = match rings_codec::deserialize::<OnionHttpsRequest>(&request) {
236                Ok(request) => match self.fetch(&request).await {
237                    Ok(response) => OnionHttpsOutcome::Response(response),
238                    Err(error) => OnionHttpsOutcome::Error(OnionExitFailure::from_error(&error)),
239                },
240                Err(_) => OnionHttpsOutcome::Error(OnionExitFailure::MalformedRequest),
241            };
242            self.outcome = Bytes::from(encode_outcome(&outcome)?);
243        }
244        if self.outcome.is_empty() {
245            return Ok(None);
246        }
247        let length = max.min(self.outcome.len());
248        Ok(Some(self.outcome.split_to(length)))
249    }
250}
251
252impl OnionHttpsReader {
253    /// Fetch `request` at the session's target through the reader's egress.
254    async fn fetch(&self, request: &OnionHttpsRequest) -> Result<OnionHttpsResponse> {
255        match self.egress {
256            OnionHttpsEgress::Platform => {
257                fetch(&self.target, request, &self.policy, &self.accounting).await
258            }
259            #[cfg(all(test, rings_native))]
260            OnionHttpsEgress::Test(respond) => Ok(respond(&self.target, request)),
261        }
262    }
263}
264
265/// Fetch `request` at `target`, the session's authority, recording the response's headers and
266/// body chunks against the policy's byte budget as they arrive, and refusing past it: the
267/// budget holds across every concurrent fetch, and these are the reader's own records (every
268/// world records what it reads; the session shell records only writes).
269async fn fetch(
270    target: &OnionProxyTarget,
271    request: &OnionHttpsRequest,
272    policy: &OnionExitPolicy,
273    accounting: &OnionExitAccounting,
274) -> Result<OnionHttpsResponse> {
275    let body_limit =
276        https_response_body_limit(accounting.remaining_bytes(policy, accounting.now_ms())?);
277    if body_limit == 0 {
278        return Err(Error::NoPermission);
279    }
280    let url = format!(
281        "https://{}{}",
282        target.authority(),
283        normalize_path(&request.path)?
284    );
285    execute_https_request(&url, target, request, body_limit, |bytes| {
286        accounting.record_bytes(policy, bytes, accounting.now_ms())
287    })
288    .await
289}
290
291/// Return whether the HTTPS exit transport, rather than the onion client, owns this request header.
292///
293/// The validated session target is the sole authority source, and message framing / hop-by-hop
294/// headers belong to the exit's HTTP client (`reqwest` on native, `fetch` on browser).
295pub(crate) fn is_transport_managed_header(name: &str) -> bool {
296    [
297        "host",
298        ":authority",
299        "connection",
300        "proxy-connection",
301        "keep-alive",
302        "proxy-authenticate",
303        "proxy-authorization",
304        "te",
305        "trailer",
306        "transfer-encoding",
307        "content-length",
308        "upgrade",
309        "expect",
310    ]
311    .iter()
312    .any(|managed| name.eq_ignore_ascii_case(managed))
313}
314
315/// The canonical form of a method: trimmed, upper case, `GET` when empty.
316fn normalize_method(method: &str) -> String {
317    let method = method.trim();
318    if method.is_empty() {
319        default_method()
320    } else {
321        method.to_ascii_uppercase()
322    }
323}
324
325/// The canonical form of a path and query: `/` when empty, `/?q` for a bare query.
326fn normalize_path(path: &str) -> Result<String> {
327    let path = path.trim();
328    if path.is_empty() {
329        return Ok(default_path());
330    }
331    if path.starts_with('/') {
332        return Ok(path.to_string());
333    }
334    if path.starts_with('?') {
335        return Ok(format!("/{path}"));
336    }
337    Err(Error::HttpRequestError(format!(
338        "HTTPS onion proxy path must start with '/' or '?', got {path:?}"
339    )))
340}
341
342/// The default method, `GET`.
343fn default_method() -> String {
344    "GET".to_string()
345}
346
347/// The default path, `/`.
348fn default_path() -> String {
349    "/".to_string()
350}
351
352#[cfg(all(test, rings_native))]
353mod tests;
354
355#[cfg(rings_browser)]
356mod browser;
357mod client;
358mod limits;
359#[cfg(rings_native)]
360mod native;