rings-node 1.0.0-pre.5

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
use std::time::Duration;

use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;

use super::super::*;
use crate::onion::exit_accounting::OnionExitAccounting;
use crate::onion::OnionLoopClass;
use crate::test_support::TestTask;

/// The request a normalized call becomes.
fn wire(call: OnionHttpsCall) -> OnionHttpsRequest {
    call.into_request()
}

#[test]
fn test_normalizes_empty_request_defaults() {
    let request = OnionHttpsClientRequest {
        method: String::new(),
        path: Some(String::new()),
        headers: Vec::new(),
        body: Vec::new(),
        class: None,
    };
    let call = OnionHttpsCall::with_default_path(request, default_path().as_str()).unwrap();
    assert_eq!(call.class(), OnionLoopClass::DEFAULT);

    assert_eq!(wire(call), OnionHttpsRequest {
        method: "GET".to_string(),
        path: "/".to_string(),
        headers: Vec::new(),
        body: Vec::new(),
    });
}

#[test]
fn test_call_preserves_and_overrides_loop_class_without_changing_wire_request() -> Result<()> {
    let request = OnionHttpsClientRequest {
        method: "POST".to_string(),
        body: b"payload".to_vec(),
        class: Some(OnionLoopClass::KiB64),
        ..OnionHttpsClientRequest::default()
    };
    let (_, call) = OnionHttpsCall::from_url("https://example.com/upload", request)?;
    assert_eq!(call.class(), OnionLoopClass::KiB64);

    let call = call.with_class(OnionLoopClass::KiB256);
    assert_eq!(call.class(), OnionLoopClass::KiB256);
    assert_eq!(wire(call), OnionHttpsRequest {
        method: "POST".to_string(),
        path: "/upload".to_string(),
        headers: Vec::new(),
        body: b"payload".to_vec(),
    });
    Ok(())
}

#[test]
fn test_client_request_deserializes_optional_loop_class_and_aliases() {
    let default_req: OnionHttpsClientRequest = serde_json::from_str("{}").expect("empty object");
    assert_eq!(default_req.class, None);

    for (raw, expected) in [
        ("KiB16", OnionLoopClass::KiB16),
        ("16KiB", OnionLoopClass::KiB16),
        ("16 KiB", OnionLoopClass::KiB16),
        ("KiB64", OnionLoopClass::KiB64),
        ("64KiB", OnionLoopClass::KiB64),
        ("64 KiB", OnionLoopClass::KiB64),
        ("KiB256", OnionLoopClass::KiB256),
        ("256KiB", OnionLoopClass::KiB256),
        ("MiB1", OnionLoopClass::MiB1),
        ("1MiB", OnionLoopClass::MiB1),
        ("MiB4", OnionLoopClass::MiB4),
        ("4MiB", OnionLoopClass::MiB4),
        ("MiB12", OnionLoopClass::MiB12),
        ("12MiB", OnionLoopClass::MiB12),
    ] {
        let json = format!(r#"{{"method":"GET","class":"{raw}"}}"#);
        let parsed: OnionHttpsClientRequest = serde_json::from_str(&json).expect("valid class");
        assert_eq!(parsed.class, Some(expected), "failed for {raw}");
    }
}

#[test]
fn test_call_from_url_uses_https_url_target_and_path() -> Result<()> {
    let (target, call) = OnionHttpsCall::from_url(
        "https://Example.COM/search?q=rust#ignored",
        Default::default(),
    )?;
    let request = wire(call);

    assert_eq!(target.authority(), "example.com:443");
    assert_eq!(request.method, "GET");
    assert_eq!(request.path, "/search?q=rust");
    Ok(())
}

#[test]
fn test_call_from_url_preserves_explicit_port_and_path_override() -> Result<()> {
    let request = OnionHttpsClientRequest {
        path: Some("?override=1".to_string()),
        ..OnionHttpsClientRequest::default()
    };
    let (target, call) = OnionHttpsCall::from_url("https://Example.COM:8443/original", request)?;

    assert_eq!(target.authority(), "example.com:8443");
    assert_eq!(wire(call).path, "/?override=1");
    Ok(())
}

#[test]
fn test_call_from_url_rejects_non_https_urls() {
    assert!(matches!(
        OnionHttpsCall::from_url("http://example.com/", Default::default()),
        Err(Error::HttpRequestError(_))
    ));
}

#[test]
fn test_rejects_relative_path_without_slash() {
    assert!(matches!(
        normalize_path("index.html"),
        Err(Error::HttpRequestError(_))
    ));
}

#[test]
fn test_default_body_limit_applies_when_policy_is_unlimited() {
    assert_eq!(
        https_response_body_limit(None),
        DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES
    );
    assert_eq!(https_response_body_limit(Some(7)), 7);
    assert_eq!(
        https_response_body_limit(Some(DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES + 1)),
        DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES
    );
}

#[test]
fn test_checked_status_code_rejects_invalid_js_status_values() {
    assert_eq!(checked_status_code(200.0).expect("status"), 200);
    assert!(matches!(
        checked_status_code(99.0),
        Err(Error::HttpRequestError(_))
    ));
    assert!(matches!(
        checked_status_code(200.5),
        Err(Error::HttpRequestError(_))
    ));
}

/// Read the whole world-to-client stream of a fetch in reads of at most `max` bytes.
async fn read_outcome(reader: &mut OnionHttpsReader, max: usize) -> Vec<u8> {
    let mut outcome = Vec::new();
    while let Some(bytes) = reader.read(max).await.expect("fetch read") {
        assert!(bytes.len() <= max);
        outcome.extend_from_slice(&bytes);
    }
    outcome
}

/// Law (fetch at fin): the world fetches only once its request stream ends, and a request that
/// does not decode yields an encoded exit failure, not a fetch.
#[tokio::test]
async fn test_fetch_world_answers_a_malformed_request_with_an_encoded_failure() {
    let world = OnionHttpsWorld::new(OnionExitPolicy::default(), OnionExitAccounting::default());
    let target = OnionProxyTarget::parse_authority("example.com:443").unwrap();
    let (mut reader, mut writer) = world.open(&target).await.unwrap();

    writer.write(Bytes::from_static(b"\xff")).await.unwrap();
    writer.shutdown().await.unwrap();

    assert!(matches!(
        decode_outcome(&read_outcome(&mut reader, 3).await).unwrap(),
        OnionHttpsOutcome::Error(OnionExitFailure::MalformedRequest)
    ));
}

/// Law (session end without fin): a fetch whose writer is dropped before `fin` has no request and
/// ends its stream empty.
#[tokio::test]
async fn test_fetch_world_without_fin_ends_empty() {
    let world = OnionHttpsWorld::new(OnionExitPolicy::default(), OnionExitAccounting::default());
    let target = OnionProxyTarget::parse_authority("example.com:443").unwrap();
    let (mut reader, writer) = world.open(&target).await.unwrap();

    drop(writer);

    assert_eq!(reader.read(16).await.unwrap(), None);
}

/// Law (request bound): the writer refuses a request past [`MAX_HTTPS_REQUEST_BYTES`].
#[tokio::test]
async fn test_fetch_world_bounds_the_request() {
    let world = OnionHttpsWorld::new(OnionExitPolicy::default(), OnionExitAccounting::default());
    let target = OnionProxyTarget::parse_authority("example.com:443").unwrap();
    let (_reader, mut writer) = world.open(&target).await.unwrap();

    writer
        .write(Bytes::from(vec![0; MAX_HTTPS_REQUEST_BYTES]))
        .await
        .unwrap();

    assert!(writer.write(Bytes::from_static(b"x")).await.is_err());
}

/// Law (codec): an outcome round-trips through its stream encoding.
#[test]
fn test_outcome_round_trips() {
    let outcome = OnionHttpsOutcome::Response(OnionHttpsResponse {
        status: 204,
        headers: vec![("a".to_string(), "b".to_string())],
        body: b"body".to_vec(),
    });

    assert_eq!(
        decode_outcome(&encode_outcome(&outcome).unwrap()).unwrap(),
        outcome
    );
}

#[tokio::test]
async fn test_native_fetch_times_out_stalled_response() {
    let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
    let address = listener.local_addr().unwrap();
    let server = TestTask::spawn(async move {
        let (_stream, _) = listener.accept().await.unwrap();
        std::future::pending::<()>().await;
    });
    let request = OnionHttpsRequest {
        method: "GET".to_string(),
        path: "/".to_string(),
        headers: Vec::new(),
        body: Vec::new(),
    };
    let egress = NativeHttpsEgress {
        host: address.ip().to_string(),
        addresses: vec![address],
    };

    let result = native_fetch_with_timeout(
        &format!("http://{address}/"),
        &request,
        DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES,
        Duration::from_millis(25),
        &egress,
        |_| Ok(()),
    )
    .await;

    server.abort();
    assert!(
        matches!(result, Err(Error::HttpRequestError(message)) if message.contains("timed out"))
    );
}

#[tokio::test]
async fn test_native_fetch_reads_a_chunked_body_whole() {
    let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
    let address = listener.local_addr().unwrap();
    let server = TestTask::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut request = [0_u8; 1024];
        let _ = stream.read(&mut request).await.unwrap();
        stream
            .write_all(
                b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n",
            )
            .await
            .unwrap();
    });
    let request = OnionHttpsRequest {
        method: "GET".to_string(),
        path: "/".to_string(),
        headers: Vec::new(),
        body: Vec::new(),
    };
    let egress = NativeHttpsEgress {
        host: address.ip().to_string(),
        addresses: vec![address],
    };

    let response = native_fetch_with_timeout(
        &format!("http://{address}/"),
        &request,
        DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES,
        Duration::from_secs(1),
        &egress,
        |_| Ok(()),
    )
    .await
    .unwrap();

    server.await.unwrap();
    assert_eq!(response.body, b"abcde");
}

#[test]
fn test_native_transport_headers_are_not_caller_controlled() {
    for name in [
        "Host",
        ":authority",
        "Connection",
        "Proxy-Connection",
        "Keep-Alive",
        "Proxy-Authenticate",
        "Proxy-Authorization",
        "TE",
        "Trailer",
        "Transfer-Encoding",
        "Content-Length",
        "Upgrade",
        "Expect",
    ] {
        assert!(is_native_transport_managed_header(name), "{name}");
    }
    for name in ["Accept", "Authorization", "Content-Type", "X-Application"] {
        assert!(!is_native_transport_managed_header(name), "{name}");
    }
}

#[tokio::test]
async fn test_native_fetch_uses_validated_url_authority_instead_of_caller_host() {
    let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
    let address = listener.local_addr().unwrap();
    let expected_host = format!("allowed.example:{}", address.port());
    let expected_host_for_server = expected_host.clone();
    let server = TestTask::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut request = Vec::new();
        let mut chunk = [0_u8; 1024];
        while !request.windows(4).any(|window| window == b"\r\n\r\n") {
            let length = stream.read(&mut chunk).await.unwrap();
            assert_ne!(length, 0, "request headers ended before their delimiter");
            request.extend_from_slice(&chunk[..length]);
        }
        let request = String::from_utf8_lossy(&request).to_ascii_lowercase();
        assert!(request.starts_with("post /probe http/1.1\r\n"));
        assert!(request.contains(&format!("\r\nhost: {expected_host_for_server}\r\n")));
        assert!(request.contains("\r\nx-application: preserved\r\n"));
        assert!(request.contains("\r\ncontent-length: 2\r\n"));
        assert!(!request.contains("blocked.example"));
        assert!(!request.contains("content-length: 999"));
        assert!(!request.contains("proxy-connection:"));
        stream
            .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
            .await
            .unwrap();
    });
    let request = OnionHttpsRequest {
        method: "POST".to_string(),
        path: "/probe".to_string(),
        headers: vec![
            ("Host".to_string(), "blocked.example".to_string()),
            (":authority".to_string(), "blocked.example".to_string()),
            ("Content-Length".to_string(), "999".to_string()),
            ("Proxy-Connection".to_string(), "keep-alive".to_string()),
            ("X-Application".to_string(), "preserved".to_string()),
        ],
        body: b"ok".to_vec(),
    };
    let egress = NativeHttpsEgress {
        host: "allowed.example".to_string(),
        addresses: vec![address],
    };

    let response = native_fetch_with_timeout(
        &format!("http://{expected_host}/probe"),
        &request,
        DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES,
        Duration::from_secs(1),
        &egress,
        |_| Ok(()),
    )
    .await
    .unwrap();

    server.await.unwrap();
    assert_eq!(response.status, 200);
    assert_eq!(response.body, b"ok");
}

/// Render bytes as lowercase hex.
fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

/// The `https` symbol's carry payloads are wire bytes (#834 L10): one request, one response and
/// every failure, each pinned byte for byte, so a reordered field or variant is a visible cutover.
#[test]
fn test_https_session_encodings_are_pinned() {
    let request = OnionHttpsRequest {
        method: "POST".to_string(),
        path: "/p?q".to_string(),
        headers: vec![("a".to_string(), "b".to_string())],
        body: b"xy".to_vec(),
    };
    let response = OnionHttpsOutcome::Response(OnionHttpsResponse {
        status: 201,
        headers: vec![("c".to_string(), "d".to_string())],
        body: b"z".to_vec(),
    });
    let pinned = [
        (
            hex(&encode_request(&request).expect("encode")),
            "04504f5354042f703f710101610162027879",
        ),
        (
            hex(&encode_outcome(&response).expect("encode")),
            "00c9010101630164017a",
        ),
        (
            hex(&encode_outcome(&OnionHttpsOutcome::Error(
                OnionExitFailure::PermissionDenied,
            ))
            .expect("encode")),
            "0100",
        ),
        (
            hex(&encode_outcome(&OnionHttpsOutcome::Error(
                OnionExitFailure::MalformedRequest,
            ))
            .expect("encode")),
            "0101",
        ),
        (
            hex(
                &encode_outcome(&OnionHttpsOutcome::Error(OnionExitFailure::Internal))
                    .expect("encode"),
            ),
            "0102",
        ),
    ];

    for (encoded, golden) in pinned {
        assert_eq!(encoded, golden);
    }
    assert_eq!(
        decode_outcome(&encode_outcome(&response).expect("encode")).expect("decode"),
        response
    );
}

/// One budget across concurrent fetches: each fetch records its header names and
/// values and its body chunks as they stream against the shared accounting, so two fetches whose
/// bodies together exceed the window's budget cannot both complete, and no more than the budget
/// is ever recorded.
///
/// Only what the budget guarantees is asserted: how the two streams interleave is
/// socket timing, and an interleaving in which each has recorded part of its body before the
/// other's next chunk is refused fails both, a correct outcome of recording as bytes stream.
#[tokio::test]
async fn test_concurrent_fetches_share_one_byte_budget() {
    let listener = TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
    let address = listener.local_addr().unwrap();
    let body = vec![b'b'; 3_000];
    let server = TestTask::spawn(async move {
        let mut served = Vec::new();
        for _ in 0..2 {
            let (mut stream, _) = listener.accept().await.unwrap();
            let body = body.clone();
            served.push(TestTask::spawn(async move {
                let mut request = [0_u8; 1024];
                let _ = stream.read(&mut request).await;
                let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len());
                let _ = stream.write_all(head.as_bytes()).await;
                let _ = stream.write_all(&body).await;
            }));
        }
        for serving in served {
            let _ = serving.await;
        }
    });
    let policy = OnionExitPolicy {
        max_bytes_per_minute: 4_000,
        ..OnionExitPolicy::default()
    };
    let accounting = OnionExitAccounting::default();
    let fetch = || {
        let request = OnionHttpsRequest {
            method: "GET".to_string(),
            path: "/".to_string(),
            headers: Vec::new(),
            body: Vec::new(),
        };
        let egress = NativeHttpsEgress {
            host: address.ip().to_string(),
            addresses: vec![address],
        };
        let accounting = accounting.clone();
        let policy = policy.clone();
        async move {
            native_fetch_with_timeout(
                &format!("http://{address}/"),
                &request,
                DEFAULT_HTTPS_RESPONSE_BODY_LIMIT_BYTES,
                Duration::from_secs(5),
                &egress,
                |bytes| accounting.record_bytes(&policy, bytes, 0),
            )
            .await
        }
    };

    let (first, second) = tokio::join!(fetch(), fetch());
    server.await.unwrap();

    assert!(
        first.is_err() || second.is_err(),
        "both fetches fit a budget below their sum"
    );
    let recorded = accounting.recorded_bytes_for_test(0).unwrap();
    assert!(
        recorded > 0 && recorded <= 4_000,
        "the one budget holds across both fetches: {recorded} bytes recorded"
    );
}

#[derive(Clone, Default)]
struct MockCancelState {
    aborted: std::sync::Arc<std::sync::atomic::AtomicBool>,
    body_cancelled: std::sync::Arc<std::sync::atomic::AtomicBool>,
    reader_cancelled: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

impl FetchCancelTarget for MockCancelState {
    type Body = ();
    type Reader = ();

    fn cancel_body(&mut self, (): &Self::Body) -> bool {
        self.body_cancelled
            .store(true, std::sync::atomic::Ordering::SeqCst);
        true
    }

    fn cancel_reader(&mut self, (): &Self::Reader) -> bool {
        self.reader_cancelled
            .store(true, std::sync::atomic::Ordering::SeqCst);
        true
    }

    fn abort(&mut self) {
        self.aborted
            .store(true, std::sync::atomic::Ordering::SeqCst);
    }
}

struct MockHttpsResponse {
    status: f64,
    headers: Vec<(String, String)>,
    has_body: bool,
}

struct MockHttpsFetch {
    response: Option<MockHttpsResponse>,
    chunks: std::sync::Mutex<std::collections::VecDeque<Option<Vec<u8>>>>,
    stall_after_chunks: bool,
}

impl CancellableHttpsFetch for MockHttpsFetch {
    type Response = MockHttpsResponse;
    type Body = ();
    type Reader = ();
    type Cancel = MockCancelState;

    async fn await_response(&mut self) -> Result<Self::Response> {
        match self.response.take() {
            Some(response) => Ok(response),
            None => std::future::pending().await,
        }
    }

    fn response_status(&self, response: &Self::Response) -> Result<f64> {
        Ok(response.status)
    }

    fn response_body(&self, response: &Self::Response) -> Result<Option<Self::Body>> {
        Ok(response.has_body.then_some(()))
    }

    fn response_headers(&self, response: &Self::Response) -> Result<Vec<(String, String)>> {
        Ok(response.headers.clone())
    }

    fn body_reader(&self, (): &Self::Body) -> Result<Self::Reader> {
        Ok(())
    }

    async fn read_chunk(&self, (): &Self::Reader) -> Result<Option<Vec<u8>>> {
        let next = self.chunks.lock().expect("chunks lock").pop_front();
        match next {
            Some(chunk) => Ok(chunk),
            None if self.stall_after_chunks => std::future::pending().await,
            None => Ok(None),
        }
    }
}

/// Regression (#1216): dropping the outer fetch future (e.g. on exit session teardown) or
/// hitting the request timeout aborts the `AbortController` and cancels any active stream reader.
#[tokio::test]
async fn test_cancellable_https_fetch_aborts_on_outer_drop_and_timeout() {
    use std::sync::atomic::Ordering;

    // 1. Outer future dropped while waiting for initial response headers.
    let state = MockCancelState::default();
    {
        let fut = drive_cancellable_https_fetch(
            MockHttpsFetch {
                response: None,
                chunks: std::sync::Mutex::new(std::collections::VecDeque::new()),
                stall_after_chunks: true,
            },
            state.clone(),
            1024,
            Duration::from_secs(30),
            |_| Ok(()),
        );
        futures::pin_mut!(fut);
        assert!(futures::poll!(fut.as_mut()).is_pending());
    }
    assert!(state.aborted.load(Ordering::SeqCst));
    assert!(!state.body_cancelled.load(Ordering::SeqCst));
    assert!(!state.reader_cancelled.load(Ordering::SeqCst));

    // 2. Outer future dropped mid-body after acquiring the stream reader.
    let state = MockCancelState::default();
    {
        let fut = drive_cancellable_https_fetch(
            MockHttpsFetch {
                response: Some(MockHttpsResponse {
                    status: 200.0,
                    headers: Vec::new(),
                    has_body: true,
                }),
                chunks: std::sync::Mutex::new(std::collections::VecDeque::from([Some(
                    b"part".to_vec(),
                )])),
                stall_after_chunks: true,
            },
            state.clone(),
            1024,
            Duration::from_secs(30),
            |_| Ok(()),
        );
        futures::pin_mut!(fut);
        assert!(futures::poll!(fut.as_mut()).is_pending());
    }
    assert!(state.aborted.load(Ordering::SeqCst));
    assert!(state.reader_cancelled.load(Ordering::SeqCst));
    assert!(!state.body_cancelled.load(Ordering::SeqCst));

    // 3. Request timeout fires while response is stalled.
    let state = MockCancelState::default();
    let result = drive_cancellable_https_fetch(
        MockHttpsFetch {
            response: None,
            chunks: std::sync::Mutex::new(std::collections::VecDeque::new()),
            stall_after_chunks: true,
        },
        state.clone(),
        1024,
        Duration::from_millis(15),
        |_| Ok(()),
    )
    .await;
    assert!(matches!(result, Err(Error::HttpRequestError(msg)) if msg.contains("timed out")));
    assert!(state.aborted.load(Ordering::SeqCst));
}

/// Regression (#1216): rejecting response status, `content-length > max_body_bytes`, or header
/// byte budget cancels the unconsumed response `body` stream and aborts the `AbortController`.
#[tokio::test]
async fn test_cancellable_https_fetch_cancels_body_and_aborts_on_header_or_length_rejection() {
    use std::sync::atomic::Ordering;

    // 1. Oversized Content-Length rejected before body reader is acquired.
    let state = MockCancelState::default();
    let result = drive_cancellable_https_fetch(
        MockHttpsFetch {
            response: Some(MockHttpsResponse {
                status: 200.0,
                headers: vec![("Content-Length".to_string(), "100".to_string())],
                has_body: true,
            }),
            chunks: std::sync::Mutex::new(std::collections::VecDeque::new()),
            stall_after_chunks: false,
        },
        state.clone(),
        10,
        Duration::from_secs(5),
        |_| Ok(()),
    )
    .await;
    assert!(matches!(result, Err(Error::NoPermission)));
    assert!(state.body_cancelled.load(Ordering::SeqCst));
    assert!(!state.reader_cancelled.load(Ordering::SeqCst));
    assert!(state.aborted.load(Ordering::SeqCst));

    // 2. Header byte budget rejected by accounting.
    let state = MockCancelState::default();
    let result = drive_cancellable_https_fetch(
        MockHttpsFetch {
            response: Some(MockHttpsResponse {
                status: 200.0,
                headers: vec![("X-Large".to_string(), "oversized-header".to_string())],
                has_body: true,
            }),
            chunks: std::sync::Mutex::new(std::collections::VecDeque::new()),
            stall_after_chunks: false,
        },
        state.clone(),
        1024,
        Duration::from_secs(5),
        |_| Err(Error::NoPermission),
    )
    .await;
    assert!(matches!(result, Err(Error::NoPermission)));
    assert!(state.body_cancelled.load(Ordering::SeqCst));
    assert!(state.aborted.load(Ordering::SeqCst));

    // 3. Invalid HTTP status code rejected after response resolves.
    let state = MockCancelState::default();
    let result = drive_cancellable_https_fetch(
        MockHttpsFetch {
            response: Some(MockHttpsResponse {
                status: 99.0,
                headers: Vec::new(),
                has_body: true,
            }),
            chunks: std::sync::Mutex::new(std::collections::VecDeque::new()),
            stall_after_chunks: false,
        },
        state.clone(),
        1024,
        Duration::from_secs(5),
        |_| Ok(()),
    )
    .await;
    assert!(matches!(result, Err(Error::HttpRequestError(_))));
    assert!(state.body_cancelled.load(Ordering::SeqCst));
    assert!(state.aborted.load(Ordering::SeqCst));
}

/// Regression (#1216): body chunk budget overflow cancels the active stream reader and aborts the
/// controller, whereas a complete response within budget disarms the guard without aborting.
#[tokio::test]
async fn test_cancellable_https_fetch_cancels_reader_on_chunk_overflow_and_disarms_on_success() {
    use std::sync::atomic::Ordering;

    // 1. Body chunk exceeds max_body_bytes mid-stream.
    let state = MockCancelState::default();
    let result = drive_cancellable_https_fetch(
        MockHttpsFetch {
            response: Some(MockHttpsResponse {
                status: 200.0,
                headers: Vec::new(),
                has_body: true,
            }),
            chunks: std::sync::Mutex::new(std::collections::VecDeque::from([
                Some(b"1234".to_vec()),
                Some(b"5678".to_vec()),
            ])),
            stall_after_chunks: false,
        },
        state.clone(),
        6,
        Duration::from_secs(5),
        |_| Ok(()),
    )
    .await;
    assert!(matches!(result, Err(Error::NoPermission)));
    assert!(state.reader_cancelled.load(Ordering::SeqCst));
    assert!(!state.body_cancelled.load(Ordering::SeqCst));
    assert!(state.aborted.load(Ordering::SeqCst));

    // 2. Successful completion disarms `FetchCancellationGuard` so neither cancel nor abort fires.
    let state = MockCancelState::default();
    let guard_check = FetchCancellationGuard::new(state.clone());
    drop(guard_check);
    assert!(state.aborted.load(Ordering::SeqCst));

    let clean_state = MockCancelState::default();
    let response = drive_cancellable_https_fetch(
        MockHttpsFetch {
            response: Some(MockHttpsResponse {
                status: 200.0,
                headers: vec![("content-type".to_string(), "text/plain".to_string())],
                has_body: true,
            }),
            chunks: std::sync::Mutex::new(std::collections::VecDeque::from([
                Some(b"hello ".to_vec()),
                Some(b"world".to_vec()),
                None,
            ])),
            stall_after_chunks: false,
        },
        clean_state.clone(),
        64,
        Duration::from_secs(5),
        |_| Ok(()),
    )
    .await
    .expect("clean fetch succeeds");
    assert_eq!(response.status, 200);
    assert_eq!(response.body, b"hello world");
    assert!(!clean_state.aborted.load(Ordering::SeqCst));
    assert!(!clean_state.body_cancelled.load(Ordering::SeqCst));
    assert!(!clean_state.reader_cancelled.load(Ordering::SeqCst));
}