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
//! The update predecessor secret chain.

use crate::{
    cgka::{Cgka, NoImplicitRemoves},
    collections::Set,
    keys::ShareKeyMap,
    operation::{CgkaChange, CgkaOperation, PredecessorSecret},
    pcs_key::PcsKey,
    test_utils::{assert_chain_bookkeeping, for_each_seed, member, Group, Member},
    transact::{Fork, Merge},
};
use alloc::{sync::Arc, vec, vec::Vec};
use future_form::Local;
use keyhive_crypto::{
    digest::Digest,
    share_key::ShareSecretKey,
    signer::{async_signer::AsyncSigner, memory::MemorySigner},
    verified::Verified,
};
use rand::rngs::StdRng;

async fn rotate<S: AsyncSigner<Local>, R: rand::CryptoRng>(
    cgka: &mut Cgka<NoImplicitRemoves>,
    signer: &S,
    csprng: &mut R,
) -> (PcsKey, Verified<CgkaOperation>) {
    let sk = ShareSecretKey::generate(csprng);
    let (pcs_key, op, _) = cgka
        .update::<Local, _, _>(sk.share_key(), sk, signer, csprng)
        .await
        .unwrap();
    (pcs_key, op)
}

fn predecessor_secrets(op: &Verified<CgkaOperation>) -> &[PredecessorSecret] {
    let CgkaChange::Update {
        predecessor_secrets,
        ..
    } = &op.payload().change
    else {
        panic!("an update should be an Update op")
    };
    predecessor_secrets
}

fn added_to_chain(op: &Verified<CgkaOperation>, hash: &Digest<CgkaOperation>) -> bool {
    predecessor_secrets(op)
        .iter()
        .any(|s| s.update_op_hash == *hash)
}

/// `member`'s [`Cgka`] built by applying every operation in `source`.
fn view_of(source: &Cgka<NoImplicitRemoves>, member: &Member) -> Cgka<NoImplicitRemoves> {
    let mut sks = ShareKeyMap::new();
    sks.insert(member.pk, member.sk.clone());
    let mut view = Cgka::new(source.doc_id, member.id, sks, NoImplicitRemoves);
    view.apply_batches(&source.ops().unwrap()).unwrap();
    view
}

/// Re-sign `op` with its predecessor secrets replaced by `entries`.
async fn with_entries(
    signer: &MemorySigner,
    op: &Verified<CgkaOperation>,
    entries: Vec<PredecessorSecret>,
) -> Verified<CgkaOperation> {
    let CgkaChange::Update { ref new_path, .. } = op.payload().change else {
        panic!("an update should be an Update op")
    };
    let rebuilt = CgkaOperation {
        doc_id: op.payload().doc_id,
        predecessors: op.payload().predecessors.clone(),
        change: CgkaChange::Update {
            new_path: new_path.clone(),
            predecessor_secrets: entries,
        },
    };
    Verified::sign::<Local, _>(&rebuilt, signer).await.unwrap()
}

/// Alice rotates and adds Carol while Bob rotates, and Alice receives Bob's
/// update. Carol, who cannot derive Bob's secret, then updates from Alice's
/// history. Returns the group, Alice's and Bob's update hashes, and Carol's
/// update, which nobody has applied yet.
async fn carol_updates_without_bobs_secret(
    rng: &mut StdRng,
) -> (
    Group<NoImplicitRemoves>,
    Digest<CgkaOperation>,
    Digest<CgkaOperation>,
    Verified<CgkaOperation>,
) {
    let mut group = Group::new(2, rng).await;
    let alice_op1_hash = group.rotate(0, rng).await.digest();
    let carol = member(rng);
    group.add(0, carol.id, carol.pk).await;
    let bob_op = group.rotate(1, rng).await;
    group.deliver(&bob_op, &[0]);

    let mut carol_cgka = view_of(&group.replicas[0], &carol);
    let (_, carol_op) = rotate(&mut carol_cgka, &carol.signer, rng).await;
    (group, alice_op1_hash, bob_op.digest(), carol_op)
}

#[test]
fn an_update_chains_an_ancestor_an_earlier_update_could_not() {
    for_each_seed(|mut rng| async move {
        let (mut group, alice_op1_hash, bob_op_hash, carol_op) =
            carol_updates_without_bobs_secret(&mut rng).await;
        let alice_signer = group.members[0].signer.clone();
        let carol_op_hash = carol_op.digest();
        assert!(
            added_to_chain(&carol_op, &alice_op1_hash),
            "Carol should add the ancestor secret her invitation wraps to the chain"
        );

        let alice = &mut group.replicas[0];
        alice
            .merge_concurrent_operation(Arc::new(carol_op))
            .unwrap();
        assert!(
            !alice.unchained_updates.contains(&alice_op1_hash),
            "an entry we did not author should be chained once it decrypts to the real secret"
        );
        assert!(
            alice.unchained_updates.contains(&bob_op_hash),
            "an update nothing added to the chain should still be reported as unchained"
        );
        assert_eq!(
            alice
                .ops_graph
                .nearest_update_ancestors(&alice.ops_graph.cgka_op_heads),
            Set::from_iter([carol_op_hash]),
            "precondition: Carol's update should cover Bob's, leaving the unchained record as the \
             only route to it"
        );

        let (_, alice_op2) = rotate(alice, &alice_signer, &mut rng).await;
        assert!(
            added_to_chain(&alice_op2, &bob_op_hash),
            "a member that can derive an unchained ancestor secret should add it to the chain"
        );
        assert!(
            !alice.unchained_updates.contains(&bob_op_hash),
            "an update in the chain should no longer be reported as unchained"
        );
    });
}

#[test]
fn the_traversal_ignores_an_entry_whose_secret_is_not_its_updates() {
    for_each_seed(|mut rng| async move {
        let mut group = Group::new(2, &mut rng).await;
        let doc_id = group.replicas[0].doc_id;
        let alice_signer = group.members[0].signer.clone();
        let bob_id = group.members[1].id;
        let bob_pk = group.members[1].pk;
        let bob_sk = group.members[1].sk.clone();
        let alice = &mut group.replicas[0];

        let (_, op1) = rotate(alice, &alice_signer, &mut rng).await;
        let op1_hash = op1.digest();
        let (root2, op2) = rotate(alice, &alice_signer, &mut rng).await;
        let op2_hash = op2.digest();
        let (root3, op3) = rotate(alice, &alice_signer, &mut rng).await;
        let op3_hash = op3.digest();

        // Rebuild the third update with only an entry that wraps root2 labelled
        // with op1, an update that did not produce it.
        let entry = PredecessorSecret {
            update_op_hash: op1_hash,
            encrypted_root_secret: root3
                .derive_predecessor_secrets_key()
                .try_seal(root2.0.as_slice(), doc_id.as_bytes())
                .unwrap(),
        };
        let tampered_op = with_entries(&alice_signer, &op3, vec![entry]).await;

        let mut bob_sks = ShareKeyMap::new();
        bob_sks.insert(bob_pk, bob_sk);
        let mut bob = Cgka::new(doc_id, bob_id, bob_sks, NoImplicitRemoves);
        for epoch in alice.ops().unwrap() {
            for op in epoch.iter() {
                if op.digest() == op3_hash {
                    continue;
                }
                bob.apply_operation_and_record_root_secret(op.clone())
                    .unwrap();
            }
        }
        let tampered_hash = tampered_op.digest();
        bob.apply_operation_and_record_root_secret(Arc::new(tampered_op))
            .unwrap();
        assert!(
            bob.root_secrets.get(&tampered_hash).is_some(),
            "precondition: Bob records the tampered update's secret"
        );

        // With only the third update's secret recorded, the forged entry is the
        // traversal's only route to op1.
        bob.root_secrets.remove(&op1_hash);
        bob.root_secrets.remove(&op2_hash);
        assert_eq!(
            bob.root_secret_from_chain(&op1_hash),
            None,
            "the traversal took a secret for op1 from an entry whose secret op1 did not produce"
        );
        assert!(
            bob.root_secrets.get(&op1_hash).is_none(),
            "the forged secret should not be recorded for op1"
        );
    });
}

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

        // Everyone sees Bob's update, so Mallory's follows it and Alice can derive
        // Mallory's root secret when it arrives.
        let target = group.rotate(1, &mut rng).await;
        let target_hash = target.digest();
        group.broadcast(&target);

        // Mallory has her own update's root secret, so she can encrypt anything at
        // all under the key its entries are read with. The entry is correctly
        // signed, and anyone could sign one like it about any update.
        let genuine = group.rotate(2, &mut rng).await;
        let mallory_secret = group.replicas[2]
            .root_secrets
            .get(&genuine.digest())
            .expect("the author records the secret its own update produced");
        let doc_id = group.replicas[0].doc_id;
        let forged = with_entries(
            &group.members[2].signer,
            &genuine,
            vec![PredecessorSecret {
                update_op_hash: target_hash,
                encrypted_root_secret: mallory_secret
                    .derive_predecessor_secrets_key()
                    .try_seal(&[0u8; 32], doc_id.as_bytes())
                    .expect("sealing 32 bytes should succeed"),
            }],
        )
        .await;
        let forged_hash = forged.digest();
        group.replicas[0]
            .merge_concurrent_operation(Arc::new(forged))
            .unwrap();
        assert!(
            group.replicas[0].root_secrets.get(&forged_hash).is_some(),
            "precondition: Alice records the forged update's secret, so she reads its entries"
        );

        assert!(
            group.replicas[0].unchained_updates.contains(&target_hash),
            "an entry that does not contain the root secret of the update it refers to \
             should not chain it"
        );
    });
}

#[test]
fn an_invitation_leaves_out_an_update_already_in_the_chain() {
    for_each_seed(|mut rng| async move {
        let mut group = Group::new(2, &mut rng).await;
        group.rotate(0, &mut rng).await;
        let op2_hash = group.rotate(0, &mut rng).await.digest();

        let invitee = member(&mut rng);
        let add = group.add(0, invitee.id, invitee.pk).await;
        let CgkaChange::Add { invitation, .. } = &add.payload().change else {
            panic!("an add should be an Add op")
        };
        let wrapped: Vec<_> = invitation
            .as_ref()
            .expect("the adder can derive the head secret")
            .ancestor_secrets
            .iter()
            .map(|secret| secret.update_op_hash)
            .collect();
        assert_eq!(
            wrapped,
            vec![op2_hash],
            "the second update put the first in the chain, so the invitation wraps only the second"
        );
    });
}

/// Carol, added after three updates by the only other member. Returns her, her
/// [`Cgka`], and each update with the secret it produced.
async fn carol_added_after_three_updates(
    rng: &mut StdRng,
) -> (
    Member,
    Cgka<NoImplicitRemoves>,
    Vec<(Digest<CgkaOperation>, PcsKey)>,
) {
    let mut group = Group::new(1, rng).await;
    let mut updates = Vec::new();
    for _ in 0..3 {
        let op_hash = group.rotate(0, rng).await.digest();
        let secret = group.replicas[0]
            .root_secrets
            .get(&op_hash)
            .expect("the author records the secret its own update produced");
        updates.push((op_hash, secret));
    }
    let carol = member(rng);
    group.add(0, carol.id, carol.pk).await;
    let carol_cgka = view_of(&group.replicas[0], &carol);
    (carol, carol_cgka, updates)
}

#[test]
fn the_traversal_records_each_secret_it_derives() {
    for_each_seed(|mut rng| async move {
        let (_, mut carol_cgka, updates) = carol_added_after_three_updates(&mut rng).await;
        assert_eq!(
            carol_cgka.root_secret_from_chain(&updates[0].0),
            Some(updates[0].1.clone()),
            "precondition: Carol reads back to the oldest update"
        );

        for (op_hash, secret) in updates {
            assert_eq!(
                carol_cgka.root_secrets.get(&op_hash),
                Some(secret),
                "every secret on the way back to the oldest update should be recorded for its update"
            );
        }
    });
}

#[test]
fn a_merge_reports_the_unchained_updates_of_the_merged_history() {
    for_each_seed(|mut rng| async move {
        let (mut group, _, _, carol_op) = carol_updates_without_bobs_secret(&mut rng).await;
        group.replicas[0]
            .merge_concurrent_operation(Arc::new(carol_op))
            .unwrap();
        let alice = group.replicas[0].fork();

        // Only the merge tells Bob that Carol's update made his chainable.
        let bob = &mut group.replicas[1];
        bob.merge(alice);

        assert_chain_bookkeeping(bob, "after the merge");
    });
}

#[test]
fn a_merge_keeps_what_either_side_chained() {
    for_each_seed(|mut rng| async move {
        let (mut group, _, bob_op_hash, carol_op) =
            carol_updates_without_bobs_secret(&mut rng).await;
        let alice_signer = group.members[0].signer.clone();
        let alice = &mut group.replicas[0];
        alice
            .merge_concurrent_operation(Arc::new(carol_op))
            .unwrap();
        let behind = alice.fork();

        // The second rotation keeps the update that chains Bob's from being the
        // head a replay records.
        rotate(alice, &alice_signer, &mut rng).await;
        rotate(alice, &alice_signer, &mut rng).await;
        assert!(
            behind.unchained_updates.contains(&bob_op_hash)
                && !alice.unchained_updates.contains(&bob_op_hash),
            "precondition: only Alice has chained Bob's update"
        );

        let mut caught_up = behind.fork();
        caught_up.merge(alice.fork());
        assert_chain_bookkeeping(&caught_up, "after merging in an update that chains ours");

        let mut alice_merged = alice.fork();
        alice_merged.merge(behind);
        assert_chain_bookkeeping(&alice_merged, "after merging in our own update unchained");
    });
}

#[test]
fn a_new_members_first_update_wraps_only_what_is_not_in_the_chain() {
    for_each_seed(|mut rng| async move {
        let (carol, mut carol_cgka, updates) = carol_added_after_three_updates(&mut rng).await;

        let (_, op) = rotate(&mut carol_cgka, &carol.signer, &mut rng).await;

        let wrapped: Vec<_> = predecessor_secrets(&op)
            .iter()
            .map(|entry| entry.update_op_hash)
            .collect();
        assert_eq!(
            wrapped,
            vec![updates[2].0],
            "the earlier updates are already in the chain, so only the nearest one is wrapped"
        );
    });
}

/// A single member's replica after two updates, which has lost the second's
/// secret, so the first is unchained again. Returns the group and both updates'
/// hashes. The second update is the head.
async fn missing_the_second_secret(
    rng: &mut StdRng,
) -> (
    Group<NoImplicitRemoves>,
    Digest<CgkaOperation>,
    Digest<CgkaOperation>,
) {
    let mut group = Group::new(1, rng).await;
    let first = group.rotate(0, rng).await.digest();
    let second = group.rotate(0, rng).await.digest();
    let cgka = &mut group.replicas[0];
    cgka.root_secrets.remove(&second);
    cgka.unchained_updates.insert(first);
    assert_chain_bookkeeping(cgka, "precondition: only the second update wraps the first");
    (group, first, second)
}

#[test]
fn a_rebuilt_secret_chains_the_updates_its_entries_contain() {
    for_each_seed(|mut rng| async move {
        let (mut group, _, second) = missing_the_second_secret(&mut rng).await;
        let cgka = &mut group.replicas[0];

        cgka.rebuild_root_secret(&second)
            .expect("the author's own update can be rebuilt");

        assert_chain_bookkeeping(cgka, "after rebuilding the second update's secret");
    });
}

#[test]
fn a_replayed_secret_chains_the_updates_its_entries_contain() {
    for_each_seed(|mut rng| async move {
        let (mut group, first, _) = missing_the_second_secret(&mut rng).await;
        let cgka = &mut group.replicas[0];
        let fork = cgka.fork();

        cgka.merge(fork);

        assert!(
            !cgka.unchained_updates.contains(&first),
            "the replay recorded the head, whose entries chain the first"
        );
        assert_chain_bookkeeping(cgka, "after the replay");
    });
}