fips-core 0.4.5

Reusable FIPS mesh, endpoint, transport, and protocol library
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
use super::*;

// ===== Main Convergence Test =====

/// Integration test: 100 nodes with random connectivity converge to a
/// consistent spanning tree with the correct root.
#[tokio::test]
async fn test_spanning_tree_convergence_100_nodes() {
    let _guard = lock_large_network_test().await;

    const NUM_NODES: usize = 100;
    const TARGET_EDGES: usize = 250;
    const SEED: u64 = 42;

    let edges = generate_random_edges(NUM_NODES, TARGET_EDGES, SEED);
    let mut nodes = run_tree_test(NUM_NODES, &edges, true).await;
    verify_tree_convergence(&nodes);
    cleanup_nodes(&mut nodes).await;
}

// ===== Topology Variant Tests =====

/// Ring topology: 5 nodes in a cycle.
#[tokio::test]
async fn test_spanning_tree_ring() {
    let edges: Vec<(usize, usize)> = vec![(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)];
    let mut nodes = run_tree_test(5, &edges, false).await;
    verify_tree_convergence(&nodes);
    cleanup_nodes(&mut nodes).await;
}

/// Star topology: node 0 connected to all others.
#[tokio::test]
async fn test_spanning_tree_star() {
    let edges: Vec<(usize, usize)> = vec![(0, 1), (0, 2), (0, 3), (0, 4)];
    let mut nodes = run_tree_test(5, &edges, false).await;
    verify_tree_convergence(&nodes);
    cleanup_nodes(&mut nodes).await;
}

/// Linear chain: 0-1-2-3-4.
#[tokio::test]
async fn test_spanning_tree_chain() {
    let edges: Vec<(usize, usize)> = vec![(0, 1), (1, 2), (2, 3), (3, 4)];
    let mut nodes = run_tree_test(5, &edges, false).await;
    verify_tree_convergence(&nodes);
    cleanup_nodes(&mut nodes).await;
}

/// Two disconnected components: nodes 0-2 and nodes 3-5.
#[tokio::test]
async fn test_spanning_tree_disconnected() {
    let edges: Vec<(usize, usize)> = vec![
        (0, 1),
        (1, 2), // component 1
        (3, 4),
        (4, 5), // component 2
    ];
    let mut nodes = run_tree_test(6, &edges, false).await;
    verify_tree_convergence_components(&nodes, &[vec![0, 1, 2], vec![3, 4, 5]]);
    cleanup_nodes(&mut nodes).await;
}

#[tokio::test]
async fn filter_received_before_tree_child_marks_changed_outputs() {
    let edges = [(0, 1), (1, 2), (2, 0)];
    let mut nodes = run_tree_test(3, &edges, false).await;

    let (sender, receiver) = edges
        .iter()
        .flat_map(|&(left, right)| [(left, right), (right, left)])
        .find(|&(sender, receiver)| {
            let sender_addr = nodes[sender].node.node_addr();
            !nodes[receiver].node.is_tree_peer(sender_addr)
                && !nodes[receiver]
                    .node
                    .tree_state()
                    .my_coords()
                    .contains(sender_addr)
        })
        .expect("triangle should have a non-tree edge with a loop-free orientation");
    let sender_addr = *nodes[sender].node.node_addr();
    let receiver_addr = *nodes[receiver].node.node_addr();
    let observer_addr = *nodes[receiver]
        .node
        .peers
        .keys()
        .find(|addr| **addr != sender_addr && nodes[receiver].node.is_tree_peer(addr))
        .expect("receiver should have another tree peer");
    assert!(
        nodes[receiver]
            .node
            .get_peer(&sender_addr)
            .and_then(|peer| peer.inbound_filter())
            .is_some(),
        "the non-tree peer filter should arrive before its child declaration"
    );

    let before = nodes[receiver]
        .node
        .bloom_state
        .compute_outgoing_filter(&observer_addr, &nodes[receiver].node.peer_inbound_filters());
    assert!(
        !before.contains(&sender_addr),
        "a non-tree peer must not contribute to the outgoing filter"
    );
    nodes[receiver]
        .node
        .bloom_state
        .record_sent_filter(observer_addr, before);
    nodes[receiver].node.bloom_state.clear_pending_updates();
    assert!(
        !nodes[receiver]
            .node
            .bloom_state
            .needs_update(&observer_addr)
    );

    {
        let sender_node = &mut nodes[sender].node;
        let sequence = sender_node.tree_state().my_declaration().sequence() + 1;
        sender_node
            .tree_state_mut()
            .set_parent(receiver_addr, sequence, crate::time::now_secs());
        sender_node.tree_state_mut().recompute_coords();
        sender_node
            .tree_state
            .sign_declaration(&sender_node.identity)
            .expect("sign child declaration");
    }
    let encoded = nodes[sender]
        .node
        .build_tree_announce()
        .expect("build child TreeAnnounce")
        .encode()
        .expect("encode child TreeAnnounce");
    nodes[receiver]
        .node
        .handle_tree_announce(&sender_addr, &encoded[1..])
        .await;

    assert!(nodes[receiver].node.is_tree_peer(&sender_addr));
    assert!(
        nodes[receiver]
            .node
            .bloom_state
            .needs_update(&observer_addr),
        "accepting the child declaration should publish the already-received filter"
    );
    cleanup_nodes(&mut nodes).await;
}

/// Tests that a node ignores a signed TreeAnnounce whose advertised root is not the smallest node_addr in the ancestry.
#[tokio::test]
async fn test_rejects_tree_announce_with_inconsistent_root() {
    // Start from a healthy 2-node tree so node B already has a normal, trusted
    // view of node A's coordinates.
    let mut nodes = run_tree_test(2, &[(0, 1)], false).await;

    let a_addr = *nodes[0].node.node_addr();
    let current_root = *nodes[1].node.tree_state().root();
    let current_depth = nodes[1].node.tree_state().my_coords().depth();
    let peer_coords_before = nodes[1]
        .node
        .get_peer(&a_addr)
        .unwrap()
        .coords()
        .unwrap()
        .clone();
    let accepted_before = nodes[1].node.stats().tree.accepted;

    // Use two fixed synthetic ancestors so the forged path is explicit:
    // - fake_parent = 00000000000000000000000000000000
    // - fake_root   = 00000000000000000000000000000001
    //
    // The forged ancestry is therefore:
    //   [A, 000...000, 000...001]
    //
    // That makes 000...001 the advertised root because it is the final entry,
    // even though 000...000 is smaller and appears earlier in the path.
    let fake_parent = NodeAddr::from_bytes([0u8; 16]);
    let mut fake_root_bytes = [0u8; 16];
    fake_root_bytes[15] = 1;
    let fake_root = NodeAddr::from_bytes(fake_root_bytes);

    // Sign a fresh declaration from A. The 99/12345 values are just a newer
    // sequence/timestamp so the announce would be acceptable on freshness
    // grounds if its ancestry semantics were valid.
    let mut declaration = ParentDeclaration::new(a_addr, fake_parent, 99, 12345);
    declaration.sign(nodes[0].node.identity()).unwrap();

    let announce = TreeAnnounce::new(
        declaration,
        TreeCoordinate::new(vec![
            CoordEntry::new(a_addr, 99, 12345),
            CoordEntry::new(fake_parent, 98, 12344),
            CoordEntry::new(fake_root, 97, 12343),
        ])
        .unwrap(),
    );
    let encoded = announce.encode().unwrap();

    nodes[1]
        .node
        .handle_tree_announce(&a_addr, &encoded[1..])
        .await;

    // B should reject the malformed ancestry before mutating either its local
    // tree state or its cached view of peer A.
    assert_eq!(*nodes[1].node.tree_state().root(), current_root);
    assert_eq!(
        nodes[1].node.tree_state().my_coords().depth(),
        current_depth
    );
    assert_eq!(nodes[1].node.stats().tree.accepted, accepted_before);
    assert_eq!(
        nodes[1].node.get_peer(&a_addr).unwrap().coords().unwrap(),
        &peer_coords_before
    );

    cleanup_nodes(&mut nodes).await;
}

#[tokio::test]
async fn test_tree_announce_repushed_on_root_disagreement() {
    let mut nodes = run_tree_test(2, &[(0, 1)], false).await;

    let root_idx = if nodes[0].node.tree_state().is_root() {
        0
    } else {
        1
    };
    let child_idx = 1 - root_idx;
    let root_addr = *nodes[root_idx].node.node_addr();

    assert_eq!(nodes[child_idx].node.tree_state().root(), &root_addr);
    assert!(!nodes[child_idx].node.tree_state().is_root());

    {
        let child = &mut nodes[child_idx].node;
        child.tree_state.become_root();
        child.tree_state.remove_peer(&root_addr);
        child.tree_state.sign_declaration(&child.identity).unwrap();
    }
    assert!(nodes[child_idx].node.tree_state().is_root());

    let _ = drain_all_packets(&mut nodes, false).await;
    tokio::time::sleep(Duration::from_millis(600)).await;

    let root_sent_before = nodes[root_idx].node.stats().tree.sent;
    nodes[child_idx]
        .node
        .send_tree_announce_to_peer(&root_addr)
        .await
        .unwrap();

    let _ = drain_all_packets(&mut nodes, false).await;

    let root_sent_after = nodes[root_idx].node.stats().tree.sent;
    assert!(
        root_sent_after > root_sent_before,
        "root should re-push its TreeAnnounce when a peer advertises a worse root"
    );
    assert!(
        !nodes[child_idx].node.tree_state().is_root(),
        "child should re-attach instead of staying self-rooted"
    );
    assert_eq!(nodes[child_idx].node.tree_state().root(), &root_addr);

    cleanup_nodes(&mut nodes).await;
}

#[tokio::test]
async fn test_parent_reeval_ignores_unmeasured_peer_costs() {
    let mut config = Config::new();
    config.node.tree.hold_down_secs = 0;
    config.node.tree.parent_hysteresis = 0.0;
    config.node.tree.reeval_interval_secs = 1;
    let mut node = Node::new(config).unwrap();
    let transport_id = TransportId::new(1);

    let (current_conn, current_id) =
        make_completed_connection(&mut node, LinkId::new(1), transport_id, 1_000);
    let current_parent = *current_id.node_addr();
    node.add_connection(current_conn).unwrap();
    node.promote_connection(LinkId::new(1), current_id, 2_000)
        .unwrap();

    let (candidate_conn, candidate_id) =
        make_completed_connection(&mut node, LinkId::new(2), transport_id, 1_000);
    let unmeasured_candidate = *candidate_id.node_addr();
    node.add_connection(candidate_conn).unwrap();
    node.promote_connection(LinkId::new(2), candidate_id, 2_000)
        .unwrap();

    let root = make_node_addr(0);
    let intermediate = make_node_addr(1);
    node.tree_state_mut().update_peer(
        ParentDeclaration::new(current_parent, intermediate, 1, 1_000),
        TreeCoordinate::from_addrs(vec![current_parent, intermediate, root]).unwrap(),
    );
    node.tree_state_mut().update_peer(
        ParentDeclaration::new(unmeasured_candidate, root, 1, 1_000),
        TreeCoordinate::from_addrs(vec![unmeasured_candidate, root]).unwrap(),
    );
    node.tree_state_mut().set_parent(current_parent, 2, 1_000);
    node.tree_state_mut().recompute_coords();

    super::super::seed_dataplane_fmp_srtt_for_test(&mut node, current_parent, 10_000);
    assert!(
        !node.dataplane_fmp_has_srtt(&unmeasured_candidate),
        "fixture should leave the candidate without RTT evidence"
    );

    let parent_before = *node.tree_state().my_declaration().parent_id();
    let switches_before = node.stats().tree.parent_switches;

    node.check_tree_state().await;

    assert_eq!(
        node.tree_state().my_declaration().parent_id(),
        &parent_before,
        "periodic parent re-eval must not treat an unmeasured peer as an artificially cheap parent"
    );
    assert_eq!(
        node.stats().tree.parent_switches,
        switches_before,
        "ignored unmeasured candidates must not be counted as parent switches"
    );
}

#[tokio::test]
async fn test_parent_reeval_ignores_fresh_bogus_metrics_without_valid_rtt() {
    let mut config = Config::new();
    config.node.tree.hold_down_secs = 0;
    config.node.tree.parent_hysteresis = 0.0;
    config.node.tree.reeval_interval_secs = 1;
    let mut node = Node::new(config).unwrap();
    let transport_id = TransportId::new(1);

    let (current_conn, current_id) =
        make_completed_connection(&mut node, LinkId::new(1), transport_id, 1_000);
    let current_parent = *current_id.node_addr();
    node.add_connection(current_conn).unwrap();
    node.promote_connection(LinkId::new(1), current_id, 2_000)
        .unwrap();

    let (candidate_conn, candidate_id) =
        make_completed_connection(&mut node, LinkId::new(2), transport_id, 1_000);
    let bogus_candidate = *candidate_id.node_addr();
    node.add_connection(candidate_conn).unwrap();
    node.promote_connection(LinkId::new(2), candidate_id, 2_000)
        .unwrap();

    let root = make_node_addr(0);
    let intermediate = make_node_addr(1);
    node.tree_state_mut().update_peer(
        ParentDeclaration::new(current_parent, intermediate, 1, 1_000),
        TreeCoordinate::from_addrs(vec![current_parent, intermediate, root]).unwrap(),
    );
    node.tree_state_mut().update_peer(
        ParentDeclaration::new(bogus_candidate, root, 1, 1_000),
        TreeCoordinate::from_addrs(vec![bogus_candidate, root]).unwrap(),
    );
    node.tree_state_mut().set_parent(current_parent, 2, 1_000);
    node.tree_state_mut().recompute_coords();

    super::super::seed_dataplane_fmp_srtt_for_test(&mut node, current_parent, 10_000);

    let parent_before = *node.tree_state().my_declaration().parent_id();
    let switches_before = node.stats().tree.parent_switches;

    let counter_baseline = ReceiverReport {
        highest_counter: 100,
        cumulative_packets_recv: 100,
        cumulative_bytes_recv: 10_000,
        timestamp_echo: u32::MAX - 10,
        dwell_time: 20,
        max_burst_loss: u16::MAX,
        mean_burst_loss: u16::MAX,
        jitter: u32::MAX,
        ecn_ce_count: 0,
        owd_trend: i32::MAX,
        burst_loss_count: u32::MAX,
        cumulative_reorder_count: 0,
        interval_packets_recv: 0,
        interval_bytes_recv: 0,
    }
    .encode();
    node.handle_receiver_report(&bogus_candidate, &counter_baseline[1..])
        .await;

    tokio::time::sleep(Duration::from_millis(1)).await;

    let fresh_bogus_delta = ReceiverReport {
        highest_counter: 300,
        cumulative_packets_recv: 100,
        cumulative_bytes_recv: u64::MAX,
        timestamp_echo: u32::MAX - 10,
        dwell_time: 20,
        max_burst_loss: u16::MAX,
        mean_burst_loss: u16::MAX,
        jitter: u32::MAX,
        ecn_ce_count: u32::MAX,
        owd_trend: i32::MIN,
        burst_loss_count: u32::MAX,
        cumulative_reorder_count: u32::MAX,
        interval_packets_recv: 0,
        interval_bytes_recv: u32::MAX,
    }
    .encode();
    node.handle_receiver_report(&bogus_candidate, &fresh_bogus_delta[1..])
        .await;

    let metrics = node
        .dataplane_fmp_link_metrics(&bogus_candidate, std::time::Instant::now())
        .expect("candidate dataplane FMP metrics");
    assert!(
        !node.dataplane_fmp_has_srtt(&bogus_candidate),
        "invalid RTT samples must not make the candidate parent-eligible"
    );
    assert_eq!(
        metrics.last_forward_loss_sample,
        Some((200, 1.0)),
        "fixture should exercise a fresh severe-loss sample rather than a stale report"
    );
    assert!(
        metrics.goodput_bps > 0.0,
        "fixture should exercise a fresh goodput sample rather than a stale report"
    );

    node.check_tree_state().await;

    assert_eq!(
        node.tree_state().my_declaration().parent_id(),
        &parent_before,
        "fresh bogus metrics without valid RTT must not switch parent choice"
    );
    assert_eq!(
        node.stats().tree.parent_switches,
        switches_before,
        "fresh bogus metrics without valid RTT must not count as a parent switch"
    );
}