rings-node 0.20.0

Rings is a structured peer-to-peer network implementation using WebRTC, Chord algorithm, and full WebAssembly (WASM) support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! HTTPS onion-exit request/response adapter.
//!
//! This protocol is intentionally application-layer HTTPS. Clients can send an HTTPS request
//! description over the route-aware onion circuit, the exit performs the request, and the response
//! is sent back over the circuit return path.
//!
//! A browser page exit is constrained by the host browser's `fetch` capability: CORS, forbidden
//! headers, credentials policy, and extension host permissions still apply. A full arbitrary HTTPS
//! exit must run in a browser-extension or native context that grants those fetch permissions.

#[cfg(any(test, rings_browser))]
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;

use bytes::Bytes;
#[cfg(any(test, rings_browser))]
use futures::channel::oneshot;
use rings_core::dht::Did;
use rings_core::session::SessionSk;
use serde::Deserialize;
use serde::Serialize;

#[cfg(rings_browser)]
use self::browser::execute_https_request;
#[cfg(test)]
use self::limits::checked_status_code;
use self::limits::https_response_body_limit;
use self::limits::usize_to_u64;
#[cfg(rings_native)]
use self::native::execute_https_request;
#[cfg(all(test, rings_native))]
use self::native::native_fetch_with_timeout;
#[cfg(all(test, rings_native))]
use self::native::select_native_https_egress;
#[cfg(all(test, rings_native))]
use self::native::NativeHttpsEgress;
#[cfg(any(test, rings_browser))]
use self::pending::PendingOnionHttpsRequest;
use crate::error::Error;
use crate::error::Result;
use crate::extension::ext::Scope;
use crate::onion::circuit::send_backward;
#[cfg(any(test, rings_browser))]
use crate::onion::circuit::OnionAuthenticatedPayload;
use crate::onion::circuit::OnionBackwardPath;
use crate::onion::circuit::OnionBackwardSequence;
use crate::onion::circuit::OnionCircuitExitFrame;
#[cfg(rings_browser)]
use crate::onion::circuit::OnionCircuitHandler;
use crate::onion::circuit::OnionCircuitId;
use crate::onion::circuit::OnionCircuitPayload;
use crate::onion::circuit::OnionForwardNonce;
use crate::onion::circuit::OnionForwardSequence;
use crate::onion::circuit::OnionLinkSender;
#[cfg(any(test, rings_browser))]
use crate::onion::circuit::OnionReturnId;
use crate::onion::exit_accounting::OnionExitAccounting;
use crate::onion::exit_accounting::OnionExitLease;
use crate::onion::proxy::OnionProxyTarget;
use crate::onion::proxy::ONION_PROXY_HTTPS_SERVICE;
use crate::onion::replay::OnionForwardReplayKey;
use crate::onion::replay::OnionForwardReplayPartitions;
use crate::onion::replay::ReplayAdmission;
#[cfg(any(test, rings_browser))]
use crate::onion::OnionExitDescriptor;
use crate::onion::OnionExitFailure;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionExitTarget;
use crate::onion::OnionRouteError;
use crate::sync_lock::lock;

const DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES: u64 = 8 * 1024 * 1024;

/// One HTTPS request executed by an HTTPS exit.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnionHttpsRequest {
    /// Target authority (`host:port`).
    pub target: String,
    /// HTTP method.
    pub method: String,
    /// Path and query.
    pub path: String,
    /// Request headers.
    pub headers: Vec<(String, String)>,
    /// Request body bytes.
    pub body: Vec<u8>,
}

/// One HTTPS response returned by an HTTPS exit.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnionHttpsResponse {
    /// HTTP status code.
    pub status: u16,
    /// Response headers.
    pub headers: Vec<(String, String)>,
    /// Response body bytes.
    pub body: Vec<u8>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) enum OnionHttpsPayload {
    Request(OnionHttpsRequest),
    Response(OnionHttpsResponse),
    Error(OnionExitFailure),
}

pub(crate) fn encode_https_payload(payload: OnionHttpsPayload) -> Result<OnionCircuitPayload> {
    rings_codec::serialize(&payload)
        .map(|body| {
            OnionCircuitPayload::new(crate::onion::OnionServiceName::https(), Bytes::from(body))
        })
        .map_err(|_| Error::EncodeError)
}

fn decode_https_payload(payload: OnionCircuitPayload) -> Result<Option<OnionHttpsPayload>> {
    if !payload.matches_service(ONION_PROXY_HTTPS_SERVICE) {
        return Ok(None);
    }
    rings_codec::deserialize(payload.body.as_ref())
        .map(Some)
        .map_err(|_| Error::DecodeError)
}

/// JS-facing request fields for one HTTPS proxy request.
#[cfg(any(test, rings_browser))]
#[cfg_attr(test, derive(Default))]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct OnionHttpsClientRequest {
    /// HTTP method. Defaults to `GET`.
    #[serde(default = "default_method")]
    pub method: String,
    /// Optional path and query override. Defaults to the request URL path, then `/`.
    #[serde(default)]
    pub path: Option<String>,
    /// Request headers.
    #[serde(default)]
    pub headers: Vec<(String, String)>,
    /// Request body bytes.
    #[serde(default)]
    pub body: Vec<u8>,
}

/// JS-facing response fields returned from one HTTPS proxy request.
#[cfg(any(test, rings_browser))]
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct OnionHttpsClientResponse {
    /// HTTP status code.
    pub status: u16,
    /// Response headers.
    pub headers: Vec<(String, String)>,
    /// Response body bytes.
    pub body: Vec<u8>,
}

/// Shared runtime for the local HTTPS proxy protocol.
pub(crate) struct OnionHttpsRuntime {
    #[cfg(any(test, rings_browser))]
    pending: Mutex<HashMap<OnionCircuitId, PendingRequest>>,
    exit_policy: Mutex<Option<OnionExitPolicy>>,
    forward_replays: Mutex<OnionForwardReplayPartitions>,
    accounting: OnionExitAccounting,
    link_sender: OnionLinkSender,
    #[cfg(rings_native)]
    native_proxy: Mutex<Option<String>>,
}

impl Default for OnionHttpsRuntime {
    fn default() -> Self {
        Self::with_resources(OnionExitAccounting::default(), OnionLinkSender::default())
    }
}

#[cfg(any(test, rings_browser))]
struct PendingRequest {
    expected_return_peer: Did,
    expected_exit: OnionExitDescriptor,
    return_id: OnionReturnId,
    sender: oneshot::Sender<std::result::Result<OnionHttpsClientResponse, Error>>,
}

impl OnionHttpsRuntime {
    /// Create an empty runtime.
    #[cfg(any(test, rings_browser))]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Create a runtime sharing node-wide accounting and link-traffic effect capabilities.
    pub(crate) fn with_resources(
        accounting: OnionExitAccounting,
        link_sender: OnionLinkSender,
    ) -> Self {
        Self {
            #[cfg(any(test, rings_browser))]
            pending: Mutex::new(HashMap::new()),
            exit_policy: Mutex::new(None),
            forward_replays: Mutex::new(OnionForwardReplayPartitions::default()),
            accounting,
            link_sender,
            #[cfg(rings_native)]
            native_proxy: Mutex::new(None),
        }
    }

    #[cfg(rings_browser)]
    pub(crate) fn link_sender(&self) -> OnionLinkSender {
        self.link_sender.clone()
    }

    #[cfg(rings_native)]
    pub(crate) fn set_native_proxy(&self, proxy: Option<String>) {
        if let Ok(mut current) = self.native_proxy.lock() {
            *current = proxy;
        }
    }

    #[cfg(rings_native)]
    pub(crate) fn native_proxy(&self) -> Option<String> {
        self.native_proxy
            .lock()
            .ok()
            .and_then(|proxy| proxy.clone())
    }

    #[cfg(all(test, rings_native))]
    pub(crate) fn accounting_for_test(&self) -> OnionExitAccounting {
        self.accounting.clone()
    }

    /// Set the local exit policy. `None` means client-only mode.
    pub(crate) fn set_exit_policy(&self, policy: Option<OnionExitPolicy>) {
        if let Ok(mut current) = self.exit_policy.lock() {
            *current = policy;
        }
    }

    /// Begin a client request expected to complete from the immediate return peer.
    #[cfg(any(test, rings_browser))]
    pub(crate) fn begin_request(
        self: &Arc<Self>,
        expected_return_peer: Did,
        expected_exit: OnionExitDescriptor,
        return_id: OnionReturnId,
    ) -> Result<(OnionCircuitId, PendingOnionHttpsRequest)> {
        let mut pending = lock(&self.pending)?;
        for _ in 0..16 {
            let id = OnionCircuitId::random();
            if pending.contains_key(&id) {
                continue;
            }
            let (sender, receiver) = oneshot::channel();
            pending.insert(id, PendingRequest {
                expected_return_peer,
                expected_exit,
                return_id,
                sender,
            });
            return Ok((
                id,
                PendingOnionHttpsRequest::new(self.clone(), id, receiver),
            ));
        }
        Err(Error::OnionRouteError(
            OnionRouteError::CircuitIdAllocationFailed,
        ))
    }

    #[cfg(any(test, rings_browser))]
    fn cancel_request(&self, id: OnionCircuitId) {
        if let Ok(mut pending) = self.pending.lock() {
            pending.remove(&id);
        }
    }

    /// Complete a pending HTTPS request with a signed response or error payload.
    #[cfg(any(test, rings_browser))]
    pub(crate) fn complete_payload(
        &self,
        from: Did,
        id: OnionCircuitId,
        payload: OnionAuthenticatedPayload,
    ) {
        let Some((pending, payload)) = self.take_pending_payload(from, id, payload) else {
            return;
        };
        match decode_https_payload(payload) {
            Ok(Some(OnionHttpsPayload::Response(response))) => {
                let _ = pending.sender.send(Ok(OnionHttpsClientResponse {
                    status: response.status,
                    headers: response.headers,
                    body: response.body,
                }));
            }
            Ok(Some(OnionHttpsPayload::Error(failure))) => {
                let _ =
                    pending
                        .sender
                        .send(Err(Error::OnionRouteError(OnionRouteError::ExitFailure(
                            failure,
                        ))));
            }
            Ok(Some(OnionHttpsPayload::Request(_)) | None) => {
                let _ = pending.sender.send(Err(Error::OnionRouteError(
                    OnionRouteError::UnexpectedBackwardPayload,
                )));
            }
            Err(error) => {
                let _ = pending.sender.send(Err(error));
            }
        }
    }

    #[cfg(any(test, rings_browser))]
    fn take_pending_payload(
        &self,
        from: Did,
        id: OnionCircuitId,
        payload: OnionAuthenticatedPayload,
    ) -> Option<(PendingRequest, OnionCircuitPayload)> {
        let mut pending = self.pending.lock().ok()?;
        let request = pending.remove(&id)?;
        if request.expected_return_peer != from {
            pending.insert(id, request);
            return None;
        }
        match payload.into_verified_payload(request.return_id, &request.expected_exit) {
            Ok(verified) => Some((request, verified.payload)),
            Err(error) => {
                let _ = request.sender.send(Err(error));
                None
            }
        }
    }

    pub(crate) fn exit_policy(&self) -> Option<OnionExitPolicy> {
        self.exit_policy
            .lock()
            .ok()
            .and_then(|policy| policy.clone())
    }

    fn admit_exit_request(
        &self,
        policy: &OnionExitPolicy,
        circuit_id: OnionCircuitId,
        return_peer: Did,
        bytes: u64,
    ) -> Result<OnionExitLease> {
        self.accounting
            .admit(policy, circuit_id, return_peer, bytes)
    }

    fn record_exit_bytes(&self, policy: &OnionExitPolicy, bytes: u64) -> Result<()> {
        self.accounting.record_bytes(policy, bytes)
    }

    fn remaining_exit_bytes(&self, policy: &OnionExitPolicy) -> Result<Option<u64>> {
        self.accounting.remaining_bytes(policy)
    }

    fn consume_forward_nonce(
        &self,
        from: Did,
        circuit_id: OnionCircuitId,
        nonce: OnionForwardNonce,
    ) -> Result<()> {
        let mut replays = lock(&self.forward_replays)?;
        match replays.consume(
            from,
            OnionForwardReplayKey::new(circuit_id, nonce),
            rings_core::utils::get_epoch_ms(),
        ) {
            ReplayAdmission::Consumed => Ok(()),
            ReplayAdmission::Duplicate => {
                Err(Error::OnionRouteError(OnionRouteError::ForwardReplay))
            }
            ReplayAdmission::Full => Err(Error::NoPermission),
        }
    }

    #[cfg(test)]
    pub(crate) fn pending_len(&self) -> usize {
        self.pending
            .lock()
            .map(|pending| pending.len())
            .unwrap_or(0)
    }
}

/// Parse a full HTTPS URL and encode one client request for its target.
#[cfg(any(test, rings_browser))]
pub(crate) fn client_request_from_url(
    url: &str,
    request: OnionHttpsClientRequest,
) -> Result<(OnionProxyTarget, OnionHttpsRequest)> {
    let (target, path) = parse_https_url(url)?;
    let request = client_request_with_default_path(&target, request, path.as_str())?;
    Ok((target, request))
}

#[cfg(any(test, rings_browser))]
fn client_request_with_default_path(
    target: &OnionProxyTarget,
    request: OnionHttpsClientRequest,
    default_path: &str,
) -> Result<OnionHttpsRequest> {
    let path = request.path.as_deref().unwrap_or(default_path);
    Ok(OnionHttpsRequest {
        target: target.authority(),
        method: normalize_method(&request.method),
        path: normalize_path(path)?,
        headers: request.headers,
        body: request.body,
    })
}

#[cfg(any(test, rings_browser))]
fn parse_https_url(url: &str) -> Result<(OnionProxyTarget, String)> {
    let url = url.trim();
    let (scheme, rest) = url.split_once("://").ok_or_else(|| {
        Error::HttpRequestError(
            "browser HTTPS onion proxy request URL must be absolute".to_string(),
        )
    })?;
    if !scheme.eq_ignore_ascii_case("https") {
        return Err(Error::HttpRequestError(format!(
            "browser HTTPS onion proxy only supports https URLs, got scheme {scheme:?}"
        )));
    }
    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, suffix) = rest.split_at(authority_end);
    if authority.contains('@') {
        return Err(Error::HttpRequestError(
            "browser HTTPS onion proxy URLs must not contain userinfo".to_string(),
        ));
    }
    let authority = https_authority_with_default_port(authority)?;
    let target = OnionProxyTarget::parse_authority(authority.as_str())?;
    Ok((target, url_path(suffix)))
}

#[cfg(any(test, rings_browser))]
fn https_authority_with_default_port(authority: &str) -> Result<String> {
    let authority = authority.trim();
    if authority.is_empty() {
        return Err(Error::HttpRequestError(
            "browser HTTPS onion proxy URL host must not be empty".to_string(),
        ));
    }

    if let Some(rest) = authority.strip_prefix('[') {
        let Some((host, suffix)) = rest.split_once(']') else {
            return Err(Error::HttpRequestError(format!(
                "invalid IPv6 HTTPS onion proxy authority {authority:?}"
            )));
        };
        if host.is_empty() {
            return Err(Error::HttpRequestError(
                "browser HTTPS onion proxy URL host must not be empty".to_string(),
            ));
        }
        return if suffix.is_empty() {
            Ok(format!("[{host}]:443"))
        } else if let Some(port) = suffix.strip_prefix(':') {
            if port.is_empty() {
                Err(Error::HttpRequestError(format!(
                    "HTTPS onion proxy authority {authority:?} has an empty port"
                )))
            } else {
                Ok(authority.to_string())
            }
        } else {
            Err(Error::HttpRequestError(format!(
                "invalid IPv6 HTTPS onion proxy authority {authority:?}"
            )))
        };
    }

    if authority.contains('[') || authority.contains(']') {
        return Err(Error::HttpRequestError(format!(
            "invalid HTTPS onion proxy authority {authority:?}"
        )));
    }
    let colon_count = authority.chars().filter(|ch| *ch == ':').count();
    if colon_count > 1 {
        return Err(Error::HttpRequestError(
            "IPv6 HTTPS onion proxy URLs must use bracketed hosts".to_string(),
        ));
    }
    if colon_count == 1 {
        let Some((host, port)) = authority.rsplit_once(':') else {
            return Err(Error::HttpRequestError(format!(
                "invalid HTTPS onion proxy authority {authority:?}"
            )));
        };
        if host.is_empty() || port.is_empty() {
            return Err(Error::HttpRequestError(format!(
                "invalid HTTPS onion proxy authority {authority:?}"
            )));
        }
        Ok(authority.to_string())
    } else {
        Ok(format!("{authority}:443"))
    }
}

#[cfg(any(test, rings_browser))]
fn url_path(suffix: &str) -> String {
    let path = suffix
        .split_once('#')
        .map_or(suffix, |(before_fragment, _)| before_fragment);
    if path.is_empty() {
        default_path()
    } else if path.starts_with('?') {
        format!("/{path}")
    } else {
        path.to_string()
    }
}

/// Browser handler for HTTPS onion circuits.
#[cfg(rings_browser)]
pub(crate) struct BrowserOnionCircuitHandler {
    https: Arc<OnionHttpsRuntime>,
    session_sk: SessionSk,
}

#[cfg(rings_browser)]
impl BrowserOnionCircuitHandler {
    /// Create a browser circuit handler backed by the HTTPS runtime.
    pub(crate) fn new(https: Arc<OnionHttpsRuntime>, session_sk: SessionSk) -> Self {
        Self { https, session_sk }
    }
}

#[cfg(rings_browser)]
#[async_trait::async_trait(?Send)]
impl OnionCircuitHandler for BrowserOnionCircuitHandler {
    async fn handle_exit(&self, scope: &Scope, frame: OnionCircuitExitFrame) -> Result<()> {
        let _ = try_handle_https_exit_payload(&self.https, &self.session_sk, scope, frame).await?;
        Ok(())
    }

    async fn handle_client(
        &self,
        _scope: &Scope,
        from: Did,
        circuit_id: OnionCircuitId,
        payload: OnionAuthenticatedPayload,
    ) -> Result<()> {
        self.https.complete_payload(from, circuit_id, payload);
        Ok(())
    }
}

pub(crate) async fn try_handle_https_exit_payload(
    runtime: &Arc<OnionHttpsRuntime>,
    session_sk: &SessionSk,
    scope: &Scope,
    frame: OnionCircuitExitFrame,
) -> Result<bool> {
    if !frame.payload.matches_service(ONION_PROXY_HTTPS_SERVICE) {
        return Ok(false);
    }
    let Some(payload) = (match decode_https_payload(frame.payload) {
        Ok(payload) => payload,
        Err(Error::DecodeError) => return Ok(false),
        Err(error) => return Err(error),
    }) else {
        return Ok(false);
    };
    let response = match payload {
        OnionHttpsPayload::Request(request) => {
            match execute_exit_fetch(
                runtime,
                &request,
                frame.circuit_id,
                frame.return_peer,
                frame.forward_nonce,
                frame.forward_sequence,
            )
            .await
            {
                Ok(response) => OnionHttpsPayload::Response(response),
                Err(error) => OnionHttpsPayload::Error(OnionExitFailure::from_error(&error)),
            }
        }
        OnionHttpsPayload::Response(_) | OnionHttpsPayload::Error(_) => return Ok(true),
    };
    send_backward(
        &runtime.link_sender,
        scope,
        session_sk,
        OnionBackwardPath::new(
            frame.circuit_id,
            frame.return_peer,
            frame.return_session_public_key,
            frame.client,
        ),
        OnionBackwardSequence::FIRST,
        encode_https_payload(response)?,
    )
    .await?;
    Ok(true)
}

pub(crate) async fn execute_exit_fetch(
    runtime: &OnionHttpsRuntime,
    request: &OnionHttpsRequest,
    circuit_id: OnionCircuitId,
    return_peer: Did,
    forward_nonce: OnionForwardNonce,
    forward_sequence: OnionForwardSequence,
) -> Result<OnionHttpsResponse> {
    if forward_sequence != OnionForwardSequence::FIRST {
        return Err(Error::OnionRouteError(OnionRouteError::ForwardReplay));
    }
    runtime.consume_forward_nonce(return_peer, circuit_id, forward_nonce)?;
    let target = OnionProxyTarget::parse_authority(&request.target)?;
    let authority = target.authority();
    let exit_target = OnionExitTarget::from_proxy_target(&target);
    let Some(policy) = runtime.exit_policy() else {
        return Err(Error::InvalidConfig(
            "browser HTTPS onion exit is not enabled locally".to_string(),
        ));
    };
    if !policy.allows_target(&exit_target) {
        return Err(Error::NoPermission);
    }
    let request_body_bytes = usize_to_u64(request.body.len())?;
    let _lease =
        runtime.admit_exit_request(&policy, circuit_id, return_peer, request_body_bytes)?;
    let body_limit = https_response_body_limit(runtime.remaining_exit_bytes(&policy)?);
    if body_limit == 0 {
        return Err(Error::NoPermission);
    }
    let url = format!("https://{}{}", authority, normalize_path(&request.path)?);
    let response =
        execute_https_request(&url, &target, request, body_limit, runtime, &policy).await?;
    Ok(OnionHttpsResponse {
        status: response.status,
        headers: response.headers,
        body: response.body,
    })
}

pub(super) struct FetchResponse {
    status: u16,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
}

fn normalize_method(method: &str) -> String {
    let method = method.trim();
    if method.is_empty() {
        default_method()
    } else {
        method.to_ascii_uppercase()
    }
}

fn normalize_path(path: &str) -> Result<String> {
    let path = path.trim();
    if path.is_empty() {
        return Ok(default_path());
    }
    if path.starts_with('/') {
        return Ok(path.to_string());
    }
    if path.starts_with('?') {
        return Ok(format!("/{path}"));
    }
    Err(Error::HttpRequestError(format!(
        "browser HTTPS onion proxy path must start with '/' or '?', got {path:?}"
    )))
}

fn default_method() -> String {
    "GET".to_string()
}

fn default_path() -> String {
    "/".to_string()
}

#[cfg(test)]
mod tests;

#[cfg(rings_browser)]
mod browser;
mod limits;
#[cfg(rings_native)]
mod native;
#[cfg(any(test, rings_browser))]
mod pending;