beekem 0.10.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
//! Tests concurrent updates.

use crate::{
    cgka::{Cgka, NoImplicitRemoves},
    encrypted::{encrypt_secret, EncryptedSecret},
    id::{MemberId, TreeId},
    keys::ShareKeyMap,
    operation::{CgkaChange, CgkaOperation},
    test_utils::{causal_past, for_each_seed, Group},
    tree::PathChange,
    treemath::{InnerNodeIndex, LeafNodeIndex, TreeNodeIndex},
};
use alloc::{collections::BTreeSet, sync::Arc, vec, vec::Vec};
use future_form::Local;
use keyhive_codec::traits::{Decode, Encode};
use keyhive_crypto::{
    share_key::{ShareKey, ShareSecretKey},
    signer::memory::MemorySigner,
    verified::Verified,
};
use rand::{rngs::StdRng, SeedableRng};

#[tokio::test]
async fn replicas_converge_over_concurrent_updates_in_either_order() {
    let mut rng = StdRng::seed_from_u64(0x0cd0_1234);
    let mut group = Group::new(4, &mut rng).await;
    group.settle(0, &mut rng).await;

    let by_a = group.rotate(0, &mut rng).await;
    let by_b = group.rotate(1, &mut rng).await;

    // `a` and `c` see `a`'s rotation first, `b` and `d` see `b`'s.
    group.try_deliver(&by_a, &[2]);
    group.try_deliver(&by_b, &[0, 2]);
    group.try_deliver(&by_b, &[3]);
    group.try_deliver(&by_a, &[1, 3]);

    group.check("after concurrent updates delivered in opposite orders");
}

#[tokio::test]
async fn a_concurrent_update_is_merged_on_arrival() {
    let mut rng = StdRng::seed_from_u64(0x0cd0_1235);
    let mut group = Group::new(2, &mut rng).await;
    group.settle(0, &mut rng).await;

    group.rotate(0, &mut rng).await;
    let by_b = group.rotate(1, &mut rng).await;
    group.deliver(&by_b, &[0]);

    group.assert_trees_match_replay("after a concurrent update arrived");
}

#[test]
fn a_concurrent_updates_secret_is_decrypted_from_its_own_path() {
    for_each_seed(|mut rng| async move {
        let mut group = Group::new(4, &mut rng).await;
        group.settle(0, &mut rng).await;

        let by_a = group.rotate(0, &mut rng).await;
        let by_b = group.rotate(1, &mut rng).await;
        group.broadcast(&by_a);
        group.broadcast(&by_b);

        // Each reader listed received that update while it had another head.
        for (author, op, readers) in [(0, &by_a, vec![1]), (1, &by_b, vec![0, 2, 3])] {
            let op_hash = op.digest();
            let secret = group.replicas[author]
                .root_secrets
                .get(&op_hash)
                .expect("the author records the secret its own update produced");
            for reader in readers {
                let cgka = &mut group.replicas[reader];
                assert_eq!(
                    cgka.root_secrets.get(&op_hash),
                    None,
                    "precondition: the conflicted root left the secret unrecorded"
                );
                assert_eq!(
                    cgka.root_secret_from_update_path(&op_hash),
                    Some(secret.clone()),
                    "replica {reader} should decrypt the secret from the update's own path"
                );
            }
        }
    });
}

#[test]
fn a_secret_neither_its_path_nor_the_chain_reaches_is_rebuilt() {
    for_each_seed(|mut rng| async move {
        let mut group = Group::new(4, &mut rng).await;
        group.settle(0, &mut rng).await;

        // `d` receives `c`'s update while it has its own, so it never decrypts the
        // node `c` set above them, and `a` encrypts its new root to that node.
        let by_c = group.rotate(2, &mut rng).await;
        group.rotate(3, &mut rng).await;
        group.deliver(&by_c, &[0, 3]);
        let by_a = group.rotate(0, &mut rng).await;
        group.deliver(&by_a, &[3]);
        let a_hash = by_a.digest();
        let secret = group.replicas[0]
            .root_secrets
            .get(&a_hash)
            .expect("the author records the secret its own update produced");

        let d = &mut group.replicas[3];
        assert!(
            d.root_secrets.get(&a_hash).is_none(),
            "precondition: d has not recorded the secret"
        );
        assert!(
            d.ops_graph
                .nearest_update_ancestors(&d.ops_graph.cgka_op_heads)
                .len()
                > 1,
            "precondition: d has more than one nearest update, so it cannot record the tree's secret"
        );
        assert!(
            d.clone().root_secret_from_update_path(&a_hash).is_none(),
            "precondition: d cannot decrypt the secret from the update's path"
        );
        assert!(
            !d.ops_graph.is_chainable(&a_hash),
            "precondition: no later update can wrap the secret in the chain"
        );
        assert_eq!(
            d.group_secret_from_hashes(&secret.digest(), &a_hash).ok(),
            Some(secret),
            "a rebuild from d's earlier leaf key should derive the secret"
        );
    });
}

/// Rotate `cgka`'s leaf to `sk`.
async fn rotate_to(
    cgka: &mut Cgka<NoImplicitRemoves>,
    signer: &MemorySigner,
    sk: ShareSecretKey,
    rng: &mut StdRng,
) -> Arc<Verified<CgkaOperation>> {
    let (_, op, _) = cgka
        .update::<Local, _, _>(sk.share_key(), sk, signer, rng)
        .await
        .expect("the owner can rotate");
    Arc::new(op)
}

#[tokio::test]
async fn one_identitys_concurrent_rotations_leave_every_replica_with_the_same_leaf_keys() {
    let mut rng = StdRng::seed_from_u64(0x0cd0_1236);
    let mut group = Group::new(3, &mut rng).await;
    group.settle(0, &mut rng).await;
    let mut sks: Vec<ShareSecretKey> = (0..3).map(|_| ShareSecretKey::generate(&mut rng)).collect();
    sks.sort_by_key(|sk| sk.share_key());
    let [lowest, middle, highest]: [ShareSecretKey; 3] =
        sks.try_into().expect("three keys were generated");

    // A second instance of `b` rotates to the middle key while the first
    // rotates to the lowest and then the highest. `c` receives the second
    // instance's rotation first, `a` and `b` last.
    let signer = group.members[1].signer.clone();
    let mut second_instance = group.replicas[1].clone();
    let by_second = rotate_to(&mut second_instance, &signer, middle, &mut rng).await;
    let first = rotate_to(&mut group.replicas[1], &signer, lowest, &mut rng).await;
    let then = rotate_to(&mut group.replicas[1], &signer, highest, &mut rng).await;
    group.deliver(&by_second, &[2]);
    for op in [&first, &then] {
        group.deliver(op, &[0, 2]);
    }
    group.deliver(&by_second, &[0, 1]);

    group.check("after one identity rotated its leaf from two instances");
    group.assert_trees_match_replay("after one identity rotated its leaf from two instances");
}

/// `op` with its change edited by `edit` and signed again by `signer`.
async fn resigned(
    op: &Verified<CgkaOperation>,
    signer: &MemorySigner,
    edit: impl FnOnce(&mut CgkaChange),
) -> Arc<Verified<CgkaOperation>> {
    let mut payload = op.payload().clone();
    edit(&mut payload.change);
    Arc::new(
        Verified::sign::<Local, _>(&payload, signer)
            .await
            .expect("signing succeeds"),
    )
}

/// Flip one byte of `sealed`'s ciphertext. It still decodes and seals to the
/// same key, so an update carrying it has the same keys and a new digest.
fn reseal(sealed: &mut EncryptedSecret<ShareSecretKey>) {
    let mut bytes = sealed.encode().as_bytes().to_vec();
    bytes[10] ^= 1;
    *sealed = EncryptedSecret::decode(&bytes).expect("a flipped ciphertext byte still decodes");
}

/// Give the node at position `at` on `new_path` the existing key `pk`, and
/// encrypt it and the node above it again so the path stays well formed.
/// `secrets` has the secrets of `pk` and of every key on the path.
fn reuse_key(
    new_path: &mut PathChange,
    at: usize,
    pk: ShareKey,
    secrets: &ShareKeyMap,
    doc_id: TreeId,
) {
    let secret = |key: &ShareKey| {
        secrets
            .get(key)
            .expect("the secret of a key on the path")
            .clone()
    };
    // A node's encrypter is the previous key down the path.
    let encrypter_pk = match at.checked_sub(1) {
        Some(below) => new_path.path[below].1.pk,
        None => new_path.leaf_pk,
    };
    let encrypter_sk = secret(&encrypter_pk);
    let node = &mut new_path.path[at].1;
    node.pk = pk;
    for sealed in node.sk.values_mut() {
        *sealed = encrypt_secret(doc_id, &secret(&pk), &encrypter_sk, &sealed.paired_pk)
            .expect("encryption succeeds");
    }
    if let Some((_, above)) = new_path.path.get_mut(at + 1) {
        let above_sk = secret(&above.pk);
        for sealed in above.sk.values_mut() {
            *sealed = encrypt_secret(doc_id, &above_sk, &secret(&pk), &sealed.paired_pk)
                .expect("encryption succeeds");
        }
    }
    debug_assert!(new_path.is_well_formed());
}

#[tokio::test]
async fn replicas_converge_when_an_update_reuses_a_key_a_causally_unrelated_update_removes() {
    let mut rng = StdRng::seed_from_u64(0x0cd0_1239);
    let mut group = Group::new(4, &mut rng).await;
    group.settle(0, &mut rng).await;

    // `b`'s update, concurrent with `a`'s, writes the key `a` wrote at the
    // node above them. `a`'s next update removes that key.
    let by_a = group.rotate(0, &mut rng).await;
    let CgkaChange::Update {
        new_path: a_path, ..
    } = &by_a.payload().change
    else {
        unreachable!("a rotation is an update")
    };
    let a_key = a_path.path[0].1.pk;
    let above = TreeNodeIndex::Inner(InnerNodeIndex::new(a_path.path[0].0));
    // `b` can decrypt that key's secret from `a`'s update, being its sibling.
    let a_sk = group.replicas[0]
        .owner_sks
        .get(&a_key)
        .expect("a has its path secrets")
        .clone();
    let signer = group.members[1].signer.clone();
    let mut b_copy = group.replicas[1].clone();
    let b_leaf = ShareSecretKey::generate(&mut rng);
    let by_b = rotate_to(&mut b_copy, &signer, b_leaf, &mut rng).await;
    b_copy.owner_sks.insert(a_key, a_sk);
    let by_b = resigned(&by_b, &signer, |change| {
        let CgkaChange::Update { new_path, .. } = change else {
            unreachable!("a rotation is an update")
        };
        reuse_key(new_path, 0, a_key, &b_copy.owner_sks, b_copy.doc_id);
    })
    .await;
    group.deliver(&by_b, &[1]);
    group.deliver(&by_a, &[1, 2, 3]);
    let then_by_a = group.rotate(0, &mut rng).await;

    // `b` and `c` apply `b`'s update before `a`'s second, `a` and `d` after it.
    group.deliver(&by_b, &[2]);
    group.deliver(&then_by_a, &[1, 2, 3]);
    group.deliver(&by_b, &[0, 3]);

    group.check("after an update reused a key a causally unrelated update removes");
    group.assert_trees_match_replay(
        "after an update reused a key a causally unrelated update removes",
    );
    // `a`'s second update saw its first one there but not `b`'s, so `b`'s
    // version survives beside it although the two share a key.
    for replica in &group.replicas {
        let origins: BTreeSet<_> = replica
            .tree
            .origins_by_node()
            .into_iter()
            .filter(|(node, _)| *node == above)
            .map(|(_, origin)| origin)
            .collect();
        assert_eq!(origins, BTreeSet::from([by_b.digest(), then_by_a.digest()]));
    }
}

/// An update and a copy of it, re-signed by its author, that differ only in the secret
/// sealed to `entry`. Both contain the same keys, and neither is causally after the other.
async fn an_update_and_its_resealed_twin(
    group: &mut Group<NoImplicitRemoves>,
    author: usize,
    entry: TreeNodeIndex,
    rng: &mut StdRng,
) -> (Arc<Verified<CgkaOperation>>, Arc<Verified<CgkaOperation>>) {
    let update = group.rotate(author, rng).await;
    let twin = resigned(&update, &group.members[author].signer, |change| {
        let CgkaChange::Update { new_path, .. } = change else {
            unreachable!("a rotation is an update")
        };
        reseal(
            new_path.path[0]
                .1
                .sk
                .get_mut(&entry)
                .expect("the path's first node seals a secret to that child"),
        );
    })
    .await;
    (update, twin)
}

#[tokio::test]
async fn a_resealed_twin_arriving_after_a_covering_update_leaves_replicas_matching_a_replay() {
    let mut rng = StdRng::seed_from_u64(0x0cd0_1241);
    let mut group = Group::new(4, &mut rng).await;
    group.settle(0, &mut rng).await;

    let (update, twin) = an_update_and_its_resealed_twin(
        &mut group,
        1,
        TreeNodeIndex::Leaf(LeafNodeIndex::new(1)),
        &mut rng,
    )
    .await;
    group.broadcast(&update);
    // `a`'s update covers `b`'s, so it removes the keys the twin also contains.
    let by_a = group.rotate(0, &mut rng).await;
    group.broadcast(&by_a);
    group.broadcast(&twin);

    group.check("after the twin arrives behind a covering update");
    group.assert_trees_match_replay("after the twin arrives behind a covering update");
    group.settle(2, &mut rng).await;
    group.assert_key_agreement("after an update that has the twin in its past");
}

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

    // As in a document's genesis, `a` rotates with the prekey its add
    // contained, while a second instance of `a` rotates to a fresh key. `b`
    // receives the genesis rotation first, `c` the other.
    let signer = group.members[0].signer.clone();
    let prekey = group.members[0].sk.clone();
    let mut second_instance = group.replicas[0].clone();
    let fresh = ShareSecretKey::generate(&mut rng);
    let by_second = rotate_to(&mut second_instance, &signer, fresh, &mut rng).await;
    let genesis = rotate_to(&mut group.replicas[0], &signer, prekey, &mut rng).await;
    group.deliver(&genesis, &[1]);
    group.deliver(&by_second, &[0, 1, 2]);
    group.deliver(&genesis, &[2]);

    group.check("after a rotation keeping the leaf key and a concurrent one by another instance");
    group.assert_trees_match_replay(
        "after a rotation keeping the leaf key and a concurrent one by another instance",
    );
}

/// One author in [`replicas_converge_over_random_causal_delivery_orders`]: a member's
/// signer and one replica of that member.
struct Author {
    signer: MemorySigner,
    replica: Cgka<NoImplicitRemoves>,
}

/// Merge `op` into `replica`, and assert that the versions it removed are
/// exactly those at the nodes it writes whose origins are in its causal past.
fn merge_removing_only_its_past(
    replica: &mut Cgka<NoImplicitRemoves>,
    op: &Arc<Verified<CgkaOperation>>,
) {
    let CgkaChange::Update { new_path, .. } = &op.payload().change else {
        unreachable!("these ops are rotations")
    };
    let issuer = MemberId::from(op.issuer());
    // Only updates are applied, so every path is valid.
    let written: Vec<TreeNodeIndex> = [TreeNodeIndex::Leaf(
        *replica
            .tree
            .leaf_index_for_id(issuer)
            .expect("the issuer is in the tree"),
    )]
    .into_iter()
    .chain(
        new_path
            .path
            .iter()
            .map(|(idx, _)| TreeNodeIndex::Inner(InnerNodeIndex::new(*idx))),
    )
    .collect();
    let past = causal_past(&replica.ops_graph, &op.payload().predecessors);
    let before = replica.tree.origins_by_node();
    replica
        .merge_concurrent_operation(op.clone())
        .expect("the op's predecessors are applied");
    let after = replica.tree.origins_by_node();
    for (node, origin) in before.iter().filter(|version| !after.contains(version)) {
        assert!(
            past.contains(origin) && written.contains(node),
            "merging {} removed a version at {node:?} written by {origin}, which is not a node \
             it writes or not in its past",
            op.digest()
        );
    }
    let kept = replica.tree.origins_at(issuer, new_path);
    assert!(
        kept.is_disjoint(&past),
        "merging {} kept a version written in its past at a node it writes",
        op.digest()
    );
}

/// Apply to `replica` every op in `ops` it lacks, choosing at random among
/// those whose predecessors it has, until `limit` are applied or none is left.
fn deliver_in_random_causal_order(
    replica: &mut Cgka<NoImplicitRemoves>,
    ops: &[Arc<Verified<CgkaOperation>>],
    limit: usize,
    rng: &mut StdRng,
) {
    use rand::seq::IteratorRandom;
    for _ in 0..limit {
        let Some(op) = ops
            .iter()
            .filter(|op| {
                !replica.ops_graph.contains_op_hash(&op.digest())
                    && replica.contains_all(op.payload().predecessors())
            })
            .choose(rng)
        else {
            return;
        };
        merge_removing_only_its_past(replica, op);
    }
}

/// A rotation by `author`, edited at random so that it reuses another op's key
/// at a node they share, or is a resealed twin of one of `author`'s earlier
/// ops. The author's replica applies it. `secrets` has the secret of every
/// key on a published path, as a member who decrypted them would, and gains
/// those of this rotation.
async fn a_rotation_that_may_misbehave(
    author: &mut Author,
    published: &[Arc<Verified<CgkaOperation>>],
    secrets: &mut ShareKeyMap,
    rng: &mut StdRng,
) -> Arc<Verified<CgkaOperation>> {
    use rand::{seq::IndexedRandom, RngExt};
    let paths: Vec<_> = published
        .iter()
        .filter_map(|op| match &op.payload().change {
            CgkaChange::Update { new_path, .. } => Some(new_path.as_ref()),
            _ => None,
        })
        .collect();
    let own: Vec<_> = published
        .iter()
        .filter(|op| {
            MemberId::from(op.issuer()) == MemberId::from(&author.signer.0)
                && author.replica.ops_graph.contains_op_hash(&op.digest())
        })
        .collect();
    let choice = rng.random_range(0..3);
    if choice == 2 {
        if let Some(original) = own.choose(rng) {
            let twin = resigned(original, &author.signer, |change| {
                let CgkaChange::Update { new_path, .. } = change else {
                    unreachable!("an author's ops are rotations")
                };
                if let Some(sealed) = new_path
                    .path
                    .first_mut()
                    .and_then(|(_, node)| node.sk.values_mut().next())
                {
                    reseal(sealed);
                }
            })
            .await;
            author
                .replica
                .merge_concurrent_operation(twin.clone())
                .expect("the twin's predecessors are applied");
            return twin;
        }
    }
    let sk = ShareSecretKey::generate(rng);
    let mut copy = author.replica.clone();
    let op = rotate_to(&mut copy, &author.signer, sk, rng).await;
    secrets.extend(&copy.owner_sks);
    let op = resigned(&op, &author.signer, |change| {
        let CgkaChange::Update { new_path, .. } = change else {
            unreachable!("a rotation is an update")
        };
        if choice == 1 {
            let shared: Vec<_> = new_path
                .path
                .iter()
                .enumerate()
                .flat_map(|(i, (idx, _))| {
                    paths.iter().flat_map(move |path| {
                        path.path
                            .iter()
                            .filter(move |(other_idx, _)| other_idx == idx)
                            .map(move |(_, node)| (i, node.pk))
                    })
                })
                .collect();
            if let Some((i, pk)) = shared.choose(rng) {
                reuse_key(new_path, *i, *pk, secrets, copy.doc_id);
            }
        }
    })
    .await;
    author
        .replica
        .merge_concurrent_operation(op.clone())
        .expect("the author has the rotation's predecessors");
    op
}

#[test]
fn replicas_converge_over_random_causal_delivery_orders() {
    for_each_seed(|mut rng| async move {
        use rand::RngExt;
        let mut group = Group::new(3, &mut rng).await;
        group.settle(0, &mut rng).await;
        let start = group.replicas.clone();

        // Each member, and a second instance of `a`, rotates after receiving
        // some of the ops published so far.
        let mut authors: Vec<Author> = (0..3)
            .map(|i| Author {
                signer: group.members[i].signer.clone(),
                replica: start[i].clone(),
            })
            .chain([Author {
                signer: group.members[0].signer.clone(),
                replica: start[0].clone(),
            }])
            .collect();
        let mut published = Vec::new();
        let mut secrets = ShareKeyMap::new();
        for _ in 0..10 {
            let author = &mut authors[rng.random_range(0..4)];
            let limit = rng.random_range(0..=published.len());
            deliver_in_random_causal_order(&mut author.replica, &published, limit, &mut rng);
            let op =
                a_rotation_that_may_misbehave(author, &published, &mut secrets, &mut rng).await;
            published.push(op);
        }

        let mut replicas: Vec<_> = authors.into_iter().map(|a| a.replica).collect();
        replicas.extend(start.iter().cloned());
        for replica in &mut replicas {
            deliver_in_random_causal_order(replica, &published, usize::MAX, &mut rng);
        }
        group.replicas = replicas;
        group.check("after every replica applied every op");
        group.assert_trees_match_replay("after every replica applied every op");
    });
}