use super::super::{
DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecShareStore, DeRecTransport,
DeRecUserSecretStore, SecretKind,
};
use crate::protocol::types::{ChannelRecord, ChannelStatus, ReplicaMember, ReplicaRole};
use crate::types::{ChannelId, ReplicaId};
use crate::{Error, Result};
use derec_proto::UnpairRequestMessage;
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(secret_id)))]
#[allow(clippy::too_many_arguments)]
pub(in crate::protocol) async fn start<
Ch: DeRecChannelStore,
Ss: DeRecSecretStore,
T: DeRecTransport,
>(
channel_store: &mut Ch,
secret_store: &mut Ss,
transport: &T,
secret_id: u64,
target: u64,
memo: Option<String>,
local_replica_id: Option<u64>,
) -> Result<Vec<DeRecEvent>> {
let own = local_replica_id.ok_or(Error::ReplicaIdNotConfigured)?;
let target = ReplicaId::try_from(target)?;
let roster = channel_store.replicas(secret_id).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::Unpairing)
.cloned()
} else {
None
};
let group_channel = member.channel_id;
let key = match secret_store
.load(secret_id, group_channel, SecretKind::SharedKey)
.await?
{
Some(crate::protocol::types::SecretValue::SharedKey(k)) => k,
_ => {
return Err(Error::InvalidInput(
"channel has no shared key — not yet paired",
));
}
};
let memo = memo.unwrap_or_default();
let mut notified = Vec::new();
for peer in roster.iter().filter(|m| m.replica_id.0 != own) {
let request = crate::primitives::unpairing::request::produce(
peer.channel_id,
&memo,
&key,
None,
Some(target.0),
)?;
let envelope = super::apply_trace_id(request.envelope, super::fresh_trace_id())?;
if transport.send(&peer.transport, envelope).await.is_ok() {
notified.push(peer.replica_id);
}
}
flag_unpairing(channel_store, secret_id, &member).await?;
let mut events = Vec::new();
if let Some(successor) = successor {
channel_store
.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) async fn handle_request<Ch: DeRecChannelStore>(
channel_store: &mut Ch,
secret_id: u64,
request: &UnpairRequestMessage,
target: u64,
) -> Result<Vec<DeRecEvent>> {
let _ = request;
let target = ReplicaId::try_from(target)?;
let member = channel_store
.replicas(secret_id)
.await?
.into_iter()
.find(|m| m.replica_id == target)
.ok_or(Error::InvalidInput(
"unpair names a member that is not in the group",
))?;
flag_unpairing(channel_store, secret_id, &member).await?;
Ok(vec![DeRecEvent::NoOp])
}
async fn flag_unpairing<Ch: DeRecChannelStore>(
channel_store: &mut Ch,
secret_id: u64,
member: &ReplicaMember,
) -> Result<()> {
channel_store
.save(
secret_id,
ChannelRecord::Replica(ReplicaMember {
status: ChannelStatus::Unpairing,
..member.clone()
}),
)
.await?;
Ok(())
}
pub(in crate::protocol) enum RemovalOutcome {
Nothing,
Removed(Vec<u64>),
SelfRemoved,
}
pub(in crate::protocol) async fn reconcile<Ch: DeRecChannelStore>(
channel_store: &mut Ch,
secret_id: u64,
roster_ids: &[u64],
local_replica_id: Option<u64>,
) -> Result<RemovalOutcome> {
let stored = channel_store.replicas(secret_id).await?;
let mut removed = Vec::new();
let mut self_removed = false;
for member in stored
.iter()
.filter(|m| m.status == ChannelStatus::Unpairing)
{
if roster_ids.contains(&member.replica_id.0) {
continue;
}
if Some(member.replica_id.0) == local_replica_id {
self_removed = true;
continue;
}
channel_store
.remove(
secret_id,
crate::protocol::types::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<
Ch: DeRecChannelStore,
Sh: DeRecShareStore,
Ss: DeRecSecretStore,
Us: DeRecUserSecretStore,
>(
channel_store: &mut Ch,
share_store: &mut Sh,
secret_store: &mut Ss,
user_secret_store: &mut Us,
secret_id: u64,
) -> Result<()> {
for helper in channel_store.helpers(secret_id).await? {
drop_channel(
channel_store,
share_store,
secret_store,
secret_id,
helper.channel_id,
crate::protocol::types::ChannelQuery::Helper {
channel_id: helper.channel_id,
},
)
.await?;
}
for member in channel_store.replicas(secret_id).await? {
drop_channel(
channel_store,
share_store,
secret_store,
secret_id,
member.channel_id,
crate::protocol::types::ChannelQuery::Replica {
channel_id: member.channel_id,
replica_id: member.replica_id,
},
)
.await?;
}
user_secret_store.remove(secret_id).await?;
Ok(())
}
async fn drop_channel<Ch: DeRecChannelStore, Sh: DeRecShareStore, Ss: DeRecSecretStore>(
channel_store: &mut Ch,
share_store: &mut Sh,
secret_store: &mut Ss,
secret_id: u64,
channel_id: ChannelId,
query: crate::protocol::types::ChannelQuery,
) -> Result<()> {
let _ = share_store.remove_channel(secret_id, channel_id).await;
for kind in [
SecretKind::SharedKey,
SecretKind::PairingSecret,
SecretKind::PairingContact,
] {
let _ = secret_store.remove(secret_id, channel_id, kind).await;
}
channel_store.remove(secret_id, query).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocol::test::{
InMemChannelStore, InMemSecretStore, InMemShareStore, InMemUserSecretStore, run_async,
};
use crate::protocol::types::{HelperChannel, SecretValue, UserSecrets};
use crate::protocol::{DeRecSecretStore, DeRecUserSecretStore};
const SECRET_ID: u64 = 0xDE9A27;
const GROUP: ChannelId = ChannelId(5001);
fn endpoint(uri: &str) -> derec_proto::TransportProtocol {
derec_proto::TransportProtocol {
uri: uri.to_owned(),
protocol: derec_proto::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),
transport: endpoint("https://peer.example"),
communication_info: std::collections::HashMap::new(),
role,
status,
created_at: 0,
}),
)
.await
.expect("seed member");
}
#[test]
fn absence_alone_removes_nothing() {
run_async(async {
let mut channels = InMemChannelStore::default();
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
let outcome = super::reconcile(&mut channels, SECRET_ID, &[1001], Some(1001))
.await
.expect("reconcile");
assert!(matches!(outcome, RemovalOutcome::Nothing));
assert_eq!(
channels.replicas(SECRET_ID).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 mut channels = InMemChannelStore::default();
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
let outcome = super::reconcile(&mut channels, SECRET_ID, &[1001, 1002], Some(1001))
.await
.expect("reconcile");
assert!(matches!(outcome, RemovalOutcome::Nothing));
assert_eq!(
channels.replicas(SECRET_ID).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 mut channels = InMemChannelStore::default();
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
channels
.save(
SECRET_ID,
ChannelRecord::Helper(HelperChannel {
channel_id: ChannelId(9001),
transport: endpoint("https://helper.example"),
communication_info: std::collections::HashMap::new(),
peer_role: derec_proto::SenderKind::Helper,
status: ChannelStatus::Paired,
created_at: 0,
}),
)
.await
.expect("seed helper");
let outcome = super::reconcile(&mut channels, SECRET_ID, &[1001], Some(1001))
.await
.expect("reconcile");
assert!(matches!(outcome, RemovalOutcome::Removed(ref ids) if ids == &[1002]));
let roster = channels.replicas(SECRET_ID).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!(
channels.helpers(SECRET_ID).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 mut channels = InMemChannelStore::default();
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
let outcome = super::reconcile(&mut channels, SECRET_ID, &[1001], Some(1002))
.await
.expect("reconcile");
assert!(
matches!(outcome, RemovalOutcome::SelfRemoved),
"the device being removed is reported, not silently torn down"
);
assert_eq!(
channels.replicas(SECRET_ID).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 mut channels = InMemChannelStore::default();
let mut shares = InMemShareStore::default();
let mut secrets = InMemSecretStore::default();
let mut user_secrets = InMemUserSecretStore::default();
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
channels
.save(
SECRET_ID,
ChannelRecord::Helper(HelperChannel {
channel_id: ChannelId(9001),
transport: endpoint("https://helper.example"),
communication_info: std::collections::HashMap::new(),
peer_role: derec_proto::SenderKind::Helper,
status: ChannelStatus::Paired,
created_at: 0,
}),
)
.await
.expect("seed helper");
secrets
.save(SECRET_ID, GROUP, SecretValue::SharedKey([0x33; 32]))
.await
.expect("seed key");
user_secrets
.save_latest(
SECRET_ID,
UserSecrets {
version: 4,
secrets: Vec::new(),
description: None,
replicas: None,
},
)
.await
.expect("seed snapshot");
super::tear_down(
&mut channels,
&mut shares,
&mut secrets,
&mut user_secrets,
SECRET_ID,
)
.await
.expect("tear down");
assert!(
channels
.replicas(SECRET_ID)
.await
.expect("roster")
.is_empty()
);
assert!(
channels
.helpers(SECRET_ID)
.await
.expect("helpers")
.is_empty()
);
assert!(
secrets
.load(SECRET_ID, GROUP, SecretKind::SharedKey)
.await
.expect("load")
.is_none(),
"the group key goes with everything else"
);
assert!(
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)
.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 mut channels = InMemChannelStore::default();
let mut secrets = InMemSecretStore::default();
let transport = crate::protocol::test::NoopTransport;
seed_group_key(&mut secrets).await;
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
let events = super::start(
&mut channels,
&mut secrets,
&transport,
SECRET_ID,
1001,
None,
Some(1002),
)
.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(&channels, 1002).await, ReplicaRole::Source);
assert_eq!(
role_of(&channels, 1001).await,
ReplicaRole::Source,
"the departing row is untouched; its absence from the next roster is what removes it"
);
});
}
#[test]
fn a_departing_member_is_not_eligible_to_succeed() {
run_async(async {
let mut channels = InMemChannelStore::default();
let mut secrets = InMemSecretStore::default();
let transport = crate::protocol::test::NoopTransport;
seed_group_key(&mut secrets).await;
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Unpairing,
)
.await;
seed_member(
&mut channels,
1003,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
super::start(
&mut channels,
&mut secrets,
&transport,
SECRET_ID,
1001,
None,
Some(1003),
)
.await
.expect("start");
assert_eq!(role_of(&channels, 1003).await, ReplicaRole::Source);
assert_eq!(role_of(&channels, 1002).await, ReplicaRole::Destination);
});
}
#[test]
fn a_sole_source_leaves_no_successor() {
run_async(async {
let mut channels = InMemChannelStore::default();
let mut secrets = InMemSecretStore::default();
let transport = crate::protocol::test::NoopTransport;
seed_group_key(&mut secrets).await;
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
let events = super::start(
&mut channels,
&mut secrets,
&transport,
SECRET_ID,
1001,
None,
Some(1001),
)
.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 mut channels = InMemChannelStore::default();
let mut secrets = InMemSecretStore::default();
let transport = crate::protocol::test::NoopTransport;
seed_group_key(&mut secrets).await;
seed_member(
&mut channels,
1001,
ReplicaRole::Source,
ChannelStatus::Paired,
)
.await;
seed_member(
&mut channels,
1002,
ReplicaRole::Destination,
ChannelStatus::Paired,
)
.await;
let events = super::start(
&mut channels,
&mut secrets,
&transport,
SECRET_ID,
1002,
None,
Some(1001),
)
.await
.expect("start");
assert!(
!events
.iter()
.any(|e| matches!(e, DeRecEvent::ReplicaSourceChanged { .. })),
"the source is unaffected by a destination leaving"
);
assert_eq!(role_of(&channels, 1001).await, ReplicaRole::Source);
});
}
}