use crate::{
cgka::NoImplicitRemoves,
encrypted::encrypt_secret,
error::CgkaError,
keys::ShareKeyMap,
operation::{CgkaChange, CgkaOperation},
secret_store::PathNode,
test_utils::Group,
tree::PathChange,
treemath::{InnerNodeIndex, LeafNodeIndex, TreeNodeIndex},
};
use alloc::{collections::BTreeMap, sync::Arc, vec::Vec};
use future_form::Local;
use keyhive_crypto::{share_key::ShareSecretKey, verified::Verified};
use rand::{rngs::StdRng, SeedableRng};
async fn forged_update(
group: &mut Group<NoImplicitRemoves>,
author: usize,
rng: &mut StdRng,
) -> Arc<Verified<CgkaOperation>> {
let doc_id = group.replicas[author].doc_id;
tampered_update(group, author, rng, |new_path, sks, rng| {
let encrypters: Vec<_> = new_path
.secret_stores()
.map(|(_, store)| store.encrypter_pk)
.collect();
for ((_, version), encrypter_pk) in new_path.path.iter_mut().zip(encrypters) {
let encrypter_sk = sks
.get(&encrypter_pk)
.expect("the author has its path secrets");
let incorrect_secret = ShareSecretKey::generate(rng);
for encrypted in version.sk.values_mut() {
*encrypted = encrypt_secret(
doc_id,
&incorrect_secret,
encrypter_sk,
&encrypted.paired_pk,
)
.expect("encryption succeeds");
}
}
})
.await
}
async fn tampered_update(
group: &mut Group<NoImplicitRemoves>,
author: usize,
rng: &mut StdRng,
tamper: impl FnOnce(&mut PathChange, &ShareKeyMap, &mut StdRng),
) -> Arc<Verified<CgkaOperation>> {
let mut copy = group.replicas[author].clone();
let sk = ShareSecretKey::generate(rng);
let signer = &group.members[author].signer;
let (_, op, _) = copy
.update::<Local, _, _>(sk.share_key(), sk, signer, rng)
.await
.expect("the author can update");
group.replicas[author].owner_sks.extend(©.owner_sks);
let mut payload = op.payload().clone();
let CgkaChange::Update { new_path, .. } = &mut payload.change else {
unreachable!("an update")
};
tamper(new_path, ©.owner_sks, rng);
Arc::new(
Verified::sign::<Local, _>(&payload, signer)
.await
.expect("signing succeeds"),
)
}
fn drop_entry(path: &mut PathChange, at: usize, node: TreeNodeIndex) {
path.path[at]
.1
.sk
.remove(&node)
.expect("the path node has an entry for that node");
}
#[tokio::test]
async fn a_member_who_receives_forged_path_secrets_still_agrees_on_later_keys() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0001);
let mut group = Group::new(4, &mut rng).await;
group.settle(0, &mut rng).await;
let forged = forged_update(&mut group, 0, &mut rng).await;
group.broadcast(&forged);
for replica in &mut group.replicas[1..] {
let root = replica.decrypt_current_group_secret();
assert!(
matches!(root, Err(CgkaError::PathSecretMismatch)),
"{root:?}"
);
}
group.settle(2, &mut rng).await;
let signer = group.members[1].signer.clone();
let (_, _, rotation) = group.replicas[1]
.group_secret_for_write::<Local, _, _>(&signer, &mut rng)
.await
.expect("a member who cannot derive the root secret still writes");
let (op, _) = rotation.expect("writing rotated");
group.broadcast(&Arc::new(op));
group.assert_key_agreement("after a forged update, an honest update and write");
}
#[tokio::test]
async fn a_member_an_update_leaves_out_reads_the_next_update_by_another_member() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0002);
let mut group = Group::new(4, &mut rng).await;
group.settle(0, &mut rng).await;
let b_leaf = TreeNodeIndex::from(LeafNodeIndex::new(1));
let leaves_out_b = tampered_update(&mut group, 0, &mut rng, |path, _, _| {
drop_entry(path, 0, b_leaf)
})
.await;
group.broadcast(&leaves_out_b);
let by_c = group.rotate(2, &mut rng).await;
group.broadcast(&by_c);
group.assert_trees_match_replay("after an update leaving b out");
let root = group.replicas[2]
.root_secrets
.get(&by_c.digest())
.expect("an updater records the root secret of its own update");
assert_eq!(
group.replicas[1]
.group_secret_from_hashes(&root.digest(), &by_c.digest())
.ok(),
Some(root),
"b cannot derive the root secret of c's update"
);
}
#[tokio::test]
async fn an_update_leaving_a_member_out_converges_with_a_concurrent_one_in_either_order() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0005);
let mut group = Group::new(4, &mut rng).await;
group.settle(0, &mut rng).await;
let d_leaf = TreeNodeIndex::from(LeafNodeIndex::new(3));
let leaves_out_d = tampered_update(&mut group, 0, &mut rng, |path, _, _| {
drop_entry(path, 1, d_leaf)
})
.await;
let by_c = group.rotate(2, &mut rng).await;
group.deliver(&leaves_out_d, &[0, 1]);
group.deliver(&by_c, &[0, 1, 3]);
group.deliver(&leaves_out_d, &[2, 3]);
for replica in &mut group.replicas {
replica
.replay_if_pending()
.expect("no membership is unknown");
}
group.check("after an update leaving d out and a concurrent one");
group.assert_trees_match_replay("after an update leaving d out and a concurrent one");
}
#[tokio::test]
async fn an_update_whose_path_is_cut_short_converges_with_concurrent_and_later_updates() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0008);
let mut group = Group::new(3, &mut rng).await;
group.settle(0, &mut rng).await;
let cut_short = tampered_update(&mut group, 0, &mut rng, |path, _, _| {
path.path.pop();
})
.await;
let by_c = group.rotate(2, &mut rng).await;
group.deliver(&cut_short, &[1]);
let by_b = group.rotate(1, &mut rng).await;
for op in [&cut_short, &by_c, &by_b] {
group.broadcast(op);
}
for replica in &mut group.replicas {
replica
.replay_if_pending()
.expect("no membership is unknown");
}
group.check("after an update cut short, a concurrent update and a later one");
group.assert_trees_match_replay(
"after an update cut short, a concurrent update and a later one",
);
}
#[tokio::test]
async fn an_update_cut_short_keeping_its_leaf_key_converges_with_a_concurrent_one() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0011);
let mut group = Group::new(2, &mut rng).await;
group.settle(0, &mut rng).await;
let leaf_pk = group.replicas[0].owner_leaf_key().expect("a member");
let cut_short = tampered_update(&mut group, 0, &mut rng, |path, _, _| {
path.path.pop();
path.leaf_pk = leaf_pk;
})
.await;
let by_b = group.rotate(1, &mut rng).await;
assert!(
cut_short.digest() < by_b.digest(),
"the seed no longer makes a replay apply the update cut short first"
);
group.deliver(&cut_short, &[0]);
group.broadcast(&by_b);
group.broadcast(&cut_short);
for replica in &mut group.replicas {
replica
.replay_if_pending()
.expect("no membership is unknown");
}
group.check("after an update cut short and a concurrent one");
group.assert_trees_match_replay("after an update cut short and a concurrent one");
}
async fn honest_path(rng: &mut StdRng) -> PathChange {
honest_path_of(0, rng).await
}
async fn honest_path_of(author: usize, rng: &mut StdRng) -> PathChange {
let mut group = Group::<NoImplicitRemoves>::new(4, rng).await;
group.settle(0, rng).await;
let op = group.rotate(author, rng).await;
let CgkaChange::Update { new_path, .. } = &op.payload().change else {
unreachable!("a rotation is an update")
};
(**new_path).clone()
}
#[tokio::test]
async fn a_path_node_without_an_entry_for_its_encrypting_child_is_malformed() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0003);
let mut path = honest_path(&mut rng).await;
let first = TreeNodeIndex::from(InnerNodeIndex::new(path.path[0].0));
path.path[1]
.1
.sk
.remove(&first)
.expect("a node has an entry for the child that encrypted it");
assert!(!path.is_well_formed());
}
#[tokio::test]
async fn a_path_node_whose_key_repeats_another_new_key_is_malformed() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0008);
let mut path = honest_path(&mut rng).await;
let mut repeats_leaf = path.clone();
repeats_leaf.path[1].1.pk = path.leaf_pk;
path.path[1].1.pk = path.path[0].1.pk;
assert!(!repeats_leaf.is_well_formed());
assert!(!path.is_well_formed());
}
#[tokio::test]
async fn a_path_with_an_index_of_2_pow_31_or_more_is_malformed() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0005);
let honest = honest_path(&mut rng).await;
let mut leaf_beyond = honest.clone();
leaf_beyond.leaf_idx += 1 << 31;
let mut node_beyond = honest.clone();
node_beyond.path[0].0 += 1 << 31;
let mut root_beyond = honest.clone();
root_beyond.path[1].0 += 1 << 31;
let mut leaf_beyond_without_nodes = leaf_beyond.clone();
leaf_beyond_without_nodes.path.clear();
assert!(!leaf_beyond.is_well_formed());
assert!(!node_beyond.is_well_formed());
assert!(!root_beyond.is_well_formed());
assert!(!leaf_beyond_without_nodes.is_well_formed());
}
#[tokio::test]
async fn a_path_that_is_not_a_chain_from_the_leaf_to_a_root_is_malformed() {
let mut rng = StdRng::seed_from_u64(0x9a7b_0009);
let honest = honest_path(&mut rng).await;
let mut empty = honest.clone();
empty.path.clear();
let mut skips_a_node = honest.clone();
skips_a_node.path.truncate(1);
skips_a_node.path[0].0 = honest.path[1].0;
let mut stops_below_a_root = honest_path_of(2, &mut rng).await;
stops_below_a_root.path.truncate(1);
assert!(!empty.is_well_formed());
assert!(!skips_a_node.is_well_formed());
assert!(!stops_below_a_root.is_well_formed());
}
async fn chain_from_leaf_zero(len: u32, rng: &mut StdRng) -> PathChange {
let mut path = honest_path(rng).await;
let leaf = TreeNodeIndex::from(LeafNodeIndex::new(path.leaf_idx));
let entry = path.path[0].1.sk[&leaf].clone();
let mut child = leaf;
path.path = (0..len)
.map(|j| {
let idx = (1u32 << j) - 1;
let pk = ShareSecretKey::generate(rng).share_key();
let node = PathNode {
pk,
sk: BTreeMap::from([(child, entry.clone())]),
};
child = TreeNodeIndex::from(InnerNodeIndex::new(idx));
(idx, node)
})
.collect();
path
}
#[tokio::test]
async fn a_path_may_be_as_long_as_the_tallest_tree_and_no_longer() {
let mut rng = StdRng::seed_from_u64(0x9a7b_000a);
assert!(chain_from_leaf_zero(31, &mut rng).await.is_well_formed());
assert!(!chain_from_leaf_zero(32, &mut rng).await.is_well_formed());
}