rings-node 1.0.0-pre.8

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.
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
use std::collections::BTreeSet;

use super::common::*;
use super::*;
use crate::descriptor::RegistryElement;
use crate::onion::OnionProcessEpoch;
use crate::onion::OnionProcessEpochCell;
use crate::onion::OnionServiceName;
use crate::tests::exit_descriptor::ExitDescriptorFixture;

#[tokio::test]
async fn test_onion_exit_lookup_uses_dedicated_exit_registry() -> Result<()> {
    let processor = prepare_processor().await;
    let relay_only = prepare_processor().await;
    let exit = prepare_processor().await;
    let relay_descriptor = relay_only.online_node_descriptor_at(get_epoch_ms())?;
    let exit_descriptor = onion_exit_descriptor_for_processor(&exit, "tcp", get_epoch_ms())?;

    processor
        .storage_store(Processor::registry_entry(ONLINE_NODES_TOPIC, vec![
            relay_descriptor,
        ])?)
        .await?;
    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            exit_descriptor.clone(),
        ])?)
        .await?;

    let exits = processor.lookup_onion_exits("tcp", false).await?;

    assert_eq!(
        exits
            .iter()
            .map(|descriptor| descriptor.to_element().ok())
            .collect::<Vec<_>>(),
        vec![exit_descriptor.to_element().ok()]
    );
    assert!(exits
        .iter()
        .all(|descriptor| descriptor.verify_signature(processor.swarm.network_id())));
    assert!(!exits
        .iter()
        .any(|descriptor| descriptor.did == relay_only.did()));
    Ok(())
}

#[tokio::test]
async fn test_onion_exit_lookup_preserves_distinct_services_for_same_did() -> Result<()> {
    let processor = prepare_processor().await;
    let exit = prepare_processor().await;
    let now_ms = get_epoch_ms();
    let older_tcp = onion_exit_descriptor_for_processor(&exit, "tcp", now_ms)?;
    let newer_https = onion_exit_descriptor_for_processor(&exit, "https", now_ms + 1)?;

    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            older_tcp,
            newer_https,
        ])?)
        .await?;

    assert_eq!(processor.lookup_onion_exits("tcp", false).await?.len(), 1);
    assert_eq!(processor.lookup_onion_exits("https", false).await?.len(), 1);
    assert_eq!(processor.lookup_onion_exits("", false).await?.len(), 2);
    Ok(())
}

/// Proxy routing closes a loop over presence relays: relay positions need no exit descriptor,
/// and the exit, registered as a relay at the same epoch, takes the symbol position.
#[tokio::test]
async fn test_onion_proxy_route_uses_presence_relays_without_exit_descriptor() -> Result<()> {
    let processor = prepare_processor().await;
    let exit = prepare_processor().await;
    let exit_descriptor = onion_exit_descriptor_for_processor(&exit, "tcp", get_epoch_ms())?;
    let relays = store_onion_relays(&processor, &[&exit], 3).await?;
    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            exit_descriptor.clone(),
        ])?)
        .await?;

    let route = directory::build_onion_proxy_route_with_first_hop(
        &processor,
        OnionProxyProtocol::TcpConnect,
        OnionProxyTarget::parse_authority("example.com:443")?,
        |_| true,
    )
    .await?
    .route;
    let dids = route
        .hops()
        .positions()
        .map(|hop| hop.did)
        .collect::<Vec<_>>();
    let relay_dids = relays.iter().map(Processor::did).collect::<BTreeSet<_>>();

    assert_eq!(dids.len(), 5);
    assert_eq!(dids.first(), dids.last());
    assert_eq!(dids.get(2), Some(&exit.did()));
    assert!(dids
        .iter()
        .enumerate()
        .all(|(index, did)| index == 2 || relay_dids.contains(did)));
    assert_eq!(
        route.exit().to_element().ok(),
        exit_descriptor.to_element().ok()
    );
    Ok(())
}

/// A symbol descriptor from an earlier process of its node is stale and never selected.
#[tokio::test]
async fn test_onion_proxy_route_rejects_exit_with_stale_process_epoch() -> Result<()> {
    let processor = prepare_processor().await;
    let exit = prepare_processor().await;
    let mut restarted = exit.clone();
    restarted.onion_process_epoch = OnionProcessEpochCell::new(OnionProcessEpoch::new([0x5a; 16]));
    let stale_descriptor = onion_exit_descriptor_for_processor(&exit, "tcp", get_epoch_ms())?;
    store_onion_relays(&processor, &[&restarted], 3).await?;
    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            stale_descriptor,
        ])?)
        .await?;

    let error = processor
        .build_onion_proxy_route(
            OnionProxyProtocol::TcpConnect,
            OnionProxyTarget::parse_authority("example.com:443")?,
        )
        .await
        .err()
        .ok_or_else(|| Error::InvalidConfig("expected route failure".to_string()))?;

    assert!(matches!(
        error,
        Error::OnionRouteError(OnionRouteError::ExitRelayRegistrationMismatch { service })
            if service == "tcp"
    ));
    Ok(())
}

#[tokio::test]
async fn test_onion_proxy_route_uses_protocol_service_class() -> Result<()> {
    let processor = prepare_processor().await;
    let tcp_exit = prepare_processor().await;
    let https_exit = prepare_processor().await;
    let now_ms = get_epoch_ms();
    let tcp_exit_descriptor = onion_exit_descriptor_for_processor(&tcp_exit, "tcp", now_ms)?;
    let https_exit_descriptor = onion_exit_descriptor_for_processor(&https_exit, "https", now_ms)?;

    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            tcp_exit_descriptor,
            https_exit_descriptor,
        ])?)
        .await?;
    store_onion_relays(&processor, &[&tcp_exit, &https_exit], 2).await?;

    let target = OnionProxyTarget::parse_authority("example.com:443")?;
    let tcp_route = directory::build_onion_proxy_route_with_first_hop(
        &processor,
        OnionProxyProtocol::TcpConnect,
        target.clone(),
        |_| true,
    )
    .await?;
    let https_route = directory::build_onion_proxy_route_with_first_hop(
        &processor,
        OnionProxyProtocol::HttpsProxy,
        target,
        |_| true,
    )
    .await?;

    assert_eq!(tcp_route.exit_service(), "tcp");
    assert_eq!(tcp_route.exit_did(), tcp_exit.did());
    assert_eq!(https_route.exit_service(), "https");
    assert_eq!(https_route.exit_did(), https_exit.did());
    Ok(())
}

#[tokio::test]
async fn test_tcp_connect_route_rejects_browser_tcp_exit_descriptor() -> Result<()> {
    let processor = prepare_processor().await;
    let browser_exit = prepare_processor().await;
    // A browser has no sockets, so a `tcp` registration from one cannot carry a tunnel.
    let descriptor = ExitDescriptorFixture {
        node_type: OnlineNodeType::Browser,
        ..ExitDescriptorFixture::live(
            &browser_exit,
            OnionServiceName::tcp(),
            bounded_policy(&["example.com:443"], &[])?,
            get_epoch_ms(),
        )
    }
    .sign()?;

    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            descriptor,
        ])?)
        .await?;

    let target = OnionProxyTarget::parse_authority("example.com:443")?;
    let error = processor
        .build_onion_proxy_route(OnionProxyProtocol::TcpConnect, target)
        .await
        .err()
        .ok_or_else(|| Error::InvalidConfig("expected route failure".to_string()))?;

    assert!(matches!(
        error,
        Error::OnionRouteError(OnionRouteError::NoExitForProxyProtocol { service, protocol })
            if service == "tcp" && protocol == "tcp-connect"
    ));
    Ok(())
}

#[tokio::test]
async fn test_onion_proxy_route_filters_exits_by_target_policy() -> Result<()> {
    let processor = prepare_processor().await;
    let allowed_exit = prepare_processor().await;
    let denied_exit = prepare_processor().await;
    let now_ms = get_epoch_ms();
    let allowed_descriptor = ExitDescriptorFixture::live(
        &allowed_exit,
        OnionServiceName::https(),
        bounded_policy(&["example.com:443"], &[])?,
        now_ms,
    )
    .sign()?;
    let denied_descriptor = ExitDescriptorFixture::live(
        &denied_exit,
        OnionServiceName::https(),
        bounded_policy(&["example.com:443"], &["example.com:443"])?,
        now_ms,
    )
    .sign()?;

    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            denied_descriptor,
            allowed_descriptor,
        ])?)
        .await?;
    store_onion_relays(&processor, &[&allowed_exit, &denied_exit], 2).await?;

    let target = OnionProxyTarget::parse_authority("example.com:443")?;
    let route = directory::build_onion_proxy_route_with_first_hop(
        &processor,
        OnionProxyProtocol::HttpsProxy,
        target,
        |_| true,
    )
    .await?;

    assert_eq!(route.exit_did(), allowed_exit.did());
    Ok(())
}

#[tokio::test]
async fn test_onion_proxy_route_reports_policy_denied_target() -> Result<()> {
    let processor = prepare_processor().await;
    let denied_exit = prepare_processor().await;
    let now_ms = get_epoch_ms();
    let denied_descriptor = ExitDescriptorFixture::live(
        &denied_exit,
        OnionServiceName::https(),
        bounded_policy(&["other.example.com:443"], &[])?,
        now_ms,
    )
    .sign()?;

    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            denied_descriptor,
        ])?)
        .await?;

    let target = OnionProxyTarget::parse_authority("example.com:443")?;
    let error = processor
        .build_onion_proxy_route(OnionProxyProtocol::HttpsProxy, target)
        .await
        .err()
        .ok_or_else(|| Error::InvalidConfig("expected route failure".to_string()))?;

    assert!(matches!(
        error,
        Error::OnionRouteError(OnionRouteError::NoExitAllowsTarget { service, target })
            if service == "https" && target == "example.com:443"
    ));
    Ok(())
}

#[tokio::test]
async fn test_https_proxy_route_skips_browser_exit_for_domain_target_and_allows_public_ip_literal(
) -> Result<()> {
    let processor = prepare_processor().await;
    let browser_exit = prepare_processor().await;
    let now_ms = get_epoch_ms();
    let descriptor = ExitDescriptorFixture {
        node_type: OnlineNodeType::Browser,
        ..ExitDescriptorFixture::live(
            &browser_exit,
            OnionServiceName::https(),
            bounded_policy(&["*:*"], &[])?,
            now_ms,
        )
    }
    .sign()?;

    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            descriptor,
        ])?)
        .await?;
    store_onion_relays(&processor, &[&browser_exit], 3).await?;

    let domain_target = OnionProxyTarget::parse_authority("example.com:443")?;
    let domain_error = directory::build_onion_proxy_route_with_first_hop(
        &processor,
        OnionProxyProtocol::HttpsProxy,
        domain_target,
        |_| true,
    )
    .await
    .err()
    .ok_or_else(|| Error::InvalidConfig("expected domain target rejection".to_string()))?;
    assert!(matches!(
        domain_error,
        Error::OnionRouteError(OnionRouteError::NoExitAllowsTarget { service, target })
            if service == "https" && target == "example.com:443"
    ));

    let public_ip_target = OnionProxyTarget::parse_authority("1.1.1.1:443")?;
    let ip_route = directory::build_onion_proxy_route_with_first_hop(
        &processor,
        OnionProxyProtocol::HttpsProxy,
        public_ip_target,
        |_| true,
    )
    .await?;
    assert_eq!(ip_route.exit_did(), browser_exit.did());
    assert!(bounded_policy(&["example.com:443"], &[])?
        .validate_browser_targets()
        .is_err());
    assert!(bounded_policy(&["1.1.1.1:443"], &[])?
        .validate_browser_targets()
        .is_ok());
    Ok(())
}

/// Regression (#1224): native `Processor::build_onion_proxy_route` requires a directly connected
/// peer for the first-hop guard instead of permitting arbitrary directory relays with no active
/// transport link.
#[tokio::test]
async fn test_onion_proxy_route_requires_direct_peer_for_first_hop() -> Result<()> {
    let processor = prepare_processor().await;
    let exit = prepare_processor().await;
    let exit_descriptor = onion_exit_descriptor_for_processor(&exit, "tcp", get_epoch_ms())?;
    store_onion_relays(&processor, &[&exit], 3).await?;
    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            exit_descriptor,
        ])?)
        .await?;

    let error = processor
        .build_onion_proxy_route(
            OnionProxyProtocol::TcpConnect,
            OnionProxyTarget::parse_authority("example.com:443")?,
        )
        .await
        .err()
        .ok_or_else(|| Error::InvalidConfig("expected NoPermittedFirstHop".to_string()))?;

    assert!(matches!(
        error,
        Error::OnionRouteError(OnionRouteError::NoPermittedFirstHop)
    ));
    Ok(())
}

/// Regression (#1224): when only one directory relay has an active transport link to `processor`,
/// `Processor::build_onion_proxy_route` selects that connected peer as the first-hop entry guard.
#[cfg(feature = "dummy")]
#[tokio::test]
async fn test_onion_proxy_route_selects_only_directly_connected_first_hop_guard() -> Result<()> {
    let _net = network_test_guard().await;
    let processor = prepare_processor().await;
    let exit = prepare_processor().await;
    let exit_descriptor = onion_exit_descriptor_for_processor(&exit, "tcp", get_epoch_ms())?;
    let relays = store_onion_relays(&processor, &[&exit], 3).await?;
    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            exit_descriptor,
        ])?)
        .await?;

    let _client_rec = ApplicationRecorder::attach(&processor);
    let _guard_rec = ApplicationRecorder::attach(&relays[1]);
    connect_processors(&processor, &relays[1]).await;

    let route = processor
        .build_onion_proxy_route(
            OnionProxyProtocol::TcpConnect,
            OnionProxyTarget::parse_authority("example.com:443")?,
        )
        .await?
        .route;

    assert_eq!(route.hops().guard().did, relays[1].did());
    Ok(())
}

#[tokio::test]
async fn test_onion_udp_proxy_route_admits_restricted_port_allowlist_for_bind_mode() -> Result<()> {
    let processor = prepare_processor().await;
    let dns_exit = prepare_processor().await;
    let v6_only_exit = prepare_processor().await;
    let shadowed_exit = prepare_processor().await;
    let now_ms = get_epoch_ms();

    let dns_descriptor = ExitDescriptorFixture::live(
        &dns_exit,
        OnionServiceName::udp(),
        bounded_policy(&["*:53"], &[])?,
        now_ms,
    )
    .sign()?;
    let v6_only_descriptor = ExitDescriptorFixture::live(
        &v6_only_exit,
        OnionServiceName::udp(),
        bounded_policy(&["[2606:4700:4700::1111]:53"], &[])?,
        now_ms,
    )
    .sign()?;
    let shadowed_descriptor = ExitDescriptorFixture::live(
        &shadowed_exit,
        OnionServiceName::udp(),
        bounded_policy(&["*:53"], &["*:53"])?,
        now_ms,
    )
    .sign()?;

    processor
        .storage_store(Processor::registry_entry(ONION_EXITS_TOPIC, vec![
            v6_only_descriptor,
            shadowed_descriptor,
            dns_descriptor,
        ])?)
        .await?;
    store_onion_relays(&processor, &[&dns_exit, &v6_only_exit, &shadowed_exit], 2).await?;

    let v4_route = directory::build_onion_proxy_route_with_first_hop(
        &processor,
        OnionProxyProtocol::UdpDatagram,
        crate::onion::OnionUdpBindMode::Ipv4AnyPort.to_target(),
        |_| true,
    )
    .await?;
    assert_eq!(v4_route.exit_did(), dns_exit.did());

    // Non-bind target authorities must still be rejected for `UdpDatagram`.
    let non_bind = OnionProxyTarget::parse_authority("8.8.8.8:53")?;
    let err = directory::build_onion_proxy_route_with_first_hop(
        &processor,
        OnionProxyProtocol::UdpDatagram,
        non_bind,
        |_| true,
    )
    .await
    .err()
    .ok_or_else(|| Error::InvalidConfig("expected non-bind target rejection".to_string()))?;
    assert!(matches!(
        err,
        Error::OnionRouteError(OnionRouteError::NoExitAllowsTarget { service, .. })
            if service == "udp"
    ));

    Ok(())
}