rings-node 0.39.0

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
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"
    );
}