beekem 0.8.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
use crate::{
    cgka::{Cgka, ImplicitRemovesProtocol, NoImplicitRemoves},
    error::CgkaError,
    id::{MemberId, TreeId},
    keys::ShareKeyMap,
    operation::{CgkaOperation, CitationId},
    pcs_key::PcsKey,
    root_secrets::VerifiedRootSecret,
    transact::{Fork, Merge},
};
use alloc::{
    collections::{BTreeMap, BTreeSet},
    format,
    string::{String, ToString},
    sync::Arc,
    vec::Vec,
};
use future_form::Local;
use keyhive_crypto::{
    digest::Digest,
    share_key::{ShareKey, ShareSecretKey},
    signer::memory::MemorySigner,
    verified::Verified,
};
use rand::rngs::StdRng;

pub const NO_CITATIONS: BTreeSet<CitationId> = BTreeSet::new();

/// A member of a test group, holding everything needed to act as one.
pub struct Member {
    pub id: MemberId,
    pub signer: MemorySigner,
    pub pk: ShareKey,
    pub sk: ShareSecretKey,
}

/// A new member, with a fresh signer and a fresh prekey.
pub fn member(rng: &mut StdRng) -> Member {
    let signer = MemorySigner::generate(rng);
    let id = MemberId::from(&signer.0);
    let sk = ShareSecretKey::generate(rng);
    let pk = sk.share_key();
    Member { id, signer, pk, sk }
}

/// One replica of a tree per member, with delivery between them under the
/// test's control.
pub struct Group<M> {
    pub members: Vec<Member>,
    pub replicas: Vec<Cgka<M>>,
    /// Short names for readable failures.
    pub names: BTreeMap<MemberId, String>,
    doc_id: TreeId,
    /// Every operation synced so far, in the order it was synced, so a member
    /// added part way through can be given a replica of their own.
    log: Vec<Arc<Verified<CgkaOperation>>>,
    logged: BTreeSet<Digest<CgkaOperation>>,
    /// The implicit removes protocol every replica uses.
    implicit_removes_protocol: M,
}

impl Group<NoImplicitRemoves> {
    /// `n` members, each with a replica that has every add applied.
    pub async fn new(n: usize, rng: &mut StdRng) -> Self {
        let doc_signer = MemorySigner::generate(rng);
        let doc_id = TreeId::from(&doc_signer.0);
        let members: Vec<Member> = (0..n).map(|_| member(rng)).collect();

        let replicas = members
            .iter()
            .map(|m| {
                let mut sks = ShareKeyMap::new();
                sks.insert(m.pk, m.sk.clone());
                Cgka::new(doc_id, m.id, sks, NoImplicitRemoves)
            })
            .collect();

        let names = members
            .iter()
            .enumerate()
            .map(|(i, m)| (m.id, name_for(i)))
            .collect();
        let mut group = Group {
            members,
            replicas,
            names,
            doc_id,
            log: Vec::new(),
            logged: BTreeSet::new(),
            implicit_removes_protocol: NoImplicitRemoves,
        };
        // Every tree starts empty, so member 0 places itself before the rest.
        for i in 0..n {
            let op = group.add(0, group.members[i].id, group.members[i].pk).await;
            group.broadcast(&op);
        }
        group
    }
}

impl<M: ImplicitRemovesProtocol> Group<M> {
    /// This group, with `protocol` given to every replica and every replica
    /// made later.
    pub fn with_implicit_removes_protocol<P: ImplicitRemovesProtocol>(
        self,
        protocol: P,
    ) -> Group<P> {
        let Group {
            members,
            replicas,
            names,
            doc_id,
            log,
            logged,
            implicit_removes_protocol: _,
        } = self;
        Group {
            members,
            replicas: replicas
                .into_iter()
                .map(|replica| replica.with_implicit_removes_protocol(protocol.clone()))
                .collect(),
            names,
            doc_id,
            log,
            logged,
            implicit_removes_protocol: protocol,
        }
    }

    /// Create a removal, citing `citations`, on `author`'s replica without
    /// delivering it. Doesn't list specific removal targets.
    pub async fn remove_by_citations(
        &mut self,
        author: usize,
        citations: BTreeSet<CitationId>,
    ) -> Arc<Verified<CgkaOperation>> {
        let signer = &self.members[author].signer;
        let op = self.replicas[author]
            .remove_by_citations::<Local, _>(citations, signer)
            .await
            .expect("creating the removal succeeds");
        Arc::new(op)
    }

    /// Create an add on `author`'s replica without delivering it.
    pub async fn add(
        &mut self,
        author: usize,
        id: MemberId,
        pk: ShareKey,
    ) -> Arc<Verified<CgkaOperation>> {
        self.try_add(author, id, pk)
            .await
            .expect("the added member is new")
    }

    /// Create an add on `author`'s replica without delivering it or `None` if
    /// `author`'s history already places `id`.
    pub async fn try_add(
        &mut self,
        author: usize,
        id: MemberId,
        pk: ShareKey,
    ) -> Option<Arc<Verified<CgkaOperation>>> {
        let signer = &self.members[author].signer;
        self.replicas[author]
            .add::<Local, _>(id, pk, None, NO_CITATIONS, signer)
            .await
            .expect("creating the add succeeds")
            .map(Arc::new)
    }

    /// Create a removal on `author`'s replica without delivering it.
    pub async fn remove(
        &mut self,
        author: usize,
        target: MemberId,
    ) -> Arc<Verified<CgkaOperation>> {
        self.try_remove(author, target)
            .await
            .expect("the removed member is present")
    }

    /// Create a removal on `author`'s replica without delivering it or `None`
    /// if `author`'s history already removes `target`.
    pub async fn try_remove(
        &mut self,
        author: usize,
        target: MemberId,
    ) -> Option<Arc<Verified<CgkaOperation>>> {
        let signer = &self.members[author].signer;
        self.replicas[author]
            .remove::<Local, _>(target, NO_CITATIONS, signer)
            .await
            .expect("creating the removal succeeds")
            .map(Arc::new)
    }

    /// Create a rotation on `author`'s replica without delivering it.
    pub async fn rotate(
        &mut self,
        author: usize,
        rng: &mut StdRng,
    ) -> Arc<Verified<CgkaOperation>> {
        self.try_rotate(author, rng)
            .await
            .expect("the rotating member is present")
    }

    /// Create a rotation on `author`'s replica without delivering it or `None`
    /// if `author` is no longer in the tree.
    pub async fn try_rotate(
        &mut self,
        author: usize,
        rng: &mut StdRng,
    ) -> Option<Arc<Verified<CgkaOperation>>> {
        let sk = ShareSecretKey::generate(rng);
        let pk = sk.share_key();
        let signer = &self.members[author].signer;
        match self.replicas[author]
            .update::<Local, _, StdRng>(pk, sk, signer, rng)
            .await
        {
            Ok((_pcs_key, op, _)) => Some(Arc::new(op)),
            Err(CgkaError::IdentifierNotFound) | Err(CgkaError::NoMembers) => None,
            Err(e) => panic!("creating the rotation failed: {e:?}"),
        }
    }

    /// Rotate and deliver everywhere, causing every replica to play pending
    /// operations.
    pub async fn settle(&mut self, author: usize, rng: &mut StdRng) {
        let op = self.rotate(author, rng).await;
        self.broadcast(&op);
    }

    /// Deliver `op` to the replicas named by `to`, recording it in the log.
    pub fn deliver(&mut self, op: &Arc<Verified<CgkaOperation>>, to: &[usize]) {
        let could_not_apply = self.try_deliver(op, to);
        assert!(
            could_not_apply.is_empty(),
            "operations are delivered in causal order, but replicas {could_not_apply:?} could not apply one"
        );
    }

    /// Deliver `op` to the replicas named by `to`, recording it in the log, and
    /// report which of them could not apply it.
    pub fn try_deliver(&mut self, op: &Arc<Verified<CgkaOperation>>, to: &[usize]) -> Vec<usize> {
        let could_not_apply: Vec<usize> = to
            .iter()
            .copied()
            .filter(|&i| {
                self.replicas[i]
                    .merge_concurrent_operation(op.clone())
                    .is_err()
            })
            .collect();
        if could_not_apply.len() < to.len() && self.logged.insert(op.digest()) {
            self.log.push(op.clone());
        }
        could_not_apply
    }

    /// Deliver `op` to every replica.
    pub fn broadcast(&mut self, op: &Arc<Verified<CgkaOperation>>) {
        self.deliver(op, &Vec::from_iter(0..self.replicas.len()));
    }

    /// Member `i`'s id.
    pub fn id(&self, i: usize) -> MemberId {
        self.members[i].id
    }

    fn label(&self, id: &MemberId) -> String {
        self.names
            .get(id)
            .cloned()
            .unwrap_or_else(|| format!("{id:?}"))
    }

    /// The tree members on `replica`, by ascending leaf index.
    fn tree_members(&self, replica: usize) -> Vec<(u32, MemberId)> {
        let tree = &self.replicas[replica].tree;
        let mut tree_members: Vec<(u32, MemberId)> = tree
            .member_ids()
            .map(|id| {
                let idx = tree.leaf_index_for_id(id).expect("a member has a leaf");
                (idx.u32(), id)
            })
            .collect();
        tree_members.sort();
        tree_members
    }

    /// A string for a failure message, like `"a@0 b@1 d@2"`.
    fn tree_members_string(&self, tree_members: &[(u32, MemberId)]) -> String {
        tree_members
            .iter()
            .map(|(idx, id)| format!("{}@{idx}", self.label(id)))
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// Every replica's tree satisfies its own invariants and they all agree. And
    /// each replica's chain bookkeeping matches its graph.
    pub fn check(&self, context: &str) {
        for (i, replica) in self.replicas.iter().enumerate() {
            assert_chain_bookkeeping(replica, &format!("{context}: replica {i}"));
            let violations = replica.tree.invariant_violations();
            assert!(
                violations.is_empty(),
                "{context}: replica {i}'s tree is corrupt. {}",
                violations.join(". ")
            );
        }
        for i in 1..self.replicas.len() {
            if self.replicas[i].tree != self.replicas[0].tree {
                let (theirs, ours) = (self.tree_members(i), self.tree_members(0));
                let detail = if theirs == ours {
                    format!(
                        "they place everyone the same in the tree, at {}, so they differ \
                         somewhere other than the placements",
                        self.tree_members_string(&ours)
                    )
                } else {
                    format!(
                        "replica 0 places {}, replica {i} places {}",
                        self.tree_members_string(&ours),
                        self.tree_members_string(&theirs)
                    )
                };
                panic!("{context}: replicas diverged. {detail}");
            }
        }
    }

    /// Every replica has the tree a full replay of its graph builds.
    pub fn assert_trees_match_replay(&self, context: &str) {
        for (i, replica) in self.replicas.iter().enumerate() {
            let mut replayed = replica.clone();
            // Merging always replays the merged graph.
            let fork = replayed.fork();
            replayed.merge(fork);
            assert!(
                replayed.tree == replica.tree,
                "{context}: replica {i}'s tree differs from a replay of its graph"
            );
        }
    }

    /// Replica 0 places exactly `expected`.
    pub fn assert_members(&self, context: &str, expected: &[&str]) {
        let mut want: Vec<String> = expected.iter().map(|name| name.to_string()).collect();
        want.sort();
        let mut got: Vec<String> = self.replicas[0]
            .tree
            .member_ids()
            .map(|id| self.label(&id))
            .collect();
        got.sort();
        assert_eq!(
            got,
            want,
            "{context}: wrong membership, placed as {}",
            self.tree_members_string(&self.tree_members(0))
        );
    }

    /// Every replica whose owner is still a member derives the same root key, and
    /// no replica whose owner was removed derives one.
    pub fn assert_key_agreement(&mut self, context: &str) {
        let mut agreed: Option<PcsKey> = None;
        for i in 0..self.replicas.len() {
            let owner = self.replicas[i].owner_id;
            let is_member = self.replicas[i].tree.contains_id(&owner);
            let key = self.replicas[i].decrypt_current_group_secret();
            let name = self.label(&owner);
            if !is_member {
                assert!(
                    key.is_err(),
                    "{context}: {name} was removed but still derives the root key"
                );
                continue;
            }
            let key = key.unwrap_or_else(|e| {
                panic!("{context}: {name} is still a member but cannot derive the root key. {e:?}")
            });
            match agreed {
                None => agreed = Some(key),
                Some(ref first) => assert!(
                    key == *first,
                    "{context}: {name} derived a different root key"
                ),
            }
        }
        assert!(
            agreed.is_some(),
            "{context}: no replica was left to derive a key"
        );
    }

    /// A replica owned by `id`, applying every operation delivered so far.
    fn replica_for(&self, id: MemberId, sks: ShareKeyMap) -> Cgka<M> {
        let mut replica = Cgka::new(self.doc_id, id, sks, self.implicit_removes_protocol.clone());
        for op in &self.log {
            replica
                .merge_concurrent_operation(op.clone())
                .expect("the log is in causal order");
        }
        replica
    }

    /// `id`, using `sks`, derives the same root key as the rest of the group.
    pub fn assert_reads_group_key(
        &mut self,
        id: MemberId,
        sks: ShareKeyMap,
        context: &str,
        on_failure: &str,
    ) {
        let mut replica = self.replica_for(id, sks);
        let key = replica
            .decrypt_current_group_secret()
            .unwrap_or_else(|e| panic!("{context}: {on_failure} {e:?}"));
        let group_key = self.replicas[0]
            .decrypt_current_group_secret()
            .expect("replica 0's owner is a member");
        assert!(
            key == group_key,
            "{context}: {} derived a different root key from the rest of the group",
            self.label(&id)
        );
    }
}

/// A one-letter name for member `i`. Panics for `i` above 7.
pub fn name_for(i: usize) -> String {
    ["a", "b", "c", "d", "e", "f", "g", "h"][i].to_string()
}

/// How many seeds [`for_each_seed`] runs a test on.
#[cfg(test)]
const SEED_ITERATIONS: usize = 32;

/// Run `test` with a [`StdRng`] seeded from each of [`SEED_ITERATIONS`] generated seeds.
///
/// The keys a test generates determine its operation hashes and thus the order of
/// any set or map keyed by them. Varying the seed checks that the test passes
/// regardless of those orders.
#[cfg(test)]
pub(crate) fn for_each_seed<F: core::future::Future<Output = ()>>(
    test: impl Fn(StdRng) -> F + core::panic::RefUnwindSafe,
) {
    use rand::SeedableRng;

    let runtime = tokio::runtime::Builder::new_current_thread()
        .build()
        .expect("building a runtime succeeds");
    bolero::check!()
        .with_iterations(SEED_ITERATIONS)
        .with_generator(bolero::gen::<u64>())
        .cloned()
        .for_each(|seed| runtime.block_on(test(StdRng::seed_from_u64(seed))));
}

/// Every operation in the causal past of one whose predecessors are `predecessors`.
#[cfg(test)]
pub(crate) fn causal_past(
    graph: &crate::operation::CgkaOperationGraph,
    predecessors: &crate::predecessors::Predecessors,
) -> BTreeSet<Digest<CgkaOperation>> {
    let mut past = BTreeSet::new();
    let mut frontier: Vec<_> = predecessors.iter().copied().collect();
    while let Some(op_hash) = frontier.pop() {
        if past.insert(op_hash) {
            frontier.extend(graph.predecessors_for(&op_hash).into_iter().flatten());
        }
    }
    past
}

/// Assert that `cgka`'s chainable and unchained updates match what its graph
/// and recorded secrets imply: an update is chainable if a later update has it
/// as a nearest update ancestor and unchained unless a recorded update's entry
/// contains its verified root secret.
pub(crate) fn assert_chain_bookkeeping<M: ImplicitRemovesProtocol>(cgka: &Cgka<M>, context: &str) {
    let graph = &cgka.ops_graph;
    let updates: BTreeSet<_> = graph
        .cgka_ops
        .iter()
        .filter(|(_, op)| op.payload().is_update())
        .map(|(op_hash, _)| *op_hash)
        .collect();
    let chainable: BTreeSet<_> = updates
        .iter()
        .flat_map(|update| {
            let predecessors = graph.cgka_ops.get(update).unwrap().payload().predecessors();
            graph.nearest_update_ancestors(predecessors)
        })
        .collect();
    for update in &updates {
        assert_eq!(
            graph.is_chainable(update),
            chainable.contains(update),
            "{context}: the graph's latest updates are out of date"
        );
    }
    // An update is chained once some recorded update's entry for it contains
    // its verified root secret.
    let chained: BTreeSet<_> = cgka
        .root_secrets
        .iter()
        .flat_map(|(op_hash, secret)| cgka.decrypt_predecessor_secrets(op_hash, secret, |_| true))
        .filter(|(update, secret)| {
            VerifiedRootSecret::verify(graph, *update, secret.clone()).is_some()
        })
        .map(|(update, _)| update)
        .collect();
    let unchained: BTreeSet<_> = chainable.difference(&chained).copied().collect();
    assert_eq!(
        cgka.unchained_updates
            .iter()
            .copied()
            .collect::<BTreeSet<_>>(),
        unchained,
        "{context}: the unchained updates are out of date"
    );
}