use super::{flag_unpairing, load_member_keys};
use crate::derec_message::apply_trace_id;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::primitives::unpairing::request;
use crate::protocol::context::Local;
use crate::protocol::stores::{StoreSet, Stores};
use crate::protocol::types::{
ChannelQuery, ChannelRecord, ChannelStatus, HelperFilter, ReplicaFilter, ReplicaMember,
ReplicaRole,
};
use crate::protocol::{
DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecShareStore, DeRecTransport,
DeRecUserSecretStore, SecretKind,
};
use crate::types::{ChannelId, ReplicaId};
use crate::{Error, Result};
use derec_proto::{MessageBody, UnpairRequestMessage};
pub(in crate::protocol) async fn handle<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
target: u64,
inner: MessageBody,
) -> Result<Vec<DeRecEvent>> {
match inner {
MessageBody::UnpairRequest(request) => on_request(stores, local, &request, target).await,
_ => Err(Error::Invariant(
"replica identity on a message that is not an unpair request",
)),
}
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = trace_id, local.secret_id)))]
pub(in crate::protocol) async fn start<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
target: u64,
memo: Option<String>,
trace_id: u64,
) -> Result<Vec<DeRecEvent>> {
let secret_id = local.secret_id;
let own = local.replica_id.ok_or(Error::ReplicaIdNotConfigured)?;
let target = ReplicaId::try_from(target)?;
let roster = stores
.channels
.replicas_matching(secret_id, ReplicaFilter::default())
.await?;
let member = roster
.iter()
.find(|m| m.replica_id == target)
.ok_or(Error::InvalidInput("no such member in this replica group"))?
.clone();
let successor = if member.role == ReplicaRole::Source {
roster
.iter()
.find(|m| m.replica_id != target && m.status == ChannelStatus::Paired)
.cloned()
} else {
None
};
let peers: Vec<ReplicaMember> = roster
.iter()
.filter(|m| m.replica_id.0 != own)
.cloned()
.collect();
let keys = load_member_keys(stores, local, &peers).await?;
let memo = memo.unwrap_or_default();
let mut notified = Vec::new();
for peer in &peers {
let key = &keys[&peer.channel_id];
let request = request::produce(peer.channel_id, &memo, key, &[], Some(target.0))?;
let envelope = apply_trace_id(&request.envelope, trace_id)?;
if stores
.transport
.send(&peer.transports, envelope)
.await
.is_ok()
{
notified.push(peer.replica_id);
}
}
let mut events = Vec::new();
if target.0 == own {
flag_unpairing(stores, local, &member).await?;
} else {
drop_member(stores, local, &member).await?;
events.push(DeRecEvent::ReplicaRemoved {
replica_id: target.0,
});
}
if let Some(successor) = successor {
stores
.channels
.save(
secret_id,
ChannelRecord::Replica(ReplicaMember {
role: ReplicaRole::Source,
..successor.clone()
}),
)
.await?;
events.push(DeRecEvent::ReplicaSourceChanged {
replica_id: successor.replica_id.0,
});
}
#[cfg(feature = "logging")]
tracing::info!(
secret_id,
target = target.0,
voluntary = target.0 == own,
notified = notified.len(),
"replica removal announced"
);
Ok(events)
}
pub(in crate::protocol) enum RemovalOutcome {
Nothing,
Removed(Vec<u64>),
SelfRemoved,
}
pub(in crate::protocol) async fn reconcile<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
roster_ids: &[u64],
) -> Result<RemovalOutcome> {
let stored = stores
.channels
.replicas_matching(
local.secret_id,
ReplicaFilter {
status: vec![ChannelStatus::Unpairing],
..Default::default()
},
)
.await?;
let mut removed = Vec::new();
let mut self_removed = false;
for member in stored.iter() {
if roster_ids.contains(&member.replica_id.0) {
continue;
}
if Some(member.replica_id.0) == local.replica_id {
self_removed = true;
continue;
}
if let Some(handover) = member.handover_channel {
let _ = stores
.secrets
.remove(local.secret_id, handover, SecretKind::SharedKey)
.await;
}
stores
.channels
.remove(
local.secret_id,
ChannelQuery::Replica {
channel_id: member.channel_id,
replica_id: member.replica_id,
},
)
.await?;
removed.push(member.replica_id.0);
}
if self_removed {
return Ok(RemovalOutcome::SelfRemoved);
}
if removed.is_empty() {
Ok(RemovalOutcome::Nothing)
} else {
Ok(RemovalOutcome::Removed(removed))
}
}
pub(in crate::protocol) async fn tear_down<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
) -> Result<()> {
let secret_id = local.secret_id;
for helper in stores
.channels
.helpers_matching(secret_id, HelperFilter::default())
.await?
{
drop_channel(
stores,
local,
helper.channel_id,
ChannelQuery::Helper {
channel_id: helper.channel_id,
},
)
.await?;
}
for member in stores
.channels
.replicas_matching(secret_id, ReplicaFilter::default())
.await?
{
if let Some(handover) = member.handover_channel {
let _ = stores
.secrets
.remove(secret_id, handover, SecretKind::SharedKey)
.await;
}
drop_channel(
stores,
local,
member.channel_id,
ChannelQuery::Replica {
channel_id: member.channel_id,
replica_id: member.replica_id,
},
)
.await?;
}
stores.user_secrets.remove(secret_id).await?;
Ok(())
}
async fn drop_channel<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
channel_id: ChannelId,
query: ChannelQuery,
) -> Result<()> {
let secret_id = local.secret_id;
let _ = stores.shares.remove_channel(secret_id, channel_id).await;
for kind in [
SecretKind::SharedKey,
SecretKind::PairingSecret,
SecretKind::PairingContact,
] {
let _ = stores.secrets.remove(secret_id, channel_id, kind).await;
}
stores.channels.remove(secret_id, query).await?;
Ok(())
}
async fn on_request<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
request: &UnpairRequestMessage,
target: u64,
) -> Result<Vec<DeRecEvent>> {
let _ = request;
let target = ReplicaId::try_from(target)?;
let member = stores
.channels
.replicas_matching(
local.secret_id,
ReplicaFilter {
ids: vec![target],
..Default::default()
},
)
.await?
.into_iter()
.find(|m| m.replica_id == target)
.ok_or(Error::InvalidInput(
"unpair names a member that is not in the group",
))?;
if Some(target.0) == local.replica_id {
let version = stores
.user_secrets
.load_latest(local.secret_id)
.await?
.map_or(0, |held| held.version);
tear_down(stores, local).await?;
#[cfg(feature = "logging")]
tracing::info!(
version,
"told to leave the replica group; partition dropped"
);
return Ok(vec![DeRecEvent::SelfRemovedFromGroup { version }]);
}
flag_unpairing(stores, local, &member).await?;
Ok(vec![DeRecEvent::NoOp])
}
async fn drop_member<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
member: &ReplicaMember,
) -> Result<()> {
let secret_id = local.secret_id;
stores
.channels
.remove(
secret_id,
ChannelQuery::Replica {
channel_id: member.channel_id,
replica_id: member.replica_id,
},
)
.await?;
let remaining = stores
.channels
.replicas_matching(secret_id, ReplicaFilter::default())
.await?;
for channel_id in [Some(member.channel_id), member.handover_channel]
.into_iter()
.flatten()
{
if !remaining.iter().any(|m| m.channel_id == channel_id) {
let _ = stores
.secrets
.remove(secret_id, channel_id, SecretKind::SharedKey)
.await;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::derec_message::extract_inner_message;
use crate::protocol::tests::{InMemChannelStore, InMemSecretStore, StoreRig, run_async};
use crate::protocol::tests::{LocalFixture, NoopTransport};
use crate::protocol::types::{
HelperChannel, HelperFilter, ReplicaFilter, SecretValue, UserSecrets,
};
use crate::protocol::{DeRecSecretStore, DeRecUserSecretStore};
use crate::types::SharedKey;
use derec_proto::{DeRecMessage, Protocol, SenderKind, TransportProtocol};
use prost::Message as _;
use std::collections::HashMap;
const SECRET_ID: u64 = 0xDE9A27;
const GROUP: ChannelId = ChannelId(5001);
fn endpoint(uri: &str) -> TransportProtocol {
TransportProtocol {
uri: uri.to_owned(),
protocol: Protocol::Https as i32,
}
}
async fn seed_member(
channels: &mut InMemChannelStore,
id: u64,
role: ReplicaRole,
status: ChannelStatus,
) {
channels
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: GROUP,
replica_id: ReplicaId(id),
transports: vec![endpoint("https://peer.example")],
communication_info: HashMap::new(),
role,
status,
created_at: 0,
handover_channel: None,
}),
)
.await
.expect("seed member");
}
const TRACE_ID: u64 = 0x7ACE;
#[test]
fn absence_alone_removes_nothing() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1001);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
let outcome = super::reconcile(&mut rig.stores(), &lf.local(), &[1001])
.await
.expect("reconcile");
assert!(matches!(outcome, RemovalOutcome::Nothing));
assert_eq!(
rig.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.len(),
2,
"a member never told to leave survives being omitted"
);
});
}
#[test]
fn being_flagged_alone_removes_nothing() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1001);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
let outcome = super::reconcile(&mut rig.stores(), &lf.local(), &[1001, 1002])
.await
.expect("reconcile");
assert!(matches!(outcome, RemovalOutcome::Nothing));
assert_eq!(
rig.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.len(),
2,
"a flagged member still in the roster keeps its row"
);
});
}
#[test]
fn both_halves_remove_the_row_and_nothing_else() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1001);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
rig.channels
.save(
SECRET_ID,
ChannelRecord::Helper(HelperChannel {
channel_id: ChannelId(9001),
transports: vec![endpoint("https://helper.example")],
communication_info: HashMap::new(),
peer_role: SenderKind::Helper,
status: ChannelStatus::Paired,
created_at: 0,
weight: 1,
}),
)
.await
.expect("seed helper");
let outcome = super::reconcile(&mut rig.stores(), &lf.local(), &[1001])
.await
.expect("reconcile");
assert!(matches!(outcome, RemovalOutcome::Removed(ref ids) if ids == &[1002]));
let roster = rig
.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster");
assert_eq!(roster.len(), 1, "only the departing row goes");
assert_eq!(
roster[0].channel_id, GROUP,
"the shared group channel is untouched"
);
assert_eq!(
rig.channels
.helpers(SECRET_ID, HelperFilter::default())
.await
.expect("helpers")
.len(),
1,
"a remaining member keeps every helper channel"
);
});
}
#[test]
fn a_departing_device_defers_to_its_caller() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1002);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
let outcome = super::reconcile(&mut rig.stores(), &lf.local(), &[1001])
.await
.expect("reconcile");
assert!(
matches!(outcome, RemovalOutcome::SelfRemoved),
"the device being removed is reported, not silently torn down"
);
assert_eq!(
rig.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.len(),
2,
"nothing is dropped before the acknowledgement is sent"
);
});
}
#[test]
fn tear_down_drops_the_whole_partition() {
run_async(async {
let lf = LocalFixture::new(SECRET_ID);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
rig.channels
.save(
SECRET_ID,
ChannelRecord::Helper(HelperChannel {
channel_id: ChannelId(9001),
transports: vec![endpoint("https://helper.example")],
communication_info: HashMap::new(),
peer_role: SenderKind::Helper,
status: ChannelStatus::Paired,
created_at: 0,
weight: 1,
}),
)
.await
.expect("seed helper");
rig.secrets
.save(SECRET_ID, GROUP, SecretValue::SharedKey([0x33; 32]))
.await
.expect("seed key");
rig.user_secrets
.save_latest(
SECRET_ID,
UserSecrets {
version: 4,
secrets: Vec::new(),
description: None,
author_replica_id: None,
threshold: None,
},
)
.await
.expect("seed snapshot");
super::tear_down(&mut rig.stores(), &lf.local())
.await
.expect("tear down");
assert!(
rig.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.is_empty()
);
assert!(
rig.channels
.helpers(SECRET_ID, HelperFilter::default())
.await
.expect("helpers")
.is_empty()
);
assert!(
rig.secrets
.load(SECRET_ID, GROUP, SecretKind::SharedKey)
.await
.expect("load")
.is_none(),
"the group key goes with everything else"
);
assert!(
rig.user_secrets
.load_latest(SECRET_ID)
.await
.expect("load")
.is_none(),
"a departing device keeps no copy of the secret"
);
});
}
async fn seed_group_key(secrets: &mut InMemSecretStore) {
secrets
.save(SECRET_ID, GROUP, SecretValue::SharedKey([7u8; 32]))
.await
.expect("seed group key");
}
async fn role_of(channels: &InMemChannelStore, id: u64) -> ReplicaRole {
channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.into_iter()
.find(|m| m.replica_id.0 == id)
.expect("member present")
.role
}
#[test]
fn removing_the_source_promotes_a_remaining_member() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1002);
let mut rig = StoreRig::with_transport(NoopTransport);
seed_group_key(&mut rig.secrets).await;
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
let events = super::start(&mut rig.stores(), &lf.local(), 1001, None, TRACE_ID)
.await
.expect("removing the source succeeds once a successor is chosen");
assert!(
events.iter().any(|e| matches!(
e,
DeRecEvent::ReplicaSourceChanged { replica_id } if *replica_id == 1002
)),
"the chosen successor is reported to the application"
);
assert_eq!(role_of(&rig.channels, 1002).await, ReplicaRole::Source);
assert!(
events.iter().any(|e| matches!(
e,
DeRecEvent::ReplicaRemoved { replica_id } if *replica_id == 1001
)),
"the departing source is removed at once"
);
assert!(
rig.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.iter()
.all(|m| m.replica_id.0 != 1001)
);
});
}
#[test]
fn a_departing_member_is_not_eligible_to_succeed() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1003);
let mut rig = StoreRig::with_transport(NoopTransport);
seed_group_key(&mut rig.secrets).await;
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
seed_member(
&mut rig.channels,
1003,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
super::start(&mut rig.stores(), &lf.local(), 1001, None, TRACE_ID)
.await
.expect("start");
assert_eq!(role_of(&rig.channels, 1003).await, ReplicaRole::Source);
assert_eq!(role_of(&rig.channels, 1002).await, ReplicaRole::Destination);
});
}
#[test]
fn an_unconfirmed_member_is_not_eligible_to_succeed() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1003);
let mut rig = StoreRig::with_transport(NoopTransport);
seed_group_key(&mut rig.secrets).await;
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Pending,
)
.await;
seed_member(
&mut rig.channels,
1003,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
super::start(&mut rig.stores(), &lf.local(), 1001, None, TRACE_ID)
.await
.expect("start");
assert_eq!(role_of(&rig.channels, 1003).await, ReplicaRole::Source);
assert_eq!(role_of(&rig.channels, 1002).await, ReplicaRole::Destination);
});
}
#[test]
fn a_sole_source_leaves_no_successor() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1001);
let mut rig = StoreRig::with_transport(NoopTransport);
seed_group_key(&mut rig.secrets).await;
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
let events = super::start(&mut rig.stores(), &lf.local(), 1001, None, TRACE_ID)
.await
.expect("a sole source may still leave");
assert!(
!events
.iter()
.any(|e| matches!(e, DeRecEvent::ReplicaSourceChanged { .. })),
"no successor exists to report"
);
});
}
#[test]
fn removing_a_destination_promotes_nobody() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1001);
let mut rig = StoreRig::with_transport(NoopTransport);
seed_group_key(&mut rig.secrets).await;
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
let events = super::start(&mut rig.stores(), &lf.local(), 1002, None, TRACE_ID)
.await
.expect("start");
assert!(
!events
.iter()
.any(|e| matches!(e, DeRecEvent::ReplicaSourceChanged { .. })),
"the source is unaffected by a destination leaving"
);
assert_eq!(role_of(&rig.channels, 1001).await, ReplicaRole::Source);
});
}
#[test]
fn each_notice_is_sealed_under_its_own_channel_key() {
const PAIRING: ChannelId = ChannelId(5002);
const GROUP_KEY: SharedKey = [7u8; 32];
const PAIRING_KEY: SharedKey = [0x22; 32];
for leaving in [1002, 1003] {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1001);
let mut rig = StoreRig::new();
seed_group_key(&mut rig.secrets).await;
rig.secrets
.save(SECRET_ID, PAIRING, SecretValue::SharedKey(PAIRING_KEY))
.await
.expect("seed pairing key");
seed_member(
&mut rig.channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut rig.channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
rig.channels
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: PAIRING,
replica_id: ReplicaId(1003),
transports: vec![endpoint("https://joiner.example")],
communication_info: HashMap::new(),
role: ReplicaRole::Destination,
status: ChannelStatus::Paired,
created_at: 0,
handover_channel: None,
}),
)
.await
.expect("seed joiner");
super::start(&mut rig.stores(), &lf.local(), leaving, None, TRACE_ID)
.await
.expect("start");
let mut noticed = Vec::new();
for bytes in rig.transport.sent_envelopes() {
let envelope =
DeRecMessage::decode(bytes.as_slice()).expect("envelope decodes");
let key = if envelope.channel_id == PAIRING.0 {
PAIRING_KEY
} else {
GROUP_KEY
};
match extract_inner_message(&envelope.message, &key) {
Ok(MessageBody::UnpairRequest(_)) => noticed.push(envelope.channel_id),
Ok(_) => {}
Err(e) => panic!(
"removing {leaving}: the message on channel {} must open under that channel's key: {e}",
envelope.channel_id
),
}
}
noticed.sort_unstable();
assert_eq!(
noticed,
vec![GROUP.0, PAIRING.0],
"removing {leaving}: both other members are told"
);
});
}
}
#[test]
fn removing_another_member_drops_its_row_and_its_own_key() {
const PAIRING: ChannelId = ChannelId(5002);
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1001);
let mut rig = StoreRig::with_transport(NoopTransport);
seed_group_key(&mut rig.secrets).await;
rig.secrets
.save(SECRET_ID, PAIRING, SecretValue::SharedKey([0x22; 32]))
.await
.expect("seed pairing key");
for id in [1001, 1002] {
seed_member(
&mut rig.channels,
id,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
}
rig.channels
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: PAIRING,
replica_id: ReplicaId(1003),
transports: vec![endpoint("https://joiner.example")],
communication_info: HashMap::new(),
role: ReplicaRole::Destination,
status: ChannelStatus::Paired,
created_at: 0,
handover_channel: None,
}),
)
.await
.expect("seed joiner");
let events = super::start(&mut rig.stores(), &lf.local(), 1003, None, TRACE_ID)
.await
.expect("start");
assert!(
events
.iter()
.any(|e| matches!(e, DeRecEvent::ReplicaRemoved { replica_id: 1003 })),
"{events:?}"
);
let mut ids: Vec<u64> = rig
.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.iter()
.map(|m| m.replica_id.0)
.collect();
ids.sort_unstable();
assert_eq!(ids, vec![1001, 1002]);
assert!(
rig.secrets
.load(SECRET_ID, PAIRING, SecretKind::SharedKey)
.await
.expect("load")
.is_none(),
"the key only the removed member used is dropped"
);
assert!(
rig.secrets
.load(SECRET_ID, GROUP, SecretKind::SharedKey)
.await
.expect("load")
.is_some(),
"the group key stays"
);
});
}
#[test]
fn a_member_told_to_leave_drops_everything_at_once() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1002);
let mut rig = StoreRig::new();
seed_group_key(&mut rig.secrets).await;
for id in [1001, 1002] {
seed_member(
&mut rig.channels,
id,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
}
rig.user_secrets
.save_latest(
SECRET_ID,
UserSecrets {
version: 4,
secrets: Vec::new(),
description: None,
author_replica_id: None,
threshold: None,
},
)
.await
.expect("seed snapshot");
let events = super::handle(
&mut rig.stores(),
&lf.local(),
1002,
MessageBody::UnpairRequest(UnpairRequestMessage::default()),
)
.await
.expect("handled");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::SelfRemovedFromGroup { version: 4 }]
),
"{events:?}"
);
assert!(
rig.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.is_empty()
);
assert!(
rig.secrets
.load(SECRET_ID, GROUP, SecretKind::SharedKey)
.await
.expect("load")
.is_none()
);
assert!(
rig.user_secrets
.load_latest(SECRET_ID)
.await
.expect("load")
.is_none()
);
});
}
#[test]
fn another_member_told_of_a_removal_only_flags_it() {
run_async(async {
let lf = LocalFixture::with_replica(SECRET_ID, 1001);
let mut rig = StoreRig::new();
seed_group_key(&mut rig.secrets).await;
for id in [1001, 1002] {
seed_member(
&mut rig.channels,
id,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
}
let events = super::handle(
&mut rig.stores(),
&lf.local(),
1002,
MessageBody::UnpairRequest(UnpairRequestMessage::default()),
)
.await
.expect("handled");
assert!(
matches!(events.as_slice(), [DeRecEvent::NoOp]),
"{events:?}"
);
let departing = rig
.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster")
.into_iter()
.find(|m| m.replica_id.0 == 1002)
.expect("still recorded");
assert_eq!(departing.status, ChannelStatus::Unpairing);
});
}
}