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
//! Mail through a gateway over the dummy transport (#1117): a recipient publishes its mail
//! descriptor, a gateway finds it and writes a sealed mail to the recipient's topic, and the
//! recipient fetches and opens it, every wait woken by the overlay's activity.
//!
//! ```text
//!   recipient R ─register μ(R)─▶ DHT ◀─recipient(R)─ gateway G
//!   gateway G   ─Extend(mail_topic(R), seal(m), MAX_TTL_MS)─▶ DHT ◀─poll─ recipient R
//! ```

use std::sync::Arc;

use bytes::Bytes;
use rand::rngs::OsRng;
use rings_core::consts::MAX_TTL_MS;
use rings_core::dht::entry::Entry;
use rings_core::dht::entry::EntryKind;
use rings_core::ecc::SecretKey;
use rings_core::storage::MemStorage;
use rings_core::utils::get_epoch_ms;

use super::common::connect_processors;
use super::common::network_test_guard;
use super::common::owns_entry_placement;
use super::common::prepare_processor_with_identity_key_network_and_virtual_nodes;
use super::common::wait_for_mutual_dht_topology;
use super::common::NetworkTestGuard;
use super::common::PROCESSOR_TEST_HANG_GUARD;
use crate::consts::DATA_REDUNDANT;
use crate::error::Error;
use crate::error::Result;
use crate::mail::descriptor::descriptor_topic;
use crate::mail::descriptor::MailRecipient;
use crate::mail::envelope::seal;
use crate::mail::envelope::MailElement;
use crate::mail::envelope::SealedMail;
use crate::mail::gateway::MailDrop;
use crate::mail::gateway::MailGateway;
use crate::mail::mail_topic;
use crate::mail::open::open_mail;
use crate::mail::open::Opening;
use crate::mail::recipient::KvInbox;
use crate::mail::recipient::PollReport;
use crate::mail::recipient::Recipient;
use crate::mail::recipient::RecipientRecord;
use crate::mail::recipient::StoredMail;
use crate::mail::recipient::DEFAULT_MAIL_POLL_INTERVAL;
use crate::mail::registration::MailOffer;
use crate::mail::registration::MailRegistration;
use crate::prelude::ChordStorageInterface;
use crate::processor::Processor;
use crate::registration::RegistrationContext;
use crate::registration::RegistrationTask;
use crate::tests::activity::probe_on_activity;

/// A message with a `Message-ID`.
const MESSAGE: &[u8] = b"Message-ID: <overlay@example.org>\r\n\r\nAcross the Great Wall.\r\n";

/// The recipient of these tests: its inbox and records in memory.
type MemRecipient = Recipient<KvInbox<MemStorage<StoredMail>>, MemStorage<RecipientRecord>>;

/// A gateway node and a recipient node, connected, each in the other's DHT view. Without
/// storage virtual nodes, each placement is owned by its successor, which
/// [`await_owners_holding`] reads.
async fn connected_pair() -> Result<(NetworkTestGuard, Arc<Processor>, Arc<Processor>)> {
    let network = network_test_guard().await;
    let node =
        || prepare_processor_with_identity_key_network_and_virtual_nodes(SecretKey::random(), 0, 0);
    let gateway = Arc::new(node().await);
    let recipient = Arc::new(node().await);
    connect_processors(&gateway, &recipient).await;
    wait_for_mutual_dht_topology(&gateway, &recipient).await?;
    Ok((network, gateway, recipient))
}

/// Await, on activity, the owner of every placement of `topic` among `nodes` holding a carrier
/// that satisfies `holds`, so that a read of `topic` by either node sees it.
///
/// It reads only the owners' storage, never the DHT: a probe that fetched would wake itself on
/// its own lookup and, answered locally, never yield to the deliveries it waits for.
async fn await_owners_holding(
    nodes: [&Processor; 2],
    topic: &str,
    holds: impl Fn(&Entry) -> bool,
) -> Result<()> {
    let placements = Entry::gen_did(topic)?.rotate_affine(DATA_REDUNDANT)?;
    let holds = &holds;
    probe_on_activity(
        "every owner of the topic holds the writes",
        PROCESSOR_TEST_HANG_GUARD,
        || {
            let placements = &placements;
            async move {
                for placement in placements {
                    let mut owners = nodes
                        .iter()
                        .filter(|node| owns_entry_placement(node, *placement).unwrap_or(false));
                    let Some(owner) = owners.next() else {
                        return Ok(None);
                    };
                    let stored = owner
                        .swarm
                        .dht()
                        .stored_entry_at(EntryKind::Data, *placement, get_epoch_ms())
                        .await
                        .map_err(Error::Storage)?;
                    if !stored.is_some_and(|entry| holds(&entry)) {
                        return Ok(None);
                    }
                }
                Ok(Some(()))
            }
        },
    )
    .await
}

/// Whether a carrier holds every one of `elements`.
fn holds_all(elements: &[Bytes]) -> impl Fn(&Entry) -> bool + '_ {
    |entry| elements.iter().all(|element| entry.data.contains(element))
}

/// Publish `recipient`'s mail descriptor once, await its owners holding it, and return what the
/// gateway then finds.
async fn opt_in(
    gateway: &MailGateway,
    nodes: [&Processor; 2],
    recipient: &Processor,
) -> Result<MailRecipient> {
    MailRegistration::new(recipient.did(), MailOffer::default())
        .register_once(&RegistrationContext::new(recipient))
        .await?;
    await_owners_holding(nodes, &descriptor_topic(recipient.did()), |entry| {
        !entry.data.is_empty()
    })
    .await?;
    Ok(gateway
        .recipient(recipient.did())
        .await
        .unwrap()
        .expect("the gateway finds the descriptor its owners hold"))
}

/// The recipient of `processor`, its inbox and records empty.
fn mem_recipient(processor: &Arc<Processor>) -> MemRecipient {
    Recipient::start(
        Arc::clone(processor),
        KvInbox::new(MemStorage::new()),
        MemStorage::new(),
        DEFAULT_MAIL_POLL_INTERVAL,
    )
    .unwrap()
}

/// [`MESSAGE`] sealed for `target`.
fn sealed_for(target: &MailRecipient) -> SealedMail {
    seal(MESSAGE, target, &mut OsRng).unwrap()
}

/// The messages `recipient`'s inbox holds.
async fn inbox_messages(recipient: &MemRecipient) -> Vec<Vec<u8>> {
    use rings_core::storage::KvStorageInterface;
    recipient
        .inbox()
        .store()
        .get_all()
        .await
        .unwrap()
        .into_iter()
        .map(|(_, stored)| stored.message)
        .collect()
}

#[tokio::test]
async fn test_a_mail_through_the_gateway_is_opened_by_its_recipient_within_its_lifetime(
) -> Result<()> {
    let (_network, gateway_node, recipient_node) = connected_pair().await?;
    let nodes = [gateway_node.as_ref(), recipient_node.as_ref()];
    let gateway = MailGateway::new(Arc::clone(&gateway_node));
    let target = opt_in(&gateway, nodes, &recipient_node).await?;
    assert_eq!(
        target.encryption_key,
        recipient_node.delegatee_key().delegatee_public_key()
    );
    // Sent twice, as to `d@a` and `d@b`: two ciphertexts of one `Message-ID`.
    gateway.deliver(&target, MESSAGE).await.unwrap();
    gateway.deliver(&target, MESSAGE).await.unwrap();
    // Two mails of two elements each.
    await_owners_holding(nodes, &mail_topic(target.did), |entry| {
        entry.data.len() == 4
    })
    .await?;

    let recipient = mem_recipient(&recipient_node);
    assert_eq!(
        recipient.poll().await.unwrap(),
        PollReport {
            filed: 1,
            duplicates: 1,
            ..PollReport::default()
        },
        "deduplicated by Message-ID"
    );
    assert_eq!(inbox_messages(&recipient).await, vec![MESSAGE.to_vec()]);
    assert_eq!(
        recipient.poll().await.unwrap(),
        PollReport::default(),
        "an opened mail is not opened again"
    );
    Ok(())
}

#[tokio::test]
async fn test_rcpt_for_a_did_without_a_live_descriptor_finds_no_recipient() -> Result<()> {
    let (_network, gateway_node, recipient_node) = connected_pair().await?;
    let gateway = MailGateway::new(Arc::clone(&gateway_node));
    assert_eq!(gateway.recipient(recipient_node.did()).await.unwrap(), None);
    assert_eq!(
        gateway.recipient(gateway_node.did()).await.unwrap(),
        None,
        "a node that does not opt in takes no mail, the gateway's own included"
    );
    Ok(())
}

#[tokio::test]
async fn test_a_forged_chunk_on_the_topic_is_ignored() -> Result<()> {
    let (_network, gateway_node, recipient_node) = connected_pair().await?;
    let nodes = [gateway_node.as_ref(), recipient_node.as_ref()];
    let gateway = MailGateway::new(Arc::clone(&gateway_node));
    let target = opt_in(&gateway, nodes, &recipient_node).await?;
    let sealed = sealed_for(&target);
    let topic = mail_topic(target.did);
    gateway_node
        .swarm
        .storage_extend(&topic, sealed.elements.clone(), MAX_TTL_MS)
        .await?;
    let forged = MailElement::Chunk(Bytes::from_static(b"forged"))
        .encode()
        .unwrap();
    gateway_node
        .storage_append_data(&topic, forged.clone())
        .await?;
    let written = [sealed.elements, vec![forged]].concat();
    await_owners_holding(nodes, &topic, holds_all(&written)).await?;

    let recipient = mem_recipient(&recipient_node);
    let report = recipient.poll().await.unwrap();
    assert_eq!(report, PollReport {
        filed: 1,
        ..PollReport::default()
    });
    assert_eq!(inbox_messages(&recipient).await, vec![MESSAGE.to_vec()]);
    Ok(())
}

#[tokio::test]
async fn test_a_missing_chunk_on_the_topic_discards_the_mail() -> Result<()> {
    let (_network, gateway_node, recipient_node) = connected_pair().await?;
    let nodes = [gateway_node.as_ref(), recipient_node.as_ref()];
    let gateway = MailGateway::new(Arc::clone(&gateway_node));
    let target = opt_in(&gateway, nodes, &recipient_node).await?;
    let mut sealed = sealed_for(&target);
    sealed.elements.pop();
    let topic = mail_topic(target.did);
    gateway_node
        .swarm
        .storage_extend(&topic, sealed.elements.clone(), MAX_TTL_MS)
        .await?;
    await_owners_holding(nodes, &topic, holds_all(&sealed.elements)).await?;

    let recipient = mem_recipient(&recipient_node);
    let report = recipient.poll().await.unwrap();
    assert_eq!(report, PollReport {
        incomplete: 1,
        ..PollReport::default()
    });
    assert!(inbox_messages(&recipient).await.is_empty());
    Ok(())
}

/// Law (lifetime): every node projects a carrier at its clock (`Entry::retired_at`), so the mail
/// a recipient reads opens until `τ + MAX_TTL_MS` and is gone from that instant on.
#[tokio::test]
async fn test_a_mail_not_fetched_within_its_lifetime_is_gone() -> Result<()> {
    let (_network, gateway_node, recipient_node) = connected_pair().await?;
    let nodes = [gateway_node.as_ref(), recipient_node.as_ref()];
    let gateway = MailGateway::new(Arc::clone(&gateway_node));
    let target = opt_in(&gateway, nodes, &recipient_node).await?;
    gateway.deliver(&target, MESSAGE).await.unwrap();
    let topic = mail_topic(target.did);
    await_owners_holding(nodes, &topic, |entry| entry.data.len() == 2).await?;

    let entry = recipient_node
        .fetch_storage_entry(Entry::gen_did(&topic)?)
        .await?
        .expect("the recipient reads the mail its owners hold");
    let issued_at = entry
        .crdt
        .dots
        .iter()
        .map(|dot| dot.version.logical_time_ms)
        .min()
        .expect("the written mail has dots");
    let key = recipient_node.delegatee_key();
    let opened_at = |now_ms: u128| {
        let elements = entry.clone().retired_at(now_ms).data;
        open_mail(&elements, target.did, &key, |_| true)
    };
    let last_instant = issued_at + u128::from(MAX_TTL_MS) - 1;
    assert!(matches!(
        opened_at(last_instant).as_slice(),
        [Opening::Opened(mail)] if mail.message == MESSAGE
    ));
    assert_eq!(opened_at(last_instant + 1), vec![]);
    Ok(())
}

/// Across an in-process delegation renewal (#1153), `MailRegistration` re-issues its lease with
/// the new `delegatee_public_key`, and `Recipient::poll` opens both mail sealed to the previous
/// key before the gateway observed the new descriptor and mail sealed to the new key.
#[tokio::test]
async fn test_a_recipient_opens_mail_sealed_to_its_previous_and_renewed_keys_after_in_process_rotation(
) -> Result<()> {
    let network = network_test_guard().await;
    let gateway_key = SecretKey::random();
    let recipient_key = SecretKey::random();
    let gateway_node = Arc::new(
        prepare_processor_with_identity_key_network_and_virtual_nodes(gateway_key, 0, 0).await,
    );
    let recipient_node = Arc::new(
        prepare_processor_with_identity_key_network_and_virtual_nodes(recipient_key.clone(), 0, 0)
            .await,
    );
    connect_processors(&gateway_node, &recipient_node).await;
    wait_for_mutual_dht_topology(&gateway_node, &recipient_node).await?;
    let nodes = [gateway_node.as_ref(), recipient_node.as_ref()];

    let gateway = MailGateway::new(Arc::clone(&gateway_node));
    let registration = MailRegistration::new(recipient_node.did(), MailOffer::default());
    registration
        .register_once(&RegistrationContext::new(&recipient_node))
        .await?;
    await_owners_holding(nodes, &descriptor_topic(recipient_node.did()), |entry| {
        !entry.data.is_empty()
    })
    .await?;
    let target_before = gateway
        .recipient(recipient_node.did())
        .await
        .unwrap()
        .expect("gateway finds initial mail descriptor");
    let old_pubkey = recipient_node.delegatee_key().delegatee_public_key();
    assert_eq!(target_before.encryption_key, old_pubkey);

    // Gateway seals and delivers a first message to the old key before rotation.
    const FIRST_MAIL: &[u8] =
        b"Message-ID: <before-renewal@example.org>\r\n\r\nSealed to old key.\r\n";
    gateway.deliver(&target_before, FIRST_MAIL).await.unwrap();
    await_owners_holding(nodes, &mail_topic(target_before.did), |entry| {
        entry.data.len() == 2
    })
    .await?;

    // Recipient rotates its delegatee key in process and republishes its mail descriptor.
    let now_ms = get_epoch_ms();
    let ttl_ms = recipient_node.delegatee_key().delegation().ttl_ms();
    let renewed_key = rings_core::delegation::DelegateeKey::new_with_seckey_at(
        &recipient_key,
        ttl_ms,
        now_ms + 1,
    )
    .expect("mint renewed delegatee key");
    let new_pubkey = renewed_key.delegatee_public_key();
    assert_ne!(new_pubkey, old_pubkey);
    recipient_node.renew_delegatee_key(renewed_key, now_ms)?;
    registration
        .register_once(&RegistrationContext::new(&recipient_node))
        .await?;
    await_owners_holding(nodes, &descriptor_topic(recipient_node.did()), |entry| {
        entry.data.len() >= 2
    })
    .await?;

    let target_after = gateway
        .recipient(recipient_node.did())
        .await
        .unwrap()
        .expect("gateway finds republished mail descriptor");
    assert_eq!(target_after.encryption_key, new_pubkey);

    // Gateway delivers a second message sealed to the new key.
    const SECOND_MAIL: &[u8] =
        b"Message-ID: <after-renewal@example.org>\r\n\r\nSealed to new key.\r\n";
    gateway.deliver(&target_after, SECOND_MAIL).await.unwrap();
    await_owners_holding(nodes, &mail_topic(target_after.did), |entry| {
        entry.data.len() == 4
    })
    .await?;

    // Recipient polls once after rotation and opens both messages.
    let recipient = mem_recipient(&recipient_node);
    assert_eq!(recipient.poll().await.unwrap(), PollReport {
        filed: 2,
        ..PollReport::default()
    });
    let mut opened = inbox_messages(&recipient).await;
    opened.sort();
    let mut expected = vec![FIRST_MAIL.to_vec(), SECOND_MAIL.to_vec()];
    expected.sort();
    assert_eq!(opened, expected);
    assert_eq!(
        recipient.poll().await.unwrap(),
        PollReport::default(),
        "neither old-key nor new-key mail is opened a second time"
    );

    drop(network);
    Ok(())
}