beekem 0.6.0

BeeKEM: a concurrent variant of TreeKEM for Continuous Group Key Agreement
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
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
//! Tests concurrent membership changes.

use crate::{
    encrypted::EncryptedSecret,
    id::{MemberId, TreeId},
    keys::{NodeKey, ShareKeyMap},
    operation::{CgkaChange, CgkaOperation},
    test_utils::{member, name_for, Group, Member, NO_CITATIONS},
    tree::PathChange,
};
use alloc::{collections::BTreeSet, format, string::ToString, sync::Arc, vec::Vec};
use bolero::{gen, TypeGenerator, ValueGenerator};
use future_form::Local;
use keyhive_crypto::{
    share_key::{ShareKey, ShareSecretKey},
    verified::Verified,
};
use rand::{rngs::StdRng, SeedableRng};

#[tokio::test]
async fn duplicate_adds_fill_one_leaf() {
    let mut rng = StdRng::seed_from_u64(0xd00b_1111);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);
    group.names.insert(d.id, "d".to_string());
    // Distinct prekeys, so the two adds are distinguishable.
    let other_pk = ShareSecretKey::generate(&mut rng).share_key();

    let by_a = group.add(0, d.id, d.pk).await;
    let by_b = group.add(1, d.id, other_pk).await;
    group.broadcast(&by_a);
    group.broadcast(&by_b);
    group.settle(0, &mut rng).await;

    let context = "after two concurrent adds of the same member";
    group.check(context);
    group.assert_members(context, &["a", "b", "c", "d"]);

    // Once `d` is removed, no leaf anywhere may still hold `d`'s key.
    let remove_d = group.remove(0, d.id).await;
    group.broadcast(&remove_d);
    group.settle(0, &mut rng).await;

    let context = "after removing a concurrently double-added member";
    group.check(context);
    group.assert_members(context, &["a", "b", "c"]);
    group.assert_key_agreement(context);
}

#[tokio::test]
async fn every_replica_has_a_tree_root_secret_after_rotation_resolves_concurrent_adds() {
    let mut rng = StdRng::seed_from_u64(0xa11d_5eed);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);
    let e = member(&mut rng);

    let by_a = group.add(0, d.id, d.pk).await;
    let by_b = group.add(1, e.id, e.pk).await;
    group.broadcast(&by_a);
    group.broadcast(&by_b);
    group.settle(0, &mut rng).await;

    let context = "after a rotation resolved two concurrent adds";
    group.check(context);
    group.assert_key_agreement(context);
    for i in 0..group.replicas.len() {
        assert!(
            group.replicas[i].has_tree_root_secret(),
            "{context}, replica {} reports no tree root secret",
            name_for(i)
        );
    }
}

#[tokio::test]
async fn concurrently_added_members_are_placed_in_id_order() {
    let mut rng = StdRng::seed_from_u64(0xa11d_0001);
    let mut group = Group::new(4, &mut rng).await;
    let mut joiners: Vec<Member> = (0..4).map(|_| member(&mut rng)).collect();

    let mut adds = Vec::new();
    for (author, joiner) in joiners.iter().enumerate() {
        adds.push(group.add(author, joiner.id, joiner.pk).await);
    }
    for add in &adds {
        group.broadcast(add);
    }

    joiners.sort_by_key(|joiner| joiner.id);
    let cgka = &mut group.replicas[0];
    cgka.replay_if_pending()
        .expect("replaying the concurrent adds succeeds");
    let leaves: Vec<u32> = joiners
        .iter()
        .map(|joiner| {
            cgka.tree
                .leaf_index_for_id(joiner.id)
                .expect("joiner is placed")
                .u32()
        })
        .collect();
    assert!(
        leaves.is_sorted(),
        "concurrent adds were not placed in id order: {leaves:?}"
    );
}

#[tokio::test]
async fn a_concurrent_add_is_not_applied_before_a_replay() {
    let mut rng = StdRng::seed_from_u64(0xb0f0_0001);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);

    let add_by_b = group.add(1, d.id, d.pk).await;
    group.rotate(0, &mut rng).await;
    group.deliver(&add_by_b, &[0]);

    assert!(
        !group.replicas[0].tree.contains_id(&d.id),
        "an add concurrent with a rotation was applied to the tree without a replay"
    );
}

#[tokio::test]
async fn local_add_sees_a_pending_concurrent_add() {
    let mut rng = StdRng::seed_from_u64(0xb0f0_0000);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);
    group.names.insert(d.id, "d".to_string());

    // `a` rotates first, so `b`'s add reaches it as concurrent and is pending.
    let add_by_b = group.add(1, d.id, d.pk).await;
    let rotation = group.rotate(0, &mut rng).await;
    group.deliver(&add_by_b, &[0]);

    let local = group.replicas[0]
        .add::<Local, _>(d.id, d.pk, None, NO_CITATIONS, &group.members[0].signer)
        .await
        .expect("creating the add succeeds");
    assert!(
        local.is_none(),
        "`a` placed `d` again, though a concurrent add of `d` was already in its graph"
    );

    for op in [&add_by_b, &rotation] {
        group.broadcast(op);
    }
    group.settle(0, &mut rng).await;

    let context = "after adding a member whom a pending concurrent add already covers";
    group.check(context);
    group.assert_members(context, &["a", "b", "c", "d"]);
    group.assert_key_agreement(context);
}

#[tokio::test]
async fn local_remove_sees_a_pending_concurrent_remove() {
    let mut rng = StdRng::seed_from_u64(0xb0f1_1111);
    let mut group = Group::new(3, &mut rng).await;
    let c = group.id(2);

    let remove_by_b = group.remove(1, c).await;
    let rotation = group.rotate(0, &mut rng).await;
    group.deliver(&remove_by_b, &[0]);

    let local = group.replicas[0]
        .remove::<Local, _>(c, NO_CITATIONS, &group.members[0].signer)
        .await;
    assert!(
        matches!(local, Ok(None)),
        "removing a member whom a pending concurrent removal already covers should be \
         a no-op, got {local:?}"
    );

    for op in [&remove_by_b, &rotation] {
        group.broadcast(op);
    }
    group.settle(0, &mut rng).await;

    let context = "after removing a member whom a pending concurrent removal already covers";
    group.check(context);
    group.assert_members(context, &["a", "b"]);
    group.assert_key_agreement(context);
}

#[tokio::test]
async fn local_remove_sees_a_pending_concurrent_add() {
    let mut rng = StdRng::seed_from_u64(0xb0f2_2222);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);
    group.names.insert(d.id, "d".to_string());

    // `a` rotates first, so `b`'s add reaches it as concurrent and is pending.
    let add_by_b = group.add(1, d.id, d.pk).await;
    let rotation = group.rotate(0, &mut rng).await;
    group.deliver(&add_by_b, &[0]);

    // `a`'s tree does not place `d` yet, but its graph holds the add that will.
    let local = group.replicas[0]
        .remove::<Local, _>(d.id, NO_CITATIONS, &group.members[0].signer)
        .await
        .expect("authoring the removal succeeds");
    let removal = local.map(Arc::new).unwrap_or_else(|| {
        panic!(
            "`a`'s removal of `d` was reported as a no-op, though a concurrent add \
             of `d` was already in `a`'s graph, so nothing in the history removes `d`"
        )
    });

    for op in [&add_by_b, &rotation, &removal] {
        group.broadcast(op);
    }
    group.settle(0, &mut rng).await;

    let context = "after removing a member whom a pending concurrent add was about to place";
    group.check(context);
    group.assert_members(context, &["a", "b", "c"]);
    group.assert_key_agreement(context);
}

#[tokio::test]
async fn member_ids_resolves_pending_concurrent_adds() {
    let mut rng = StdRng::seed_from_u64(0x5ead_0001);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);
    let e = member(&mut rng);
    group.names.insert(d.id, "d".to_string());
    group.names.insert(e.id, "e".to_string());

    // `b` and `c` each receive the other's add after applying their own.
    let add_by_b = group.add(1, d.id, d.pk).await;
    let add_by_c = group.add(2, e.id, e.pk).await;
    group.deliver(&add_by_b, &[0, 2]);
    group.deliver(&add_by_c, &[0, 1]);

    for replica in 0..group.replicas.len() {
        let mut got: Vec<&str> = group.replicas[replica]
            .member_ids()
            .expect("resolving pending changes succeeds")
            .map(|id| group.names[&id].as_str())
            .collect();
        got.sort();
        assert_eq!(
            got,
            ["a", "b", "c", "d", "e"],
            "replica {replica} reported members without the pending concurrent add"
        );
    }
    group.check("after reading members with concurrent adds pending");
}

async fn rotation_before_merge_scenario(seed: u64) -> bool {
    let mut rng = StdRng::seed_from_u64(seed);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);
    group.names.insert(d.id, "d".to_string());
    let pk_from_a = d.pk;
    let sk_from_b = ShareSecretKey::generate(&mut rng);
    let pk_from_b = sk_from_b.share_key();

    let add_by_a = group.add(0, d.id, pk_from_a).await;
    let add_by_b = group.add(1, d.id, pk_from_b).await;
    let rot_a = group.rotate(0, &mut rng).await;

    // Replica 0 applies its own add and rotation before `b`'s add reaches it, so
    // `rot_a` is authored against a tree that places `d` at `a`'s prekey.
    group.deliver(&add_by_b, &[2]);
    group.deliver(&add_by_a, &[1, 2]);
    group.deliver(&add_by_b, &[0]);
    group.deliver(&rot_a, &[1, 2]);

    // A membership change forces the merge without re-encrypting any path, so
    // the rotation above is the only writer to `d`'s ancestors.
    let e = member(&mut rng);
    group.names.insert(e.id, "e".to_string());
    let add_e = group.add(2, e.id, e.pk).await;
    group.broadcast(&add_e);

    let merged = format!("seed {seed:#x}, after merging two adds of d and a rotation");
    group.check(&merged);
    group.assert_members(&merged, &["a", "b", "c", "d", "e"]);

    let d_leaf_key = group.replicas[0].tree.node_key_for_id(d.id);
    let (winning_pk, winning_sk) = match d_leaf_key {
        Ok(NodeKey::ShareKey(k)) if k == pk_from_a => (pk_from_a, d.sk),
        Ok(NodeKey::ShareKey(k)) if k == pk_from_b => (pk_from_b, sk_from_b),
        other => panic!("{merged}: `d`'s leaf holds {other:?}, not one of its two added prekeys"),
    };
    let winner_is_a = winning_pk == pk_from_a;

    group.settle(2, &mut rng).await;

    let settled = format!("seed {seed:#x}, after a rotation re-established a root key");
    group.check(&settled);
    group.assert_key_agreement(&settled);

    let mut only_winner = ShareKeyMap::new();
    only_winner.insert(winning_pk, winning_sk);
    group.assert_reads_group_key(
        d.id,
        only_winner,
        &settled,
        "`d` holds the prekey the merge kept and still cannot read the group, so a \
         node is encrypted to the prekey it dropped.",
    );

    winner_is_a
}

#[tokio::test]
async fn a_rotation_before_the_merge_does_not_lock_out_the_added_member() {
    const ROTATION_SEED_BASE: u64 = 0x0170_0000;
    const ROTATION_SEEDS: u64 = 8;

    let mut outcomes = BTreeSet::new();
    for offset in 0..ROTATION_SEEDS {
        outcomes.insert(rotation_before_merge_scenario(ROTATION_SEED_BASE + offset).await);
    }
    assert_eq!(
        outcomes.len(),
        2,
        "over {ROTATION_SEEDS} seeds the merge always kept the same one of `d`'s \
         two prekeys, so the sweep never covered the case where it drops the one \
         the rotation encrypted to"
    );
}

/// One operation as created by the generator.
#[derive(Clone, Copy, Debug, TypeGenerator)]
enum CgkaOp {
    Add { joiner: u8 },
    Remove { target: u8 },
    Update,
}

/// One step of a run. The operation created and whether everything authored so far is
/// synced to every replica before the next step.
#[derive(Clone, Copy, Debug, TypeGenerator)]
struct Step {
    op: CgkaOp,
    deliver_after: bool,
}

/// A randomly generated run of concurrent operations.
///
/// `seed` determines key generation only. The operations themselves come from the
/// generator.
#[derive(Debug)]
struct Scenario {
    seed: u64,
    extra_members: u8,
    ops: Vec<Step>,
}

/// Deliver `undelivered` to `everyone`, retrying until every operation has
/// applied. Panics if a round applies nothing.
fn deliver_all(
    group: &mut Group,
    undelivered: &mut Vec<Arc<Verified<CgkaOperation>>>,
    everyone: &[usize],
) {
    let synced = undelivered.len();
    loop {
        let before = undelivered.len();
        undelivered.retain(|op| !group.try_deliver(op, everyone).is_empty());
        if undelivered.is_empty() {
            break;
        }
        assert!(
            undelivered.len() < before,
            "{} of {synced} operations never became deliverable",
            undelivered.len(),
        );
    }
}

const MIN_OPS: usize = 3;
const MAX_OPS: usize = 12;
const JOINERS: usize = 3;

struct ScenarioOutcome {
    group: Group,
    member_count: usize,
    /// Expected membership.
    expected: BTreeSet<MemberId>,
    /// Ordered list of rotations created during the scenario, represented as
    /// (author_idx, operation, members_at_rotation).
    rotations: Vec<(usize, Arc<Verified<CgkaOperation>>, BTreeSet<MemberId>)>,
}

/// Members take turns creating operations, delivering what is outstanding
/// to all members when a step asks for it. Member 0, which is never a removal
/// target, creates a final rotation at the end so we can check for convergence.
async fn run(scenario: &Scenario) -> ScenarioOutcome {
    let mut rng = StdRng::seed_from_u64(scenario.seed);

    let member_count = 2 + scenario.extra_members as usize % 4;
    let mut group = Group::new(member_count, &mut rng).await;
    let joiners: Vec<Member> = (0..JOINERS)
        .map(|i| {
            let joiner = member(&mut rng);
            group.names.insert(joiner.id, name_for(member_count + i));
            joiner
        })
        .collect();

    let everyone: Vec<usize> = (0..member_count).collect();
    let mut undelivered = Vec::new();
    let mut rotations = Vec::new();

    let mut expected: BTreeSet<MemberId> = (0..member_count).map(|i| group.id(i)).collect();
    for (position, step) in scenario.ops.iter().enumerate() {
        let author = position % member_count;
        let op = match step.op {
            CgkaOp::Add { joiner } => {
                let joiner = &joiners[joiner as usize % JOINERS];
                let (id, pk) = (joiner.id, joiner.pk);
                expected.insert(id);
                group.try_add(author, id, pk).await
            }
            CgkaOp::Remove { target } => {
                let target = 1 + (target as usize % (member_count - 1));
                let target = group.id(target);
                expected.remove(&target);
                group.try_remove(author, target).await
            }
            CgkaOp::Update => {
                let rotation = group.try_rotate(author, &mut rng).await;
                if let Some(op) = &rotation {
                    let tree = group.replicas[author].tree.member_ids().collect();
                    rotations.push((author, op.clone(), tree));
                }
                rotation
            }
        };
        undelivered.extend(op);
        if step.deliver_after {
            deliver_all(&mut group, &mut undelivered, &everyone);
        }
    }
    deliver_all(&mut group, &mut undelivered, &everyone);

    // Ensures any pending concurrent operations are merged.
    let final_rotation = group.rotate(0, &mut rng).await;
    group.broadcast(&final_rotation);
    let tree = group.replicas[0].tree.member_ids().collect();
    rotations.push((0, final_rotation, tree));

    ScenarioOutcome {
        group,
        member_count,
        expected,
        rotations,
    }
}

/// Run `property` over generated scenarios.
fn check_scenarios(property: fn(ScenarioOutcome)) {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("building a runtime succeeds");
    bolero::check!()
        .with_iterations(200)
        .with_generator(
            (
                gen::<u64>(),
                gen::<u8>(),
                gen::<Vec<Step>>().with().len(MIN_OPS..=MAX_OPS),
            )
                .map_gen(|(seed, extra_members, ops)| Scenario {
                    seed,
                    extra_members,
                    ops,
                }),
        )
        .for_each(|scenario| property(runtime.block_on(run(scenario))));
}

#[test]
fn replicas_converge_over_random_concurrent_operations() {
    check_scenarios(|mut outcome| {
        let context = "after a rotation re-established a root key";
        outcome.group.check(context);
        outcome.group.assert_trees_match_replay(context);
        outcome.group.assert_key_agreement(context);
        let got: BTreeSet<MemberId> = outcome.group.replicas[0].tree.member_ids().collect();
        assert_eq!(
            got, outcome.expected,
            "{context}: converged on the wrong membership"
        );
    });
}

/// Decrypt `encrypted`, from tree `doc_id`, with a key from `known`.
pub(super) fn try_decrypt(
    doc_id: TreeId,
    known: &ShareKeyMap,
    encrypter_pk: ShareKey,
    encrypted: &EncryptedSecret<ShareSecretKey>,
) -> Option<ShareSecretKey> {
    let bytes = match known.get(&encrypter_pk) {
        Some(encrypter_sk) => encrypted.try_encrypter_decrypt(doc_id, encrypter_sk).ok()?,
        None => known
            .try_decrypt_encryption(doc_id, encrypter_pk, encrypted)
            .ok()?,
    };
    Some(ShareSecretKey::force_from_bytes(bytes.try_into().ok()?))
}

/// Extend `known` with every node secret it can be used to decrypt from
/// `paths`, in tree `doc_id`. Repeat until nothing else is learned.
pub(super) fn learn_from(
    doc_id: TreeId,
    mut known: ShareKeyMap,
    paths: &[&PathChange],
) -> ShareKeyMap {
    loop {
        let before = known.len();
        for path in paths {
            for (_, node) in &path.path {
                for version in node.versions() {
                    if known.contains_key(&version.pk) {
                        continue;
                    }
                    let secret = version.sk.values().find_map(|encrypted| {
                        try_decrypt(doc_id, &known, version.encrypter_pk, encrypted)
                    });
                    if let Some(sk) = secret {
                        known.insert(version.pk, sk);
                    }
                }
            }
        }
        if known.len() == before {
            return known;
        }
    }
}

pub(super) fn new_path(op: &Verified<CgkaOperation>) -> &PathChange {
    match &op.payload().change {
        CgkaChange::Update { new_path, .. } => new_path,
        _ => panic!("a rotation is an update"),
    }
}

#[test]
fn removed_members_learn_nothing_from_a_rotation_that_excludes_them() {
    check_scenarios(|outcome| {
        let group = &outcome.group;
        let final_tree: BTreeSet<MemberId> = group.replicas[0].tree.member_ids().collect();
        let removed: Vec<usize> = (0..outcome.member_count)
            .filter(|&i| !final_tree.contains(&group.id(i)))
            .collect();
        let paths: Vec<&PathChange> = outcome
            .rotations
            .iter()
            .map(|(_, op, _)| new_path(op))
            .collect();

        for (author, op, tree) in &outcome.rotations {
            if removed.contains(author) {
                continue;
            }
            let excluded: Vec<usize> = removed
                .iter()
                .copied()
                .filter(|&i| !tree.contains(&group.id(i)))
                .collect();
            if excluded.is_empty() {
                continue;
            }
            let mut pooled = ShareKeyMap::new();
            for &i in &excluded {
                pooled.extend(&group.replicas[i].owner_sks);
            }
            let learned = learn_from(group.replicas[0].doc_id, pooled, &paths);
            let recipient =
                (0..outcome.member_count).find(|&j| j != *author && tree.contains(&group.id(j)));
            if let Some(j) = recipient {
                let theirs = learn_from(
                    group.replicas[j].doc_id,
                    group.replicas[j].owner_sks.clone(),
                    &paths,
                );
                assert!(
                    new_path(op).path.iter().any(|(_, node)| node
                        .versions()
                        .iter()
                        .any(|v| theirs.contains_key(&v.pk))),
                    "{} could not decrypt a rotation by {} that included them",
                    name_for(j),
                    name_for(*author),
                );
            }
            for (idx, node) in &new_path(op).path {
                for version in node.versions() {
                    assert!(
                        !learned.contains_key(&version.pk),
                        "removed members {:?} learned the secret at inner node {idx} of a \
                         rotation by {} from a tree they did not belong to",
                        excluded.iter().map(|&i| name_for(i)).collect::<Vec<_>>(),
                        name_for(*author),
                    );
                }
            }
        }
    });
}

#[tokio::test]
async fn a_removal_beats_a_concurrent_add_of_the_same_member() {
    let mut rng = StdRng::seed_from_u64(0x5a3e_0001);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);
    group.names.insert(d.id, "d".to_string());

    let add_by_a = group.add(0, d.id, d.pk).await;
    group.deliver(&add_by_a, &[2]);
    let remove_by_c = group.remove(2, d.id).await;
    group.deliver(&remove_by_c, &[0]);
    // Rotating first puts b's add deeper than the concurrent removal, so replaying in
    // causal order applies it after the removal.
    let rotations_by_b = [
        group.rotate(1, &mut rng).await,
        group.rotate(1, &mut rng).await,
    ];
    let add_by_b = group.add(1, d.id, d.pk).await;
    assert!(
        group.replicas[1].tree.contains_id(&d.id),
        "b's add did not place d in b's tree"
    );

    group.deliver(&add_by_a, &[1]);
    group.deliver(&remove_by_c, &[1]);
    for op in rotations_by_b.iter().chain([&add_by_b]) {
        group.deliver(op, &[0, 2]);
    }
    let next = group.rotate(0, &mut rng).await;
    group.broadcast(&next);

    let context = "after an add concurrent with a removal of the same member";
    group.check(context);
    group.assert_members(context, &["a", "b", "c"]);
    group.assert_key_agreement(context);

    let paths: Vec<&PathChange> = rotations_by_b
        .iter()
        .chain([&next])
        .map(|op| new_path(op))
        .collect();
    let leaf_key = |pk, sk| {
        let mut keys = ShareKeyMap::new();
        keys.insert(pk, sk);
        keys
    };
    let doc_id = group.replicas[0].doc_id;
    let learned_by_d = learn_from(doc_id, leaf_key(d.pk, d.sk), &paths);
    let c = &group.members[2];
    let learned_by_c = learn_from(doc_id, leaf_key(c.pk, c.sk), &paths);
    let next_keys: Vec<ShareKey> = new_path(&next)
        .path
        .iter()
        .flat_map(|(_, node)| node.versions().iter().map(|v| v.pk))
        .collect();
    assert!(
        next_keys.iter().any(|pk| learned_by_c.contains_key(pk)),
        "{context}: c could not decrypt the next rotation"
    );
    assert!(
        !next_keys.iter().any(|pk| learned_by_d.contains_key(pk)),
        "{context}: d learned a secret from the next rotation"
    );
}

// 5 members means the tree has 5 leaves with members and 3 that are blank.
const MEMBERS: usize = 5;

#[tokio::test]
async fn a_concurrent_add_and_remove_retains_the_add() {
    // Which leaf a removal occupies decides which paths it blanks. Every member
    // other than the one creating the removal takes a turn at being removed.
    for (removed_idx, expected) in [
        (1, ["a", "c", "d", "e", "f"]),
        (2, ["a", "b", "d", "e", "f"]),
        (3, ["a", "b", "c", "e", "f"]),
        (4, ["a", "b", "c", "d", "f"]),
    ] {
        let mut rng = StdRng::seed_from_u64(0xadd_0001 + removed_idx as u64);
        let mut group = Group::new(MEMBERS, &mut rng).await;
        let f = member(&mut rng);
        group.names.insert(f.id, "f".to_string());

        let removed = group.id(removed_idx);
        let remove_by_a = group.remove(0, removed).await;
        let add_by_b = group.add(1, f.id, f.pk).await;

        let to_others: Vec<usize> = (1..MEMBERS).collect();
        group.deliver(&remove_by_a, &to_others);
        let to_others: Vec<usize> = (0..MEMBERS).filter(|i| *i != 1).collect();
        group.deliver(&add_by_b, &to_others);
        group.settle(0, &mut rng).await;

        let context = "after an add concurrent with a removal of somebody else";
        group.check(context);
        group.assert_members(context, &expected);
        group.assert_key_agreement(context);
    }
}

#[tokio::test]
async fn a_remove_concurrent_with_several_adds_retains_the_adds() {
    for (removed_idx, expected) in [
        (1, ["a", "c", "d", "e", "f", "g", "h"]),
        (2, ["a", "b", "d", "e", "f", "g", "h"]),
        (3, ["a", "b", "c", "e", "f", "g", "h"]),
        (4, ["a", "b", "c", "d", "f", "g", "h"]),
    ] {
        let mut rng = StdRng::seed_from_u64(0xadd_0003 + removed_idx as u64);
        let mut group = Group::new(MEMBERS, &mut rng).await;

        let removed = group.id(removed_idx);
        let remove_by_a = group.remove(0, removed).await;
        let mut adds_by_b = Vec::new();
        for name in ["f", "g", "h"] {
            let joiner = member(&mut rng);
            group.names.insert(joiner.id, name.to_string());
            adds_by_b.push(group.add(1, joiner.id, joiner.pk).await);
        }

        let to_others: Vec<usize> = (1..MEMBERS).collect();
        group.deliver(&remove_by_a, &to_others);
        let to_others: Vec<usize> = (0..MEMBERS).filter(|i| *i != 1).collect();
        for add in &adds_by_b {
            group.deliver(add, &to_others);
        }
        group.settle(0, &mut rng).await;

        let context = "after three adds concurrent with a removal of somebody else";
        group.check(context);
        group.assert_members(context, &expected);
        group.assert_key_agreement(context);
    }
}

#[tokio::test]
async fn concurrent_removals_of_one_member_leave_a_usable_tree() {
    let mut rng = StdRng::seed_from_u64(0xadd_0005);
    let mut group = Group::new(3, &mut rng).await;
    let d = member(&mut rng);
    group.names.insert(d.id, "d".to_string());

    // Both `a` and `b` remove `c`, and `b` places `d` before it does so.
    let removed = group.id(2);
    let remove_by_a = group.remove(0, removed).await;
    let add_by_b = group.add(1, d.id, d.pk).await;
    let remove_by_b = group.remove(1, removed).await;

    group.deliver(&remove_by_a, &[1, 2]);
    group.deliver(&add_by_b, &[0, 2]);
    group.deliver(&remove_by_b, &[0, 2]);
    group.settle(0, &mut rng).await;

    let context = "after the same member was removed on two replicas at once";
    group.check(context);
    group.assert_members(context, &["a", "b", "d"]);
    group.assert_key_agreement(context);

    let probe = member(&mut rng);
    // Usable means a replica can still add someone.
    for replica in 0..group.replicas.len() {
        group.add(replica, probe.id, probe.pk).await;
    }
}