use super::unpairing::{self, RemovalOutcome};
use crate::derec_message::{DeRecMessageBuilder, apply_trace_id};
use crate::extensions::advertised_endpoints::reply_to_owned;
use crate::extensions::channel_store::{ChannelStoreExt as _, filter_reply_to};
#[cfg(target_arch = "wasm32")]
use crate::interop::wasm::now_secs;
use crate::primitives::sharing::response::validate_committed_share;
use crate::protocol::DeRecUserSecretStore;
use crate::protocol::context::{Exchange, Local};
use crate::protocol::handlers::sharing::subshare_count;
use crate::protocol::obligation::{Obligation, attempted, deliver, refused, reported};
use crate::protocol::stores::{StoreSet, Stores};
use crate::protocol::types::{
ChannelQuery, ChannelShare, ReplicaFilter, ReplicaMember, ReplicaRole, ReplicaSecretPayload,
Share, UserSecret,
};
use crate::protocol::{
DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecShareStore, SecretKind, SecretValue,
};
use crate::types::ReplicaId;
#[cfg(not(target_arch = "wasm32"))]
use crate::utils::now_secs;
use crate::{
Error, Result,
derec_message::current_timestamp,
protocol::types::Secret,
types::{ChannelId, SharedKey},
};
use derec_proto::{
CommittedDeRecShare, DeRecResult, MessageBody, SenderKind, StatusEnum,
StoreShareRequestMessage, StoreShareResponseMessage,
};
use prost::Message;
use std::cmp::Ordering;
use std::collections::HashMap;
pub(in crate::protocol) async fn complete_handover<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
channel_id: ChannelId,
author: u64,
) -> Result<bool> {
use crate::protocol::types::{ChannelRecord, ChannelStatus};
let (Some(own_id), Ok(author)) = (local.replica_id, ReplicaId::try_from(author)) else {
return Ok(false);
};
let secret_id = local.secret_id;
let member = |replica_id| ChannelQuery::Replica {
channel_id,
replica_id,
};
let own_on_channel = stores
.channels
.load(secret_id, member(ReplicaId(own_id)))
.await?
.and_then(|record| record.as_replica().cloned())
.is_some_and(|own| own.channel_id == channel_id);
if !own_on_channel {
return Ok(false);
}
let Some(joiner) = stores
.channels
.load(secret_id, member(author))
.await?
.and_then(|record| record.as_replica().cloned())
.filter(|m| m.channel_id != channel_id && m.status == ChannelStatus::Paired)
else {
return Ok(false);
};
let ephemeral = joiner.channel_id;
stores
.channels
.save(
secret_id,
ChannelRecord::Replica(ReplicaMember {
channel_id,
handover_channel: None,
..joiner
}),
)
.await?;
let _ = stores
.secrets
.remove(secret_id, ephemeral, SecretKind::SharedKey)
.await;
#[cfg(feature = "logging")]
tracing::info!(
ephemeral_channel_id = ephemeral.0,
group_channel_id = channel_id.0,
replica_id = author.0,
"admitted member moved onto the group channel"
);
Ok(true)
}
pub(in crate::protocol) async fn release_handover<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
member: &ReplicaMember,
channel_id: ChannelId,
) -> Result<()> {
use crate::protocol::types::ChannelRecord;
let Some(handover) = member.handover_channel.filter(|&h| h != channel_id) else {
return Ok(());
};
let secret_id = local.secret_id;
stores
.channels
.save(
secret_id,
ChannelRecord::Replica(ReplicaMember {
handover_channel: None,
..member.clone()
}),
)
.await?;
let _ = stores
.secrets
.remove(secret_id, handover, SecretKind::SharedKey)
.await;
#[cfg(feature = "logging")]
tracing::info!(
handover_channel_id = handover.0,
group_channel_id = channel_id.0,
replica_id = member.replica_id.0,
"admitting member reached this device on the group channel; handover channel dropped"
);
Ok(())
}
pub(in crate::protocol) enum Arrival {
Apply { is_install: bool },
Resend,
Conflict { held_author_replica_id: Option<u64> },
Stale,
}
pub(in crate::protocol) async fn arrival<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
version: u32,
incoming_author_replica_id: Option<u64>,
incoming_secrets: &[UserSecret],
) -> Result<Arrival> {
let Some(held) = stores.user_secrets.load_latest(local.secret_id).await? else {
return Ok(Arrival::Apply { is_install: true });
};
Ok(match version.cmp(&held.version) {
Ordering::Greater => Arrival::Apply { is_install: false },
Ordering::Less => Arrival::Stale,
Ordering::Equal
if match held.author_replica_id {
Some(author) => Some(author) == incoming_author_replica_id,
None => held.secrets == incoming_secrets,
} =>
{
Arrival::Resend
}
Ordering::Equal => Arrival::Conflict {
held_author_replica_id: held.author_replica_id,
},
})
}
pub(in crate::protocol) async fn handle<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
exchange: &Exchange<'_>,
author: u64,
inner: MessageBody,
) -> Result<Vec<DeRecEvent>> {
let member = stores
.channels
.load_replica_member(local.secret_id, exchange.channel_id, author)
.await?;
match inner {
MessageBody::StoreShareRequest(request) => {
if let Some(obligation) = exchange.obligation {
obligation.answer_at(&member.transports);
}
on_request(
stores,
local,
&member,
request,
*exchange.shared_key,
exchange.trace_id,
exchange.obligation,
)
.await
}
MessageBody::StoreShareResponse(response) => {
on_response(exchange.channel_id, &member, &response)
}
_ => Err(Error::Invariant(
"replica identity on a message that is not a store-share exchange",
)),
}
}
#[derive(Debug, Clone, Copy)]
pub(in crate::protocol) struct PayloadFault {
pub(in crate::protocol) status: StatusEnum,
pub(in crate::protocol) memo: &'static str,
}
impl PayloadFault {
pub(in crate::protocol) const fn format(memo: &'static str) -> Self {
Self {
status: StatusEnum::FormatError,
memo,
}
}
}
pub(in crate::protocol) struct Checked<'a> {
secret: &'a Secret,
shares: &'a [ChannelShare],
helper_keys: Vec<SharedKey>,
group: Option<CheckedGroup>,
}
struct CheckedGroup {
channel_id: ChannelId,
key: SharedKey,
members: Vec<(ReplicaId, ReplicaRole)>,
}
pub(in crate::protocol) fn check<'a>(
secret: &'a Secret,
shares: &'a [ChannelShare],
) -> std::result::Result<Checked<'a>, PayloadFault> {
if secret.threshold.is_some_and(|t| t < 2) {
return Err(PayloadFault::format("roster threshold must be at least 2"));
}
let helper_keys = secret
.helpers
.iter()
.map(|helper| {
helper
.shared_key
.as_slice()
.try_into()
.map_err(|_| PayloadFault::format("roster helper shared_key must be 32 bytes"))
})
.collect::<std::result::Result<Vec<SharedKey>, _>>()?;
for share in shares {
if !secret
.helpers
.iter()
.any(|h| h.channel_id == share.channel_id)
{
return Err(PayloadFault::format(
"share map names a channel absent from the roster's helpers",
));
}
validate_committed_share(&share.committed_share).map_err(|fault| PayloadFault {
status: fault.status,
memo: fault.memo,
})?;
}
let group = match secret.replicas.as_ref().filter(|g| !g.members.is_empty()) {
None => None,
Some(group) => {
let key: SharedKey =
group.shared_key.as_slice().try_into().map_err(|_| {
PayloadFault::format("roster group shared_key must be 32 bytes")
})?;
let members = group
.members
.iter()
.map(|member| {
let id = ReplicaId::try_from(member.replica_id).map_err(|_| {
PayloadFault::format("roster member carries the reserved replica_id 0")
})?;
let role = ReplicaRole::from_i32(member.role).ok_or(PayloadFault::format(
"roster member carries an unknown role",
))?;
Ok((id, role))
})
.collect::<std::result::Result<Vec<_>, PayloadFault>>()?;
Some(CheckedGroup {
channel_id: ChannelId(group.channel_id),
key,
members,
})
}
};
Ok(Checked {
secret,
shares,
helper_keys,
group,
})
}
pub(in crate::protocol) async fn hydrate<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
(arrived_on, sender): (ChannelId, ReplicaId),
version: u32,
checked: &Checked<'_>,
description: String,
author_replica_id: Option<u64>,
) -> Result<Option<(ChannelId, SharedKey)>> {
let secret_id = local.secret_id;
let secret = checked.secret;
use crate::protocol::types::{ChannelRecord, ChannelStatus, HelperChannel, UserSecrets};
for (helper, key) in secret.helpers.iter().zip(&checked.helper_keys) {
let channel_id = ChannelId(helper.channel_id);
stores
.channels
.save(
secret_id,
ChannelRecord::Helper(HelperChannel {
channel_id,
transports: helper.transports.clone(),
communication_info: helper.communication_info.clone(),
peer_role: SenderKind::Helper,
status: ChannelStatus::Paired,
created_at: now_secs(),
weight: helper.effective_weight(),
}),
)
.await?;
stores
.secrets
.save(secret_id, channel_id, SecretValue::SharedKey(*key))
.await?;
}
for share in checked.shares {
stores
.shares
.save(
secret_id,
ChannelId(share.channel_id),
Share {
secret_id,
version,
bytes: share.committed_share.clone(),
subshares: CommittedDeRecShare::decode(share.committed_share.as_slice())
.ok()
.as_ref()
.and_then(subshare_count),
threshold: secret.threshold,
},
)
.await?;
}
let (Some(group), Some(roster)) = (checked.group.as_ref(), secret.replicas.as_ref()) else {
return Ok(None);
};
let handover_channels: HashMap<ReplicaId, ChannelId> = stores
.channels
.replicas_matching(secret_id, ReplicaFilter::default())
.await?
.into_iter()
.filter_map(|m| m.handover_channel.map(|h| (m.replica_id, h)))
.collect();
for (member, (replica_id, role)) in roster.members.iter().zip(&group.members) {
let handover_channel = if arrived_on != group.channel_id && *replica_id == sender {
Some(arrived_on)
} else {
handover_channels.get(replica_id).copied()
};
stores
.channels
.save(
secret_id,
ChannelRecord::Replica(ReplicaMember {
channel_id: group.channel_id,
replica_id: *replica_id,
transports: member.transports.clone(),
communication_info: member.communication_info.clone(),
role: *role,
status: ChannelStatus::Paired,
created_at: now_secs(),
handover_channel,
}),
)
.await?;
}
stores
.secrets
.save(
secret_id,
group.channel_id,
SecretValue::SharedKey(group.key),
)
.await?;
stores
.user_secrets
.save_latest(
secret_id,
UserSecrets {
version,
secrets: secret.secrets.clone(),
description: Some(description).filter(|d| !d.is_empty()),
author_replica_id,
threshold: secret.threshold,
},
)
.await?;
Ok(Some((group.channel_id, group.key)))
}
async fn on_request<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
channel: &ReplicaMember,
request: StoreShareRequestMessage,
shared_key: SharedKey,
inbound_trace_id: u64,
obligation: Option<&Obligation>,
) -> Result<Vec<DeRecEvent>> {
let from_replica_id = request.replica_id.unwrap_or(channel.replica_id.0);
let secret_id = request.secret_id;
let partition = local.secret_id;
let version = request.version;
let mut reply = (channel.channel_id, shared_key);
macro_rules! refuse {
($fault:expr) => {{
let fault: PayloadFault = $fault;
let sent = answer(
stores,
local,
channel,
&request,
reply,
fault.status,
fault.memo,
inbound_trace_id,
obligation,
)
.await;
return refused(
obligation,
DeRecEvent::ReplicaSecretRefused {
channel_id: channel.channel_id,
from_replica_id,
secret_id,
version,
status: fault.status as i32,
memo: fault.memo.to_owned(),
},
fault.status,
fault.memo,
sent,
);
}};
}
let Ok(composite) = ReplicaSecretPayload::decode(request.share.as_slice()) else {
refuse!(PayloadFault::format(
"replica secret payload is not a valid ReplicaSecretPayload"
));
};
let Some(secret) = composite.secret else {
refuse!(PayloadFault::format(
"replica secret payload missing `secret` field"
));
};
let shares = composite.shares;
if let (Ok(group_key), Some(group)) = (
<SharedKey>::try_from(composite.shared_key.as_slice()),
secret.replicas.as_ref(),
) {
reply = (ChannelId(group.channel_id), group_key);
if let Some(obligation) = obligation {
obligation.encrypt_for(reply.0, reply.1);
}
}
if composite.version != 0 && composite.version != version {
refuse!(PayloadFault::format(
"replica payload's version disagrees with the request's version"
));
}
if !composite.shared_key.is_empty() {
let roster_key = secret.replicas.as_ref().map(|g| g.shared_key.as_slice());
if roster_key != Some(composite.shared_key.as_slice()) {
refuse!(PayloadFault::format(
"replica payload's shared_key disagrees with the roster's group key"
));
}
}
let checked = match check(&secret, &shares) {
Ok(checked) => checked,
Err(fault) => refuse!(fault),
};
let author_replica_id = composite.author_replica_id.or(Some(from_replica_id));
let is_install =
match arrival(stores, local, version, author_replica_id, &secret.secrets).await? {
Arrival::Apply { is_install } => is_install,
Arrival::Resend => {
let sent = answer(
stores,
local,
channel,
&request,
reply,
StatusEnum::Ok,
"",
inbound_trace_id,
obligation,
)
.await;
return reported(obligation, vec![DeRecEvent::NoOp], sent);
}
Arrival::Conflict {
held_author_replica_id,
} => {
let sent = answer(
stores,
local,
channel,
&request,
reply,
StatusEnum::VersionConflict,
"a different copy of this version is already held",
inbound_trace_id,
obligation,
)
.await;
return refused(
obligation,
DeRecEvent::ReplicaVersionConflict {
channel_id: channel.channel_id,
from_replica_id,
secret_id,
version,
held_author_replica_id,
incoming_author_replica_id: author_replica_id,
secret,
},
StatusEnum::VersionConflict,
"a different copy of this version is already held",
sent,
);
}
Arrival::Stale => {
let sent = answer(
stores,
local,
channel,
&request,
reply,
StatusEnum::VersionConflict,
"a newer version is already held",
inbound_trace_id,
obligation,
)
.await;
return refused(
obligation,
DeRecEvent::NoOp,
StatusEnum::VersionConflict,
"a newer version is already held",
sent,
);
}
};
let was_source = match local.replica_id {
Some(id) => stores
.channels
.load(
partition,
ChannelQuery::Replica {
channel_id: channel.channel_id,
replica_id: ReplicaId(id),
},
)
.await?
.and_then(|r| r.as_replica().cloned())
.is_some_and(|m| m.role == ReplicaRole::Source),
None => false,
};
let hydrated = hydrate(
stores,
local,
(channel.channel_id, channel.replica_id),
version,
&checked,
request.version_description.clone(),
author_replica_id,
)
.await?;
let (ack_channel, ack_key) = hydrated.unwrap_or((channel.channel_id, shared_key));
if let Some(obligation) = obligation {
obligation.encrypt_for(ack_channel, ack_key);
}
let roster_ids: Vec<u64> = secret
.replicas
.as_ref()
.map(|g| g.members.iter().map(|m| m.replica_id).collect())
.unwrap_or_default();
let removal = unpairing::reconcile(stores, local, &roster_ids).await?;
let promotion = promotion_event(local, was_source, &secret);
let sent = answer(
stores,
local,
channel,
&request,
(ack_channel, ack_key),
StatusEnum::Ok,
"",
inbound_trace_id,
obligation,
)
.await;
if sent.is_err() && !attempted(obligation) {
return sent.map(|()| Vec::new());
}
#[cfg(feature = "logging")]
tracing::info!(
channel_id = channel.channel_id.0,
from_replica_id,
secret_id,
version,
is_install,
helpers_in_secret = secret.helpers.len(),
members_in_secret = secret.replicas.as_ref().map_or(0, |g| g.members.len()),
secrets_in_secret = secret.secrets.len(),
shares_count = shares.len(),
"replica secret hydrated; ack sent"
);
let installed = if is_install {
DeRecEvent::ReplicaSecretInstalled {
channel_id: channel.channel_id,
from_replica_id,
author_replica_id,
secret_id,
version,
secret,
shares,
}
} else {
DeRecEvent::ReplicaSecretReceived {
channel_id: channel.channel_id,
from_replica_id,
author_replica_id,
secret_id,
version,
secret,
shares,
}
};
match removal {
RemovalOutcome::SelfRemoved => {
let torn_down = unpairing::tear_down(stores, local).await;
#[cfg(feature = "logging")]
tracing::info!(
secret_id,
version,
"left the replica group; partition dropped"
);
reported(
obligation,
vec![DeRecEvent::SelfRemovedFromGroup { version }],
sent.and(torn_down),
)
}
RemovalOutcome::Removed(ids) => {
let mut events: Vec<DeRecEvent> = ids
.into_iter()
.map(|replica_id| DeRecEvent::ReplicaRemoved { replica_id })
.collect();
events.extend(promotion);
events.push(installed);
reported(obligation, events, sent)
}
RemovalOutcome::Nothing => {
let mut events: Vec<DeRecEvent> = promotion.into_iter().collect();
events.push(installed);
reported(obligation, events, sent)
}
}
}
#[allow(clippy::too_many_arguments)]
async fn answer<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
channel: &ReplicaMember,
request: &StoreShareRequestMessage,
(ack_channel, ack_key): (ChannelId, SharedKey),
status: StatusEnum,
memo: &str,
inbound_trace_id: u64,
obligation: Option<&Obligation>,
) -> Result<()> {
let timestamp = current_timestamp();
let response = StoreShareResponseMessage {
result: Some(DeRecResult {
status: status as i32,
memo: memo.to_owned(),
}),
version: request.version,
timestamp: Some(timestamp),
secret_id: request.secret_id,
replica_id: local.replica_id,
};
let envelope_bytes = DeRecMessageBuilder::channel()
.channel_id(ack_channel)
.timestamp(timestamp)
.message_body(MessageBody::StoreShareResponse(response))
.encrypt(&ack_key)?
.build()?
.encode_to_vec();
let envelope = apply_trace_id(&envelope_bytes, inbound_trace_id)?;
let reply_to = filter_reply_to(local.policy, &reply_to_owned(request));
let endpoint = if reply_to.is_empty() {
channel.transports.clone()
} else {
reply_to
};
deliver(
obligation,
stores.transport,
&endpoint,
envelope,
status,
memo,
)
.await
}
fn on_response(
arrived_on: ChannelId,
channel: &ReplicaMember,
response: &StoreShareResponseMessage,
) -> Result<Vec<DeRecEvent>> {
let from_replica_id = response.replica_id.unwrap_or(channel.replica_id.0);
let (status, memo) = response
.result
.as_ref()
.map(|r| (r.status, r.memo.clone()))
.unwrap_or((-1, "response missing `result` field".to_owned()));
if status == StatusEnum::Ok as i32 {
Ok(vec![DeRecEvent::ReplicaSecretAcked {
channel_id: arrived_on,
from_replica_id,
secret_id: response.secret_id,
version: response.version,
status,
memo,
}])
} else {
Ok(vec![DeRecEvent::ReplicaSyncRejected {
replica_id: from_replica_id,
secret_id: response.secret_id,
version: response.version,
status,
memo,
}])
}
}
fn promotion_event(local: &Local<'_>, was_source: bool, secret: &Secret) -> Option<DeRecEvent> {
if was_source {
return None;
}
let id = local.replica_id?;
let now_source = secret.replicas.as_ref().is_some_and(|g| {
g.members
.iter()
.any(|m| m.replica_id == id && m.role == ReplicaRole::Source as i32)
});
now_source.then_some(DeRecEvent::ReplicaSourceChanged { replica_id: id })
}
#[cfg(test)]
mod tests {
use crate::extensions::derec_result::DeRecResultExt as _;
use crate::primitives::sharing::request;
use crate::protocol::handlers::sharing::build_secret;
use crate::protocol::tests::{InMemChannelStore, LocalFixture, StoreRig, run_async};
use crate::protocol::types::{
ChannelQuery, ChannelRecord, ChannelStatus, ReplicaFilter, ReplicaMember, ReplicaRole,
ReplicaSecretPayload, Secret,
};
use crate::protocol::{DeRecChannelStore, DeRecEvent};
use crate::transport;
use crate::types::{ChannelId, ReplicaId};
use derec_proto::{
DeRecResult, Protocol, StatusEnum, StoreShareRequestMessage, StoreShareResponseMessage,
TransportProtocol,
};
use prost::Message;
use std::collections::HashMap;
const SECRET_ID: u64 = 0xB0B;
const GROUP_CHANNEL: ChannelId = ChannelId(9001);
fn endpoint(uri: &str) -> TransportProtocol {
TransportProtocol {
uri: uri.to_owned(),
protocol: Protocol::Https as i32,
}
}
async fn seed_member(
channels: &mut InMemChannelStore,
replica_id: u64,
role: ReplicaRole,
uri: &str,
) {
channels
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: GROUP_CHANNEL,
replica_id: ReplicaId(replica_id),
transports: vec![endpoint(uri)],
communication_info: HashMap::new(),
role,
status: ChannelStatus::Paired,
created_at: 0,
handover_channel: None,
}),
)
.await
.expect("seed member");
}
#[test]
fn hydrate_uses_each_stored_endpoint_verbatim() {
run_async(async {
let lf = LocalFixture::new(SECRET_ID);
use crate::protocol::traits::DeRecChannelStore;
use crate::protocol::types::{HelperInfo, ReplicaInfo, Replicas};
const SECRET_ID: u64 = 0xD3_57;
let secret = Secret {
helpers: vec![
HelperInfo {
channel_id: 11,
transports: vec![TransportProtocol {
uri: "grpcs://helper.example:443".to_owned(),
protocol: Protocol::Grpc as i32,
}],
shared_key: vec![0xAA; 32],
communication_info: HashMap::new(),
weight: 1,
},
HelperInfo {
channel_id: 12,
transports: vec![TransportProtocol {
uri: "https://helper-b.example".to_owned(),
protocol: Protocol::Https as i32,
}],
shared_key: vec![0xAB; 32],
communication_info: HashMap::new(),
weight: 1,
},
],
secrets: Vec::new(),
replicas: Some(Replicas {
channel_id: 21,
members: vec![ReplicaInfo {
replica_id: 0xCAFE,
transports: vec![TransportProtocol {
uri: "grpcs://replica.example:443".to_owned(),
protocol: Protocol::Grpc as i32,
}],
role: ReplicaRole::Destination as i32,
communication_info: HashMap::new(),
}],
shared_key: vec![0xCC; 32],
}),
threshold: None,
};
let mut rig = StoreRig::new();
super::hydrate(
&mut rig.stores(),
&lf.local(),
(ChannelId(0), ReplicaId(0)),
4,
&super::check(&secret, &[]).expect("a well-formed roster"),
String::new(),
None,
)
.await
.expect("a grpc roster must hydrate");
let expected = [(11_u64, Protocol::Grpc), (12, Protocol::Https)];
for (channel_id, protocol) in expected {
let record = rig
.channels
.load(
SECRET_ID,
ChannelQuery::Helper {
channel_id: ChannelId(channel_id),
},
)
.await
.unwrap()
.expect("helper channel must be persisted");
let ChannelRecord::Helper(record) = record else {
panic!("a helper query must never return a replica record");
};
assert_eq!(
record.transports[0].protocol, protocol as i32,
"helper {channel_id} must carry the protocol its URI scheme names"
);
for endpoint in &record.transports {
transport::TransportProtocol::try_from(endpoint)
.expect("every rehydrated endpoint must be self-consistent");
}
}
let member = rig
.channels
.load(
SECRET_ID,
ChannelQuery::Replica {
channel_id: ChannelId(21),
replica_id: ReplicaId(0xCAFE),
},
)
.await
.unwrap()
.expect("group member must be persisted");
let ChannelRecord::Replica(member) = member else {
panic!("a replica query must never return a helper record");
};
assert_eq!(member.transports[0].protocol, Protocol::Grpc as i32);
});
}
#[test]
fn hydrate_writes_each_roster_weight_into_the_helper_channel() {
run_async(async {
use crate::protocol::types::HelperInfo;
let lf = LocalFixture::new(SECRET_ID);
let helper = |channel_id, weight| HelperInfo {
channel_id,
transports: vec![endpoint("https://helper.example")],
shared_key: vec![channel_id as u8; 32],
communication_info: HashMap::new(),
weight,
};
let secret = Secret {
helpers: vec![helper(11, 2), helper(12, 0)],
secrets: Vec::new(),
replicas: None,
threshold: None,
};
let mut rig = StoreRig::new();
super::hydrate(
&mut rig.stores(),
&lf.local(),
(ChannelId(0), ReplicaId(0)),
4,
&super::check(&secret, &[]).expect("a well-formed roster"),
String::new(),
None,
)
.await
.expect("hydrates");
for (channel_id, expected) in [(11_u64, 2_u32), (12, 1)] {
let record = rig
.channels
.load(
SECRET_ID,
ChannelQuery::Helper {
channel_id: ChannelId(channel_id),
},
)
.await
.unwrap()
.and_then(|r| r.as_helper().cloned())
.expect("helper channel persisted");
assert_eq!(record.weight, expected, "helper {channel_id}");
}
});
}
#[test]
fn hydrate_records_the_subshare_count_of_each_mirrored_share() {
run_async(async {
use crate::protocol::types::{ChannelShare, HelperInfo};
use prost::Message as _;
let lf = LocalFixture::new(SECRET_ID);
let helper = |channel_id, weight| HelperInfo {
channel_id,
transports: vec![endpoint("https://helper.example")],
shared_key: vec![channel_id as u8; 32],
communication_info: HashMap::new(),
weight,
};
let secret = Secret {
helpers: vec![helper(11, 1), helper(12, 1)],
secrets: Vec::new(),
replicas: None,
threshold: None,
};
let split = request::split(
&[(ChannelId(11), 2), (ChannelId(12), 1)],
SECRET_ID,
4,
b"mirrored secret",
3,
)
.expect("weighted split");
let shares: Vec<ChannelShare> = split
.shares
.iter()
.map(|(channel_id, committed)| ChannelShare {
channel_id: channel_id.0,
committed_share: committed.encode_to_vec(),
})
.collect();
let mut rig = StoreRig::new();
super::hydrate(
&mut rig.stores(),
&lf.local(),
(ChannelId(0), ReplicaId(0)),
4,
&super::check(&secret, &shares).expect("a well-formed roster"),
String::new(),
None,
)
.await
.expect("hydrates");
for (channel_id, expected) in [(11_u64, 2_u32), (12, 1)] {
let stored = rig
.shares
.data
.lock()
.unwrap()
.get(&(SECRET_ID, channel_id, 4))
.cloned()
.expect("mirrored tracking share");
assert_eq!(stored.subshares, Some(expected), "helper {channel_id}");
}
});
}
#[test]
fn replica_ack_attributes_the_responder_from_the_payload() {
run_async(async {
const SECRET_ID: u64 = 0xA11CE;
const CHANNEL_PEER: u64 = 1002;
const ACTUAL_RESPONDER: u64 = 1003;
let channel = ReplicaMember {
channel_id: ChannelId(5001),
replica_id: ReplicaId(CHANNEL_PEER),
transports: vec![TransportProtocol {
uri: "https://alice-2.example".to_owned(),
protocol: Protocol::Https as i32,
}],
communication_info: HashMap::new(),
status: ChannelStatus::Paired,
created_at: 0,
handover_channel: None,
role: ReplicaRole::Destination,
};
let response = StoreShareResponseMessage {
result: Some(DeRecResult::ok()),
secret_id: SECRET_ID,
version: 3,
timestamp: None,
replica_id: Some(ACTUAL_RESPONDER),
};
let events = super::on_response(channel.channel_id, &channel, &response)
.expect("ack is handled");
match events.as_slice() {
[
DeRecEvent::ReplicaSecretAcked {
from_replica_id, ..
},
] => assert_eq!(
*from_replica_id, ACTUAL_RESPONDER,
"the responder names itself; the channel's counterparty is not the author"
),
other => panic!("expected a single ReplicaSecretAcked, got {other:?}"),
}
});
}
#[test]
fn a_second_roster_reports_received_not_installed() {
run_async(async {
use crate::protocol::types::{ReplicaInfo, Replicas};
const OWNER: u64 = 1001;
const SELF_ID: u64 = 1002;
const WIRE_SECRET_ID: u64 = 0xC0FFEE;
let lf = LocalFixture::with_replica(SECRET_ID, SELF_ID);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
OWNER,
ReplicaRole::Source,
"https://owner",
)
.await;
seed_member(
&mut rig.channels,
SELF_ID,
ReplicaRole::Destination,
"https://self",
)
.await;
let channel = rig
.channels
.load(
SECRET_ID,
ChannelQuery::Replica {
channel_id: GROUP_CHANNEL,
replica_id: ReplicaId(OWNER),
},
)
.await
.expect("load")
.and_then(|r| r.as_replica().cloned())
.expect("seeded member");
let roster = || Secret {
helpers: Vec::new(),
secrets: Vec::new(),
replicas: Some(Replicas {
channel_id: GROUP_CHANNEL.0,
members: vec![
ReplicaInfo {
replica_id: OWNER,
transports: vec![endpoint("https://owner")],
role: ReplicaRole::Source as i32,
communication_info: HashMap::new(),
},
ReplicaInfo {
replica_id: SELF_ID,
transports: vec![endpoint("https://self")],
role: ReplicaRole::Destination as i32,
communication_info: HashMap::new(),
},
],
shared_key: vec![0x42; 32],
}),
threshold: None,
};
let request = |version: u32| {
let payload = ReplicaSecretPayload {
secret: Some(roster()),
shares: Vec::new(),
shared_key: Vec::new(),
version,
author_replica_id: None,
};
StoreShareRequestMessage {
secret_id: WIRE_SECRET_ID,
share: Message::encode_to_vec(&payload),
version,
version_description: String::new(),
share_algorithm: 0,
keep_version: 0,
replica_id: Some(OWNER),
reply_to_transports: Vec::new(),
timestamp: None,
}
};
let first = super::on_request(
&mut rig.stores(),
&lf.local(),
&channel,
request(1),
[0x11; 32],
7,
None,
)
.await
.expect("first roster");
assert!(
first
.iter()
.any(|e| matches!(e, DeRecEvent::ReplicaSecretInstalled { .. })),
"the first roster installs; got {first:?}"
);
let second = super::on_request(
&mut rig.stores(),
&lf.local(),
&channel,
request(2),
[0x11; 32],
8,
None,
)
.await
.expect("second roster");
assert!(
second
.iter()
.any(|e| matches!(e, DeRecEvent::ReplicaSecretReceived { .. })),
"a device that already holds the secret receives rather than installs; got {second:?}"
);
let echoed = second.iter().find_map(|e| match e {
DeRecEvent::ReplicaSecretReceived { secret_id, .. } => Some(*secret_id),
_ => None,
});
assert_eq!(
echoed,
Some(WIRE_SECRET_ID),
"the event echoes the inbound secret_id, not the local partition"
);
});
}
mod author_tests {
use super::super::on_request;
use super::*;
use crate::derec_message::extract_inner_message;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::protocol::handlers::sharing::{build_catch_up_payload, hydrate_catch_up};
use crate::protocol::types::{
ReplicaInfo, ReplicaSecretPayload, Replicas, Secret, UserSecret,
};
use crate::protocol::{DeRecEvent, DeRecUserSecretStore};
use derec_proto::{DeRecMessage, MessageBody, StatusEnum, StoreShareRequestMessage};
use std::collections::HashMap;
const B: u64 = 1001;
const A: u64 = 1002;
const C: u64 = 1003;
const GROUP_KEY: [u8; 32] = [0x42; 32];
fn state(label: &str) -> Secret {
let member = |replica_id, role: ReplicaRole| ReplicaInfo {
replica_id,
transports: vec![endpoint(&format!("https://m{replica_id}"))],
role: role as i32,
communication_info: HashMap::new(),
};
Secret {
helpers: Vec::new(),
secrets: vec![UserSecret {
id: vec![1],
name: label.to_owned(),
data: label.as_bytes().to_vec(),
}],
replicas: Some(Replicas {
channel_id: GROUP_CHANNEL.0,
members: vec![
member(B, ReplicaRole::Source),
member(A, ReplicaRole::Destination),
member(C, ReplicaRole::Destination),
],
shared_key: GROUP_KEY.to_vec(),
}),
threshold: None,
}
}
fn payload(version: u32, author: Option<u64>, label: &str) -> ReplicaSecretPayload {
ReplicaSecretPayload {
secret: Some(state(label)),
shares: Vec::new(),
shared_key: Vec::new(),
version,
author_replica_id: author,
}
}
fn push(sender: u64, payload: &ReplicaSecretPayload) -> StoreShareRequestMessage {
StoreShareRequestMessage {
secret_id: SECRET_ID,
share: payload.encode_to_vec(),
version: payload.version,
version_description: String::new(),
share_algorithm: 0,
keep_version: 0,
replica_id: Some(sender),
reply_to_transports: Vec::new(),
timestamp: None,
}
}
async fn rig_holding_b_v2() -> (LocalFixture, StoreRig) {
let lf = LocalFixture::with_replica(SECRET_ID, A);
let mut rig = StoreRig::new();
for (id, role) in [
(B, ReplicaRole::Source),
(A, ReplicaRole::Destination),
(C, ReplicaRole::Destination),
] {
seed_member(&mut rig.channels, id, role, &format!("https://m{id}")).await;
}
let events = deliver(&mut rig, &lf, B, push(B, &payload(2, Some(B), "b"))).await;
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretInstalled { .. }]
),
"{events:?}"
);
(lf, rig)
}
async fn deliver(
rig: &mut StoreRig,
lf: &LocalFixture,
sender: u64,
request: StoreShareRequestMessage,
) -> Vec<DeRecEvent> {
let channel = rig
.channels
.load_replica_member(SECRET_ID, GROUP_CHANNEL, sender)
.await
.expect("seeded member");
on_request(
&mut rig.stores(),
&lf.local(),
&channel,
request,
GROUP_KEY,
0,
None,
)
.await
.expect("a sync is handled")
}
fn last_answer(rig: &StoreRig) -> (i32, u32) {
let envelope = rig
.transport
.sent_envelopes()
.pop()
.expect("an answer was sent");
let msg = DeRecMessage::decode(envelope.as_slice()).expect("envelope decodes");
match extract_inner_message(&msg.message, &GROUP_KEY).expect("answer decrypts") {
MessageBody::StoreShareResponse(r) => (r.result.expect("result").status, r.version),
other => panic!("expected a StoreShareResponse, got {other:?}"),
}
}
async fn held(rig: &StoreRig) -> (u32, Option<u64>, String) {
let snapshot = rig
.user_secrets
.load_latest(SECRET_ID)
.await
.expect("load")
.expect("a snapshot is held");
(
snapshot.version,
snapshot.author_replica_id,
snapshot.secrets[0].name.clone(),
)
}
#[test]
fn a_rival_copy_of_the_held_version_is_a_conflict_and_writes_nothing() {
run_async(async {
let (lf, mut rig) = rig_holding_b_v2().await;
let events = deliver(&mut rig, &lf, C, push(C, &payload(2, Some(C), "c"))).await;
match events.as_slice() {
[
DeRecEvent::ReplicaVersionConflict {
from_replica_id,
version,
held_author_replica_id,
incoming_author_replica_id,
secret,
..
},
] => {
assert_eq!(*from_replica_id, C);
assert_eq!(*version, 2);
assert_eq!(*held_author_replica_id, Some(B));
assert_eq!(*incoming_author_replica_id, Some(C));
assert_eq!(secret.secrets[0].name, "c", "the incoming state");
}
other => panic!("expected one ReplicaVersionConflict, got {other:?}"),
}
assert_eq!(
last_answer(&rig),
(StatusEnum::VersionConflict as i32, 2),
"the publisher is told its copy was refused"
);
assert_eq!(held(&rig).await, (2, Some(B), "b".to_owned()));
});
}
#[test]
fn the_same_author_resending_its_version_is_acknowledged_without_rewriting() {
run_async(async {
let (lf, mut rig) = rig_holding_b_v2().await;
let events =
deliver(&mut rig, &lf, B, push(B, &payload(2, Some(B), "b-again"))).await;
assert!(
matches!(events.as_slice(), [DeRecEvent::NoOp]),
"{events:?}"
);
assert_eq!(last_answer(&rig), (StatusEnum::Ok as i32, 2));
assert_eq!(held(&rig).await, (2, Some(B), "b".to_owned()));
});
}
async fn rig_holding_authorless_v2() -> (LocalFixture, StoreRig) {
let lf = LocalFixture::with_replica(SECRET_ID, A);
let mut rig = StoreRig::new();
for (id, role) in [
(B, ReplicaRole::Source),
(A, ReplicaRole::Destination),
(C, ReplicaRole::Destination),
] {
seed_member(&mut rig.channels, id, role, &format!("https://m{id}")).await;
}
let events = catch_up(&mut rig, &lf, &payload(2, None, "b")).await;
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretInstalled { .. }]
),
"{events:?}"
);
assert_eq!(held(&rig).await, (2, None, "b".to_owned()));
(lf, rig)
}
async fn catch_up(
rig: &mut StoreRig,
lf: &LocalFixture,
payload: &ReplicaSecretPayload,
) -> Vec<DeRecEvent> {
hydrate_catch_up(
&mut rig.stores(),
&lf.local(),
GROUP_CHANNEL,
B,
SECRET_ID,
payload.version,
&payload.encode_to_vec(),
)
.await
.expect("a catch-up is handled")
}
#[test]
fn the_same_secrets_resent_over_an_authorless_version_are_acknowledged() {
run_async(async {
let (lf, mut rig) = rig_holding_authorless_v2().await;
let events = deliver(&mut rig, &lf, B, push(B, &payload(2, Some(B), "b"))).await;
assert!(
matches!(events.as_slice(), [DeRecEvent::NoOp]),
"{events:?}"
);
assert_eq!(last_answer(&rig), (StatusEnum::Ok as i32, 2));
assert_eq!(held(&rig).await, (2, None, "b".to_owned()));
});
}
#[test]
fn a_repeated_authorless_catch_up_is_not_a_conflict() {
run_async(async {
let (lf, mut rig) = rig_holding_authorless_v2().await;
let events = catch_up(&mut rig, &lf, &payload(2, None, "b")).await;
assert!(
matches!(events.as_slice(), [DeRecEvent::NoOp]),
"{events:?}"
);
assert_eq!(held(&rig).await, (2, None, "b".to_owned()));
});
}
#[test]
fn different_secrets_over_an_authorless_version_are_a_conflict() {
run_async(async {
let (lf, mut rig) = rig_holding_authorless_v2().await;
let events = deliver(&mut rig, &lf, C, push(C, &payload(2, Some(C), "c"))).await;
match events.as_slice() {
[
DeRecEvent::ReplicaVersionConflict {
held_author_replica_id,
incoming_author_replica_id,
..
},
] => {
assert_eq!(*held_author_replica_id, None);
assert_eq!(*incoming_author_replica_id, Some(C));
}
other => panic!("expected one ReplicaVersionConflict, got {other:?}"),
}
assert_eq!(last_answer(&rig), (StatusEnum::VersionConflict as i32, 2));
assert_eq!(held(&rig).await, (2, None, "b".to_owned()));
});
}
#[test]
fn an_older_version_is_refused_and_writes_nothing() {
run_async(async {
let (lf, mut rig) = rig_holding_b_v2().await;
let events = deliver(&mut rig, &lf, C, push(C, &payload(1, Some(C), "old"))).await;
assert!(
matches!(events.as_slice(), [DeRecEvent::NoOp]),
"{events:?}"
);
assert_eq!(last_answer(&rig), (StatusEnum::VersionConflict as i32, 1));
assert_eq!(held(&rig).await, (2, Some(B), "b".to_owned()));
});
}
#[test]
fn a_newer_version_is_applied_and_its_author_stored() {
run_async(async {
let (lf, mut rig) = rig_holding_b_v2().await;
let events = deliver(&mut rig, &lf, C, push(C, &payload(3, Some(C), "c3"))).await;
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretReceived {
from_replica_id: C,
author_replica_id: Some(C),
version: 3,
..
}]
),
"{events:?}"
);
assert_eq!(held(&rig).await, (3, Some(C), "c3".to_owned()));
});
}
#[test]
fn a_push_that_does_not_name_its_author_is_attributed_to_its_sender() {
run_async(async {
let (lf, mut rig) = rig_holding_b_v2().await;
let events = deliver(&mut rig, &lf, C, push(C, &payload(3, None, "c3"))).await;
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretReceived {
author_replica_id: Some(C),
..
}]
),
"{events:?}"
);
assert_eq!(held(&rig).await.1, Some(C));
});
}
#[test]
fn a_pulled_copy_keeps_its_original_author() {
run_async(async {
let (lf, mut rig) = rig_holding_b_v2().await;
let events = hydrate_catch_up(
&mut rig.stores(),
&lf.local(),
GROUP_CHANNEL,
C,
SECRET_ID,
3,
&payload(3, Some(B), "b3").encode_to_vec(),
)
.await
.expect("catch-up hydrates");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretReceived {
from_replica_id: C,
author_replica_id: Some(B),
..
}]
),
"{events:?}"
);
assert_eq!(held(&rig).await, (3, Some(B), "b3".to_owned()));
});
}
#[test]
fn a_pulled_rival_copy_is_a_conflict_and_writes_nothing() {
run_async(async {
let (lf, mut rig) = rig_holding_b_v2().await;
let events = hydrate_catch_up(
&mut rig.stores(),
&lf.local(),
GROUP_CHANNEL,
B,
SECRET_ID,
2,
&payload(2, Some(C), "c").encode_to_vec(),
)
.await
.expect("catch-up is handled");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaVersionConflict {
held_author_replica_id: Some(B),
incoming_author_replica_id: Some(C),
..
}]
),
"{events:?}"
);
assert_eq!(held(&rig).await, (2, Some(B), "b".to_owned()));
});
}
#[test]
fn a_catch_up_answer_names_the_stored_author() {
run_async(async {
let (lf, mut rig) = rig_holding_b_v2().await;
let payload = build_catch_up_payload(&mut rig.stores(), &lf.local())
.await
.expect("payload builds")
.expect("a snapshot is held");
assert_eq!(payload.version, 2);
assert_eq!(payload.author_replica_id, Some(B));
});
}
}
#[test]
fn a_received_share_map_is_stored_for_verification() {
run_async(async {
use crate::protocol::DeRecShareStore as _;
use crate::protocol::types::{ChannelShare, HelperInfo, ReplicaInfo, Replicas};
const OWNER: u64 = 1001;
const SELF_ID: u64 = 1002;
const HELPER_CHANNEL: u64 = 77;
const VERSION: u32 = 3;
let split = request::split(
&[
(ChannelId(HELPER_CHANNEL), 1),
(ChannelId(HELPER_CHANNEL + 1), 1),
],
SECRET_ID,
VERSION,
b"the secret",
2,
)
.expect("split secret");
let committed = Message::encode_to_vec(
split
.shares
.get(&ChannelId(HELPER_CHANNEL))
.expect("share for helper"),
);
let lf = LocalFixture::with_replica(SECRET_ID, SELF_ID);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
OWNER,
ReplicaRole::Source,
"https://owner",
)
.await;
seed_member(
&mut rig.channels,
SELF_ID,
ReplicaRole::Destination,
"https://self",
)
.await;
let channel = rig
.channels
.load(
SECRET_ID,
ChannelQuery::Replica {
channel_id: GROUP_CHANNEL,
replica_id: ReplicaId(OWNER),
},
)
.await
.expect("load")
.and_then(|r| r.as_replica().cloned())
.expect("seeded member");
let payload = ReplicaSecretPayload {
secret: Some(Secret {
helpers: vec![HelperInfo {
channel_id: HELPER_CHANNEL,
transports: vec![endpoint("https://helper")],
shared_key: vec![0xAA; 32],
communication_info: HashMap::new(),
weight: 1,
}],
secrets: Vec::new(),
replicas: Some(Replicas {
channel_id: GROUP_CHANNEL.0,
members: vec![
ReplicaInfo {
replica_id: OWNER,
transports: vec![endpoint("https://owner")],
role: ReplicaRole::Source as i32,
communication_info: HashMap::new(),
},
ReplicaInfo {
replica_id: SELF_ID,
transports: vec![endpoint("https://self")],
role: ReplicaRole::Destination as i32,
communication_info: HashMap::new(),
},
],
shared_key: vec![0x42; 32],
}),
threshold: None,
}),
shares: vec![ChannelShare {
channel_id: HELPER_CHANNEL,
committed_share: committed.clone(),
}],
shared_key: Vec::new(),
version: VERSION,
author_replica_id: None,
};
let request = StoreShareRequestMessage {
secret_id: SECRET_ID,
share: Message::encode_to_vec(&payload),
version: VERSION,
version_description: String::new(),
share_algorithm: 0,
keep_version: 0,
replica_id: Some(OWNER),
reply_to_transports: Vec::new(),
timestamp: None,
};
super::on_request(
&mut rig.stores(),
&lf.local(),
&channel,
request,
[0x11; 32],
7,
None,
)
.await
.expect("the sync must be accepted");
let stored = rig
.shares
.load(SECRET_ID, ChannelId(HELPER_CHANNEL), &[VERSION])
.await
.expect("share store must answer");
assert_eq!(
stored.len(),
1,
"the mirrored share map must land in the share store, or verification \
of this helper has nothing to check against"
);
assert_eq!(
stored[0].bytes, committed,
"the tracked bytes must be the same CommittedDeRecShare the helper \
received, since that is what the helper hashes"
);
});
}
#[test]
fn a_share_map_naming_an_unknown_channel_is_refused() {
run_async(async {
use crate::protocol::types::{ChannelShare, HelperInfo, ReplicaInfo, Replicas};
const OWNER: u64 = 1001;
const SELF_ID: u64 = 1002;
let lf = LocalFixture::with_replica(SECRET_ID, SELF_ID);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
OWNER,
ReplicaRole::Source,
"https://owner",
)
.await;
let channel = rig
.channels
.load(
SECRET_ID,
ChannelQuery::Replica {
channel_id: GROUP_CHANNEL,
replica_id: ReplicaId(OWNER),
},
)
.await
.expect("load")
.and_then(|r| r.as_replica().cloned())
.expect("seeded member");
let payload = ReplicaSecretPayload {
secret: Some(Secret {
helpers: vec![HelperInfo {
channel_id: 77,
transports: vec![endpoint("https://helper")],
shared_key: vec![0xAA; 32],
communication_info: HashMap::new(),
weight: 1,
}],
secrets: Vec::new(),
replicas: Some(Replicas {
channel_id: GROUP_CHANNEL.0,
members: vec![ReplicaInfo {
replica_id: OWNER,
transports: vec![endpoint("https://owner")],
role: ReplicaRole::Source as i32,
communication_info: HashMap::new(),
}],
shared_key: vec![0x42; 32],
}),
threshold: None,
}),
shares: vec![ChannelShare {
channel_id: 78,
committed_share: vec![0x01],
}],
shared_key: Vec::new(),
version: 1,
author_replica_id: None,
};
let events = super::on_request(
&mut rig.stores(),
&lf.local(),
&channel,
StoreShareRequestMessage {
secret_id: SECRET_ID,
share: Message::encode_to_vec(&payload),
version: 1,
version_description: String::new(),
share_algorithm: 0,
keep_version: 0,
replica_id: Some(OWNER),
reply_to_transports: Vec::new(),
timestamp: None,
},
[0x11; 32],
7,
None,
)
.await
.expect("a refusal is an outcome, not an error");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretRefused { status, memo, .. }]
if *status == StatusEnum::FormatError as i32
&& memo.contains("absent from the roster")
),
"got {events:?}"
);
assert!(
rig.channels.helper_rows.lock().unwrap().is_empty(),
"the roster's helpers are not written either"
);
});
}
#[test]
fn a_payload_version_disagreeing_with_the_request_is_refused() {
run_async(async {
use crate::protocol::types::{ReplicaInfo, Replicas};
const OWNER: u64 = 1001;
const SELF_ID: u64 = 1002;
let lf = LocalFixture::with_replica(SECRET_ID, SELF_ID);
let mut rig = StoreRig::new();
seed_member(
&mut rig.channels,
OWNER,
ReplicaRole::Source,
"https://owner",
)
.await;
let channel = rig
.channels
.load(
SECRET_ID,
ChannelQuery::Replica {
channel_id: GROUP_CHANNEL,
replica_id: ReplicaId(OWNER),
},
)
.await
.expect("load")
.and_then(|r| r.as_replica().cloned())
.expect("seeded member");
let payload = ReplicaSecretPayload {
secret: Some(Secret {
helpers: Vec::new(),
secrets: Vec::new(),
replicas: Some(Replicas {
channel_id: GROUP_CHANNEL.0,
members: vec![ReplicaInfo {
replica_id: OWNER,
transports: vec![endpoint("https://owner")],
role: ReplicaRole::Source as i32,
communication_info: HashMap::new(),
}],
shared_key: vec![0x42; 32],
}),
threshold: None,
}),
shares: Vec::new(),
shared_key: Vec::new(),
version: 4,
author_replica_id: None,
};
let events = super::on_request(
&mut rig.stores(),
&lf.local(),
&channel,
StoreShareRequestMessage {
secret_id: SECRET_ID,
share: Message::encode_to_vec(&payload),
version: 5,
version_description: String::new(),
share_algorithm: 0,
keep_version: 0,
replica_id: Some(OWNER),
reply_to_transports: Vec::new(),
timestamp: None,
},
[0x11; 32],
7,
None,
)
.await
.expect("a refusal is an outcome, not an error");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretRefused { status, memo, .. }]
if *status == StatusEnum::FormatError as i32
&& memo.contains("version disagrees")
),
"got {events:?}"
);
});
}
mod refused_payload_tests {
use super::super::on_response;
use super::*;
use crate::derec_message::{DeRecMessageBuilder, current_timestamp, extract_inner_message};
use crate::primitives::sharing::request;
use crate::protocol::builder::DeRecProtocolBuilder;
use crate::protocol::tests::{
InMemSecretStore, InMemShareStore, InMemStateStore, InMemUserSecretStore,
RecordingTransport,
};
use crate::protocol::types::{
ChannelShare, HelperInfo, ReplicaInfo, ReplicaSecretPayload, Replicas, Secret,
};
use crate::protocol::{
DeRecEvent, DeRecFlow, DeRecProtocol, DeRecSecretStore as _, SecretKind, SecretValue,
};
use derec_proto::{
CommittedDeRecShare, DeRecMessage, DeRecResult, GetShareResponseMessage, MessageBody,
StatusEnum, StoreShareRequestMessage, StoreShareResponseMessage,
};
use std::collections::HashMap;
const SOURCE: u64 = 1001;
const SELF_ID: u64 = 1002;
const GROUP_KEY: [u8; 32] = [0x42; 32];
const HELPER_CHANNEL: u64 = 77;
const VERSION: u32 = 1;
type Destination = DeRecProtocol<
InMemChannelStore,
InMemShareStore,
InMemSecretStore,
InMemUserSecretStore,
InMemStateStore,
RecordingTransport,
>;
struct Rig {
protocol: Destination,
channels: InMemChannelStore,
shares: InMemShareStore,
secrets: InMemSecretStore,
user_secrets: InMemUserSecretStore,
transport: RecordingTransport,
}
async fn destination(auto_respond: bool) -> Rig {
let mut channels = InMemChannelStore::default();
let mut secrets = InMemSecretStore::default();
seed_member(&mut channels, SOURCE, ReplicaRole::Source, "https://source").await;
seed_member(
&mut channels,
SELF_ID,
ReplicaRole::Destination,
"https://self",
)
.await;
secrets
.save(SECRET_ID, GROUP_CHANNEL, SecretValue::SharedKey(GROUP_KEY))
.await
.expect("seed group key");
let shares = InMemShareStore::default();
let user_secrets = InMemUserSecretStore::default();
let transport = RecordingTransport::default();
let protocol = DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(channels.clone())
.with_share_store(shares.clone())
.with_secret_store(secrets.clone())
.with_user_secret_store(user_secrets.clone())
.with_transport(transport.clone())
.with_state_store(InMemStateStore)
.with_own_transports(["https://self"])
.with_threshold(2)
.with_replica_id(SELF_ID)
.with_auto_respond_on_failure(auto_respond)
.build()
.expect("test protocol builds");
Rig {
protocol,
channels,
shares,
secrets,
user_secrets,
transport,
}
}
fn roster(helper_channels: &[u64]) -> Secret {
let member = |replica_id, role: ReplicaRole, uri: &str| ReplicaInfo {
replica_id,
transports: vec![endpoint(uri)],
role: role as i32,
communication_info: HashMap::new(),
};
Secret {
helpers: helper_channels
.iter()
.map(|&channel_id| HelperInfo {
channel_id,
transports: vec![endpoint("https://helper")],
shared_key: vec![0xAA; 32],
communication_info: HashMap::new(),
weight: 1,
})
.collect(),
secrets: Vec::new(),
replicas: Some(Replicas {
channel_id: GROUP_CHANNEL.0,
members: vec![
member(SOURCE, ReplicaRole::Source, "https://source"),
member(SELF_ID, ReplicaRole::Destination, "https://self"),
],
shared_key: GROUP_KEY.to_vec(),
}),
threshold: None,
}
}
fn committed_share() -> CommittedDeRecShare {
let split = request::split(
&[
(ChannelId(HELPER_CHANNEL), 1),
(ChannelId(HELPER_CHANNEL + 1), 1),
],
SECRET_ID,
VERSION,
b"the secret",
2,
)
.expect("split secret");
split
.shares
.get(&ChannelId(HELPER_CHANNEL))
.expect("share for helper")
.clone()
}
fn payload(helper_channels: &[u64], shares: Vec<ChannelShare>) -> Vec<u8> {
ReplicaSecretPayload {
secret: Some(roster(helper_channels)),
shares,
shared_key: Vec::new(),
version: VERSION,
author_replica_id: Some(SOURCE),
}
.encode_to_vec()
}
fn push(share: Vec<u8>) -> Vec<u8> {
let timestamp = current_timestamp();
DeRecMessageBuilder::channel()
.channel_id(GROUP_CHANNEL)
.timestamp(timestamp)
.message_body(MessageBody::StoreShareRequest(StoreShareRequestMessage {
secret_id: SECRET_ID,
share,
version: VERSION,
replica_id: Some(SOURCE),
timestamp: Some(timestamp),
..Default::default()
}))
.encrypt(&GROUP_KEY)
.expect("encrypt")
.build()
.expect("build")
.encode_to_vec()
}
fn undecodable() -> Vec<u8> {
b"not a payload".to_vec()
}
fn unknown_channel() -> Vec<u8> {
payload(
&[HELPER_CHANNEL],
vec![ChannelShare {
channel_id: HELPER_CHANNEL + 1,
committed_share: committed_share().encode_to_vec(),
}],
)
}
fn unverifiable_share() -> Vec<u8> {
let mut share = committed_share();
share.merkle_path[0].hash[0] ^= 0xFF;
payload(
&[HELPER_CHANNEL],
vec![ChannelShare {
channel_id: HELPER_CHANNEL,
committed_share: share.encode_to_vec(),
}],
)
}
fn answer(rig: &Rig) -> StoreShareResponseMessage {
let sent = rig.transport.sent_envelopes();
assert_eq!(sent.len(), 1, "exactly one answer is sent to the publisher");
let msg = DeRecMessage::decode(sent[0].as_slice()).expect("envelope decodes");
match extract_inner_message(&msg.message, &GROUP_KEY).expect("answer decrypts") {
MessageBody::StoreShareResponse(r) => r,
other => panic!("expected a StoreShareResponse, got {other:?}"),
}
}
async fn assert_refused(share: Vec<u8>, expected: StatusEnum) {
for auto_respond in [true, false] {
let mut rig = destination(auto_respond).await;
let secrets_before = rig.secrets.data.lock().unwrap().len();
let events = rig
.protocol
.process(&push(share.clone()))
.await
.expect("a refused copy is an outcome, not an error");
let memo = match events.as_slice() {
[
DeRecEvent::ReplicaSecretRefused {
channel_id,
from_replica_id,
secret_id,
version,
status,
memo,
},
] => {
assert_eq!(*channel_id, GROUP_CHANNEL);
assert_eq!(*from_replica_id, SOURCE);
assert_eq!(*secret_id, SECRET_ID);
assert_eq!(*version, VERSION);
assert_eq!(*status, expected as i32, "auto_respond={auto_respond}");
assert!(!memo.is_empty());
memo.clone()
}
other => panic!(
"expected one ReplicaSecretRefused (auto_respond={auto_respond}), \
got {other:?}"
),
};
let response = answer(&rig);
let result = response.result.clone().expect("result");
assert_eq!(
result.status, expected as i32,
"auto_respond={auto_respond}"
);
assert_eq!(result.memo, memo, "the publisher is told the same reason");
assert_eq!(response.version, VERSION);
assert!(
rig.channels.helper_rows.lock().unwrap().is_empty(),
"no helper channel is written"
);
assert_eq!(
rig.channels.member_rows.lock().unwrap().len(),
2,
"no member is written"
);
assert_eq!(
rig.secrets.data.lock().unwrap().len(),
secrets_before,
"no key is written"
);
assert!(
rig.shares.data.lock().unwrap().is_empty(),
"no tracking share is written"
);
assert!(
rig.user_secrets.data.lock().unwrap().is_empty(),
"no snapshot is written"
);
let responder = ReplicaMember {
channel_id: GROUP_CHANNEL,
replica_id: ReplicaId(SELF_ID),
transports: vec![endpoint("https://self")],
communication_info: HashMap::new(),
role: ReplicaRole::Destination,
status: ChannelStatus::Paired,
created_at: 0,
handover_channel: None,
};
let seen = on_response(GROUP_CHANNEL, &responder, &response)
.expect("the answer is handled");
assert!(
matches!(
seen.as_slice(),
[DeRecEvent::ReplicaSyncRejected { replica_id: SELF_ID, version: VERSION, status, .. }]
if *status == expected as i32
),
"got {seen:?}"
);
}
}
#[test]
fn an_undecodable_payload_is_refused_as_a_format_error() {
run_async(assert_refused(undecodable(), StatusEnum::FormatError));
}
#[test]
fn a_share_map_naming_an_unlisted_helper_is_refused_before_anything_is_written() {
run_async(assert_refused(unknown_channel(), StatusEnum::FormatError));
}
#[test]
fn a_share_that_does_not_verify_is_refused_before_anything_is_written() {
run_async(assert_refused(
unverifiable_share(),
StatusEnum::VerificationFailed,
));
}
#[test]
fn a_roster_threshold_below_two_is_refused_as_a_format_error() {
let mut secret = roster(&[HELPER_CHANNEL]);
secret.threshold = Some(1);
let share = ReplicaSecretPayload {
secret: Some(secret),
shares: Vec::new(),
shared_key: Vec::new(),
version: VERSION,
author_replica_id: Some(SOURCE),
}
.encode_to_vec();
run_async(assert_refused(share, StatusEnum::FormatError));
}
#[test]
fn a_hydrated_threshold_is_stored_and_the_next_publish_uses_it() {
run_async(async {
let mut rig = destination(false).await;
let helpers = [HELPER_CHANNEL, HELPER_CHANNEL + 1, HELPER_CHANNEL + 2];
let mut secret = roster(&helpers);
secret.threshold = Some(3);
let share = ReplicaSecretPayload {
secret: Some(secret),
shares: vec![ChannelShare {
channel_id: HELPER_CHANNEL,
committed_share: committed_share().encode_to_vec(),
}],
shared_key: Vec::new(),
version: VERSION,
author_replica_id: Some(SOURCE),
}
.encode_to_vec();
rig.protocol.process(&push(share)).await.expect("hydrates");
use crate::protocol::DeRecUserSecretStore as _;
let snapshot = rig
.user_secrets
.load_latest(SECRET_ID)
.await
.unwrap()
.expect("snapshot hydrated");
assert_eq!(snapshot.threshold, Some(3));
let mirrored = rig
.shares
.data
.lock()
.unwrap()
.get(&(SECRET_ID, HELPER_CHANNEL, VERSION))
.cloned()
.expect("mirrored tracking share");
assert_eq!(mirrored.threshold, Some(3));
rig.protocol
.start(DeRecFlow::ProtectSecret {
secrets: Vec::new(),
description: None,
weights: HashMap::new(),
threshold: None,
})
.await
.expect("the hydrated device publishes");
for channel in helpers {
let row = rig
.shares
.data
.lock()
.unwrap()
.get(&(SECRET_ID, channel, VERSION + 1))
.cloned()
.expect("tracking share of the next version");
assert_eq!(row.threshold, Some(3), "helper {channel}");
}
});
}
const ADMITTER: u64 = SOURCE;
const EPHEMERAL: ChannelId = ChannelId(4242);
const EPHEMERAL_KEY: [u8; 32] = [0x11; 32];
async fn joiner() -> Rig {
let channels = InMemChannelStore::default();
let mut secrets = InMemSecretStore::default();
for (replica_id, role, uri) in [
(ADMITTER, ReplicaRole::Source, "https://source"),
(SELF_ID, ReplicaRole::Destination, "https://self"),
] {
channels
.clone()
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: EPHEMERAL,
replica_id: ReplicaId(replica_id),
transports: vec![endpoint(uri)],
communication_info: HashMap::new(),
role,
status: ChannelStatus::Paired,
created_at: 0,
handover_channel: None,
}),
)
.await
.expect("seed member");
}
secrets
.save(SECRET_ID, EPHEMERAL, SecretValue::SharedKey(EPHEMERAL_KEY))
.await
.expect("seed ephemeral key");
rig_with(channels, secrets, SELF_ID)
}
async fn admitter() -> Rig {
let mut channels = InMemChannelStore::default();
let mut secrets = InMemSecretStore::default();
seed_member(
&mut channels,
ADMITTER,
ReplicaRole::Source,
"https://source",
)
.await;
seed_member(
&mut channels,
SELF_ID,
ReplicaRole::Destination,
"https://self",
)
.await;
secrets
.save(SECRET_ID, GROUP_CHANNEL, SecretValue::SharedKey(GROUP_KEY))
.await
.expect("seed group key");
rig_with(channels, secrets, ADMITTER)
}
fn rig_with(
channels: InMemChannelStore,
secrets: InMemSecretStore,
replica_id: u64,
) -> Rig {
let shares = InMemShareStore::default();
let user_secrets = InMemUserSecretStore::default();
let transport = RecordingTransport::default();
let protocol = DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(channels.clone())
.with_share_store(shares.clone())
.with_secret_store(secrets.clone())
.with_user_secret_store(user_secrets.clone())
.with_transport(transport.clone())
.with_state_store(InMemStateStore)
.with_own_transports(["https://self"])
.with_threshold(2)
.with_replica_id(replica_id)
.build()
.expect("test protocol builds");
Rig {
protocol,
channels,
shares,
secrets,
user_secrets,
transport,
}
}
#[test]
fn a_refused_handover_is_answered_on_the_group_channel() {
run_async(async {
let mut joiner = joiner().await;
let mut share = committed_share();
share.merkle_path[0].hash[0] ^= 0xFF;
let handover = ReplicaSecretPayload {
secret: Some(roster(&[HELPER_CHANNEL])),
shares: vec![ChannelShare {
channel_id: HELPER_CHANNEL,
committed_share: share.encode_to_vec(),
}],
shared_key: GROUP_KEY.to_vec(),
version: VERSION,
author_replica_id: Some(ADMITTER),
};
let timestamp = current_timestamp();
let request = DeRecMessageBuilder::channel()
.channel_id(EPHEMERAL)
.timestamp(timestamp)
.message_body(MessageBody::StoreShareRequest(StoreShareRequestMessage {
secret_id: SECRET_ID,
share: handover.encode_to_vec(),
version: VERSION,
replica_id: Some(ADMITTER),
timestamp: Some(timestamp),
..Default::default()
}))
.encrypt(&EPHEMERAL_KEY)
.expect("encrypt")
.build()
.expect("build")
.encode_to_vec();
let secrets_before = joiner.secrets.data.lock().unwrap().len();
let events = joiner
.protocol
.process(&request)
.await
.expect("a refused handover is an outcome, not an error");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretRefused { channel_id: EPHEMERAL, status, .. }]
if *status == StatusEnum::VerificationFailed as i32
),
"{events:?}"
);
assert!(joiner.channels.helper_rows.lock().unwrap().is_empty());
assert_eq!(joiner.channels.member_rows.lock().unwrap().len(), 2);
assert_eq!(joiner.secrets.data.lock().unwrap().len(), secrets_before);
assert!(joiner.shares.data.lock().unwrap().is_empty());
assert!(joiner.user_secrets.data.lock().unwrap().is_empty());
let sent = joiner.transport.sent_envelopes();
assert_eq!(sent.len(), 1, "the refusal is sent");
let mut admitter = admitter().await;
let seen = admitter
.protocol
.process(&sent[0])
.await
.expect("the admitter reads the refusal");
assert!(
matches!(
seen.as_slice(),
[DeRecEvent::ReplicaSyncRejected { replica_id: SELF_ID, version: VERSION, status, memo, .. }]
if *status == StatusEnum::VerificationFailed as i32
&& memo == "CommittedDeRecShare Merkle proof verification failed"
),
"{seen:?}"
);
});
}
const OTHER: u64 = 1003;
fn group_roster() -> Secret {
let mut secret = roster(&[]);
if let Some(group) = secret.replicas.as_mut() {
group.members.push(ReplicaInfo {
replica_id: OTHER,
transports: vec![endpoint("https://other")],
role: ReplicaRole::Destination as i32,
communication_info: HashMap::new(),
});
}
secret
}
fn copy(channel: ChannelId, key: &[u8; 32], sender: u64, version: u32) -> Vec<u8> {
let payload = ReplicaSecretPayload {
secret: Some(group_roster()),
shares: Vec::new(),
shared_key: if channel == GROUP_CHANNEL {
Vec::new()
} else {
GROUP_KEY.to_vec()
},
version,
author_replica_id: Some(sender),
};
let timestamp = current_timestamp();
DeRecMessageBuilder::channel()
.channel_id(channel)
.timestamp(timestamp)
.message_body(MessageBody::StoreShareRequest(StoreShareRequestMessage {
secret_id: SECRET_ID,
share: payload.encode_to_vec(),
version,
replica_id: Some(sender),
timestamp: Some(timestamp),
..Default::default()
}))
.encrypt(key)
.expect("encrypt")
.build()
.expect("build")
.encode_to_vec()
}
fn member(rig: &Rig, replica_id: u64) -> ReplicaMember {
rig.channels
.member_rows
.lock()
.unwrap()
.get(&(SECRET_ID, replica_id))
.cloned()
.expect("member row")
}
fn holds_pairing_key(rig: &Rig) -> bool {
rig.secrets.data.lock().unwrap().contains_key(&(
SECRET_ID,
EPHEMERAL.0,
SecretKind::SharedKey as u8,
))
}
fn last_sent_channel(rig: &Rig) -> ChannelId {
let sent = rig.transport.sent_envelopes();
let last = sent.last().expect("something was sent");
ChannelId(
DeRecMessage::decode(last.as_slice())
.expect("envelope")
.channel_id,
)
}
async fn handed_over() -> Rig {
let mut joiner = joiner().await;
joiner
.protocol
.process(©(EPHEMERAL, &EPHEMERAL_KEY, ADMITTER, VERSION))
.await
.expect("the handover installs");
joiner
}
#[test]
fn a_handover_records_the_pairing_channel_on_the_admitters_row() {
run_async(async {
let joiner = handed_over().await;
for id in [ADMITTER, SELF_ID, OTHER] {
assert_eq!(member(&joiner, id).channel_id, GROUP_CHANNEL, "member {id}");
}
assert_eq!(member(&joiner, ADMITTER).handover_channel, Some(EPHEMERAL));
assert_eq!(member(&joiner, SELF_ID).handover_channel, None);
assert_eq!(member(&joiner, OTHER).handover_channel, None);
assert!(holds_pairing_key(&joiner));
assert_eq!(last_sent_channel(&joiner), GROUP_CHANNEL, "the ack");
});
}
#[test]
fn a_copy_resent_on_the_pairing_channel_is_answered_on_the_group_channel() {
run_async(async {
let mut joiner = handed_over().await;
let events = joiner
.protocol
.process(©(EPHEMERAL, &EPHEMERAL_KEY, ADMITTER, VERSION))
.await
.expect("the resent copy is read");
assert!(
matches!(events.as_slice(), [DeRecEvent::NoOp]),
"{events:?}"
);
assert_eq!(joiner.transport.sent_envelopes().len(), 2);
assert_eq!(last_sent_channel(&joiner), GROUP_CHANNEL);
assert!(holds_pairing_key(&joiner));
});
}
#[test]
fn a_newer_copy_on_the_pairing_channel_is_installed() {
run_async(async {
let mut joiner = handed_over().await;
let events = joiner
.protocol
.process(©(EPHEMERAL, &EPHEMERAL_KEY, ADMITTER, VERSION + 1))
.await
.expect("the newer copy is read");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretReceived { version, .. }] if *version == VERSION + 1
),
"{events:?}"
);
assert_eq!(last_sent_channel(&joiner), GROUP_CHANNEL);
assert_eq!(member(&joiner, ADMITTER).handover_channel, Some(EPHEMERAL));
assert!(holds_pairing_key(&joiner));
});
}
#[test]
fn the_admitters_first_message_on_the_group_channel_drops_the_pairing_key() {
run_async(async {
let mut joiner = handed_over().await;
joiner
.protocol
.process(©(GROUP_CHANNEL, &GROUP_KEY, ADMITTER, VERSION + 1))
.await
.expect("the copy on the group channel is read");
assert_eq!(member(&joiner, ADMITTER).channel_id, GROUP_CHANNEL);
assert_eq!(member(&joiner, ADMITTER).handover_channel, None);
assert!(!holds_pairing_key(&joiner));
assert!(
joiner
.protocol
.process(©(EPHEMERAL, &EPHEMERAL_KEY, ADMITTER, VERSION + 2))
.await
.is_err(),
"nothing is read on the dropped channel"
);
});
}
#[test]
fn another_members_message_on_the_group_channel_keeps_the_pairing_key() {
run_async(async {
let mut joiner = handed_over().await;
joiner
.protocol
.process(©(GROUP_CHANNEL, &GROUP_KEY, OTHER, VERSION + 1))
.await
.expect("the other member's copy is read");
assert_eq!(member(&joiner, ADMITTER).handover_channel, Some(EPHEMERAL));
assert!(holds_pairing_key(&joiner));
joiner
.protocol
.process(©(EPHEMERAL, &EPHEMERAL_KEY, ADMITTER, VERSION + 2))
.await
.expect("the admitter's copy on the pairing channel is still read");
});
}
#[test]
fn another_member_named_on_the_pairing_channel_is_refused() {
run_async(async {
let mut joiner = handed_over().await;
let events = joiner
.protocol
.process(©(EPHEMERAL, &EPHEMERAL_KEY, OTHER, VERSION + 1))
.await
.expect("a refusal is an outcome");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::RequestFailed { message, .. }]
if message.contains("names a member that is not in the group")
),
"{events:?}"
);
assert_eq!(
joiner.user_secrets.data.lock().unwrap()[&SECRET_ID].version,
VERSION
);
});
}
#[test]
fn the_joiner_publishes_to_the_admitter_on_the_group_channel() {
run_async(async {
let mut joiner = handed_over().await;
joiner
.protocol
.start(DeRecFlow::ProtectSecret {
secrets: Vec::new(),
description: None,
weights: HashMap::new(),
threshold: None,
})
.await
.expect("the joiner publishes");
let sent = joiner.transport.sent_envelopes();
let uris = joiner.transport.sent_uris();
let to_admitter = uris
.iter()
.rposition(|uri| uri == "https://source")
.expect("a copy for the admitter");
let envelope =
DeRecMessage::decode(sent[to_admitter].as_slice()).expect("envelope");
assert_eq!(ChannelId(envelope.channel_id), GROUP_CHANNEL);
assert!(extract_inner_message(&envelope.message, &GROUP_KEY).is_ok());
});
}
#[test]
fn a_refused_catch_up_copy_is_reported_and_writes_nothing() {
run_async(async {
let mut rig = destination(false).await;
let secrets_before = rig.secrets.data.lock().unwrap().len();
let timestamp = current_timestamp();
let response = DeRecMessageBuilder::channel()
.channel_id(GROUP_CHANNEL)
.timestamp(timestamp)
.message_body(MessageBody::GetShareResponse(GetShareResponseMessage {
result: Some(DeRecResult {
status: StatusEnum::Ok as i32,
memo: String::new(),
}),
committed_de_rec_share: unverifiable_share(),
share_algorithm: request::SHARE_ALGORITHM_REPLICA_SECRET,
timestamp: Some(timestamp),
secret_id: SECRET_ID,
version: VERSION,
replica_id: Some(SOURCE),
}))
.encrypt(&GROUP_KEY)
.expect("encrypt")
.build()
.expect("build")
.encode_to_vec();
let events = rig
.protocol
.process(&response)
.await
.expect("a refused copy is an outcome, not an error");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretRefused {
channel_id: GROUP_CHANNEL,
from_replica_id: SOURCE,
secret_id: SECRET_ID,
version: VERSION,
status,
memo,
}] if *status == StatusEnum::VerificationFailed as i32
&& memo == "CommittedDeRecShare Merkle proof verification failed"
),
"{events:?}"
);
assert!(
rig.transport.sent_envelopes().is_empty(),
"nothing is answered"
);
assert!(rig.channels.helper_rows.lock().unwrap().is_empty());
assert_eq!(rig.channels.member_rows.lock().unwrap().len(), 2);
assert_eq!(rig.secrets.data.lock().unwrap().len(), secrets_before);
assert!(rig.shares.data.lock().unwrap().is_empty());
assert!(rig.user_secrets.data.lock().unwrap().is_empty());
});
}
#[test]
fn a_valid_payload_hydrates_in_full() {
run_async(async {
let mut rig = destination(false).await;
let committed = committed_share().encode_to_vec();
let share = payload(
&[HELPER_CHANNEL],
vec![ChannelShare {
channel_id: HELPER_CHANNEL,
committed_share: committed.clone(),
}],
);
let events = rig.protocol.process(&push(share)).await.expect("hydrates");
assert!(
matches!(
events.as_slice(),
[DeRecEvent::ReplicaSecretInstalled { .. }]
),
"{events:?}"
);
assert_eq!(
answer(&rig).result.expect("result").status,
StatusEnum::Ok as i32
);
assert_eq!(rig.channels.helper_rows.lock().unwrap().len(), 1);
let stored: Vec<Vec<u8>> = rig
.shares
.data
.lock()
.unwrap()
.values()
.map(|s| s.bytes.clone())
.collect();
assert_eq!(stored, vec![committed]);
assert_eq!(rig.user_secrets.data.lock().unwrap().len(), 1);
});
}
}
async fn roster_with_source(source_id: u64) -> Secret {
let mut rig = StoreRig::new();
for id in [1001u64, 1002] {
let role = if id == source_id {
ReplicaRole::Source
} else {
ReplicaRole::Destination
};
seed_member(&mut rig.channels, id, role, "https://peer").await;
}
let roster = rig
.channels
.replicas(SECRET_ID, ReplicaFilter::default())
.await
.expect("roster");
build_secret(
&[],
&roster,
Vec::new(),
Some(GROUP_CHANNEL),
Some([0x42; 32]),
None,
)
.expect("build secret")
}
#[test]
fn a_roster_that_promotes_this_device_reports_it() {
run_async(async {
let lf = LocalFixture::with_replica(0, 1002);
let secret = roster_with_source(1002).await;
let event = super::promotion_event(&lf.local(), false, &secret);
assert!(
matches!(
event,
Some(DeRecEvent::ReplicaSourceChanged { replica_id })
if replica_id == 1002
),
"got {event:?}"
);
});
}
#[test]
fn an_unchanged_source_is_not_reported_again() {
run_async(async {
let lf = LocalFixture::with_replica(0, 1002);
let secret = roster_with_source(1002).await;
assert!(
super::promotion_event(&lf.local(), true, &secret).is_none(),
"only the transition is an event"
);
});
}
#[test]
fn a_destination_is_not_promoted() {
run_async(async {
let lf = LocalFixture::with_replica(0, 1002);
let secret = roster_with_source(1001).await;
assert!(super::promotion_event(&lf.local(), false, &secret).is_none());
});
}
}