pub mod error;
pub mod events;
pub mod traits;
pub mod types;
pub mod utils;
mod builder;
mod handlers;
#[cfg(test)]
mod test;
use crate::{
Error, Result, primitives::pairing::request::create_contact as create_contact_message,
types::ChannelId,
};
pub use builder::{DEFAULT_KEEP_VERSIONS_COUNT, DEFAULT_THRESHOLD, DeRecProtocolBuilder};
use derec_proto::{ContactMessage, ContactMode, DeRecMessage, StatusEnum, TransportProtocol};
pub use error::{
ChannelStoreError, ProcessError, SecretStoreError, ShareStoreError, StateStoreError,
};
use prost::Message;
use std::collections::{HashMap, HashSet};
pub use traits::{
ChannelStoreFuture, DeRecChannelStore, DeRecSecretStore, DeRecShareStore, DeRecStateStore,
DeRecTransport, DeRecUserSecretStore, SecretStoreFuture, ShareStoreFuture, StateStoreFuture,
TransportFuture,
};
pub use types::{
ChannelQuery, ChannelRecord, ChannelShare, ChannelStatus, ExpiredChannelCleanup, HelperChannel,
HelperInfo, MissingPolicy, PairingKeyMaterial, ReplicaInfo, ReplicaMember, ReplicaRole,
ReplicaSecretPayload, Secret, SecretKind, SecretValue, Share, StateItem, StateKey, StateKind,
Target, UserSecret, UserSecrets,
};
pub use events::{
AutoAcceptPolicy, DeRecEvent, DeRecFlow, PendingAction, PendingActionKind, UnpairAck,
};
pub use handlers::restore::RestoreError;
#[cfg(target_arch = "wasm32")]
use crate::interop::wasm::now_secs;
#[cfg(not(target_arch = "wasm32"))]
use crate::utils::now_secs;
pub struct DeRecProtocol<
ChannelStore: DeRecChannelStore,
ShareStore: DeRecShareStore,
SecretStore: DeRecSecretStore,
UserSecretStore: DeRecUserSecretStore,
StateStore: DeRecStateStore,
Transport: DeRecTransport,
> {
pub channel_store: ChannelStore,
pub share_store: ShareStore,
pub secret_store: SecretStore,
pub user_secret_store: UserSecretStore,
pub state_store: StateStore,
pub transport: Transport,
pub own_transport: TransportProtocol,
pub(crate) unpair_ack: UnpairAck,
threshold: usize,
keep_versions_count: usize,
pub(crate) timeouts: crate::protocol::types::Timeouts,
pub(crate) unsafe_http: bool,
pub(crate) communication_info: HashMap<String, String>,
pub(crate) auto_respond_on_failure: bool,
pub(crate) auto_reply_to: bool,
pub(crate) auto_accept: AutoAcceptPolicy,
pub(crate) replica_id: Option<u64>,
pub(crate) parameter_range: Option<derec_proto::ParameterRange>,
secret_id: u64,
}
impl<
Ch: DeRecChannelStore,
Sh: DeRecShareStore,
Ss: DeRecSecretStore,
Us: DeRecUserSecretStore,
T: DeRecTransport,
St: DeRecStateStore,
> DeRecProtocol<Ch, Sh, Ss, Us, St, T>
{
#[allow(clippy::too_many_arguments)]
pub fn new(
secret_id: u64,
channel_store: Ch,
share_store: Sh,
secret_store: Ss,
user_secret_store: Us,
state_store: St,
transport: T,
own_transport: TransportProtocol,
threshold: usize,
keep_versions_count: usize,
timeouts: crate::protocol::types::Timeouts,
) -> Result<Self> {
if threshold < 2 {
return Err(crate::Error::InvalidInput(
"threshold must be >= 2; 0 or 1 lets a single helper reconstruct the secret \
and defeats threshold sharing",
));
}
Ok(Self {
channel_store,
share_store,
secret_store,
user_secret_store,
state_store,
transport,
own_transport,
unpair_ack: UnpairAck::Required,
threshold,
keep_versions_count,
timeouts,
unsafe_http: false,
communication_info: HashMap::new(),
auto_respond_on_failure: false,
auto_reply_to: false,
auto_accept: AutoAcceptPolicy::default(),
replica_id: None,
parameter_range: None,
secret_id,
})
}
pub fn secret_id(&self) -> u64 {
self.secret_id
}
pub fn replica_id(&self) -> Option<u64> {
self.replica_id
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
pub async fn create_contact(
&mut self,
channel_id: Option<ChannelId>,
contact_mode: ContactMode,
nonce: Option<u64>,
) -> Result<ContactMessage> {
let channel_id = channel_id.unwrap_or_else(|| ChannelId(rand::random::<u64>()));
#[cfg(feature = "logging")]
tracing::debug!(
channel_id = channel_id.0,
contact_mode = contact_mode as i32,
"creating contact message"
);
let result =
create_contact_message(channel_id, contact_mode, self.own_transport.clone(), nonce)?;
match result.secret_key {
Some(secret_key) => {
self.secret_store
.save(
self.secret_id,
channel_id,
SecretValue::PairingSecret(PairingKeyMaterial::from_secret(&secret_key)),
)
.await?;
}
None => {
self.secret_store
.save(
self.secret_id,
channel_id,
SecretValue::PairingContact(result.contact_message.clone()),
)
.await?;
}
}
#[cfg(feature = "logging")]
tracing::info!(channel_id = channel_id.0, "contact message created");
Ok(result.contact_message)
}
pub fn set_communication_info(&mut self, info: HashMap<String, String>) {
self.communication_info = info;
}
pub fn set_own_transport(
&mut self,
own_transport: impl crate::transport::IntoOwnTransport,
) -> crate::Result<()> {
let tp = own_transport.into_own_transport()?;
self.own_transport = tp.into();
Ok(())
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
pub async fn start(&mut self, flow: DeRecFlow) -> Result<Vec<DeRecEvent>> {
let reply_to = self.auto_reply_to.then(|| self.own_transport.clone());
match flow {
DeRecFlow::Pairing {
kind,
contact,
peer_communication_info,
} => {
self.start_pairing(kind, contact, peer_communication_info)
.await
}
DeRecFlow::Discovery { target } => self.start_discovery(target, reply_to).await,
DeRecFlow::ProtectSecret {
secrets,
description,
} => {
self.start_protect_secret(secrets, description, reply_to)
.await
}
DeRecFlow::VerifyShares {
secret_id,
version,
target,
} => {
self.start_verify_shares(secret_id, version, target, reply_to)
.await
}
DeRecFlow::RecoverSecret { secret_id, version } => {
self.start_recover_secret(secret_id, version, reply_to)
.await
}
DeRecFlow::SyncCheck => {
handlers::sync_check::start(
&mut self.channel_store,
&mut self.secret_store,
&self.user_secret_store,
&mut self.state_store,
&self.transport,
self.secret_id,
self.replica_id,
&self.own_transport,
)
.await
}
DeRecFlow::RemoveReplica { replica_id, memo } => {
handlers::remove_replica::start(
&mut self.channel_store,
&mut self.secret_store,
&self.transport,
self.secret_id,
replica_id,
memo,
self.replica_id,
)
.await
}
DeRecFlow::Unpair { channel_id, memo } => {
self.start_unpair(channel_id, memo, reply_to).await
}
DeRecFlow::UpdateChannelInfo {
target,
communication_info,
transport_protocol,
} => {
self.start_update_channel_info(target, communication_info, transport_protocol)
.await
}
}
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
pub async fn accept(&mut self, action: PendingAction) -> Result<Vec<DeRecEvent>> {
let mut events = self.accept_inner(action).await?;
let auto_publish_events = self.maybe_auto_publish_after_pair(&events).await?;
events.extend(auto_publish_events);
Ok(events)
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
pub async fn reject(
&mut self,
action: PendingAction,
status: StatusEnum,
memo: &str,
) -> Result<()> {
match action {
PendingAction::Pairing {
channel_id,
request,
trace_id,
..
} => {
handlers::pairing::reject(
&mut self.secret_store,
&self.transport,
&self.communication_info,
self.secret_id,
channel_id,
&request,
status,
memo,
trace_id,
)
.await
}
PendingAction::StoreShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::sharing::reject(
&mut self.channel_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
status,
memo,
trace_id,
self.replica_id,
)
.await
}
PendingAction::VerifyShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::verification::reject(
&mut self.channel_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
status,
memo,
trace_id,
)
.await
}
PendingAction::Discovery {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::discovery::reject(
&mut self.channel_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
status,
memo,
trace_id,
self.replica_id,
)
.await
}
PendingAction::GetShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::recovery::reject(
&mut self.channel_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
status,
memo,
trace_id,
self.replica_id,
)
.await
}
PendingAction::Unpair {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::unpairing::reject(
&mut self.channel_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
status,
memo,
trace_id,
)
.await
}
PendingAction::UpdateChannelInfo {
channel_id,
shared_key,
trace_id,
..
} => {
handlers::update_channel_info::reject(
&mut self.channel_store,
&self.transport,
self.secret_id,
channel_id,
&shared_key,
status,
memo,
trace_id,
)
.await
}
PendingAction::PrePair {
channel_id,
request,
trace_id,
} => {
handlers::pairing::reject_pre_pair(
&self.transport,
channel_id,
&request,
status,
memo,
trace_id,
)
.await
}
}
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(message_len = message.len()))
)]
pub async fn process(
&mut self,
message: &[u8],
) -> std::result::Result<Vec<DeRecEvent>, ProcessError> {
let mut timeout_events = self.run_timeout_sweeps().await;
let envelope = DeRecMessage::decode(message).map_err(|e| ProcessError {
channel_id: None,
source: Error::ProtobufDecode(e),
})?;
let channel_id = ChannelId(envelope.channel_id);
let result = self.process_inner(&envelope, channel_id).await;
let mut events = result.map_err(|source| ProcessError {
channel_id: Some(channel_id),
source,
})?;
events = self
.apply_auto_accept(events)
.await
.map_err(|source| ProcessError {
channel_id: Some(channel_id),
source,
})?;
timeout_events.append(&mut events);
let mut events = timeout_events;
self.update_sharing_round(&mut events).await;
let auto_publish_events =
self.maybe_auto_publish_after_pair(&events)
.await
.map_err(|source| ProcessError {
channel_id: Some(channel_id),
source,
})?;
events.extend(auto_publish_events);
Ok(events)
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(channel_id = channel_id.0)))]
pub async fn get_fingerprint(&self, channel_id: ChannelId) -> Result<String> {
let shared_key = match self
.secret_store
.load(self.secret_id, channel_id, SecretKind::SharedKey)
.await?
{
Some(SecretValue::SharedKey(key)) => key,
_ => {
return Err(Error::InvalidInput(
"channel has no shared key — not yet paired",
));
}
};
Ok(derec_cryptography::replica::fingerprint(&shared_key))
}
pub(crate) fn transport_policy(&self) -> crate::transport::TransportPolicy {
crate::transport::TransportPolicy::new(self.unsafe_http)
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(channel_id = channel_id.0)))]
pub async fn verify_fingerprint(
&mut self,
channel_id: ChannelId,
fingerprint: &str,
) -> Result<bool> {
let local = self.get_fingerprint(channel_id).await?;
if local != fingerprint {
return Ok(false);
}
let mut transitioned_helper = false;
if let Some(record) = self
.channel_store
.load(
self.secret_id,
crate::protocol::types::ChannelQuery::Helper { channel_id },
)
.await?
&& let Some(helper) = record.as_helper()
&& helper.status == crate::protocol::types::ChannelStatus::Pending
{
let mut helper = helper.clone();
helper.status = crate::protocol::types::ChannelStatus::Paired;
self.channel_store
.save(
self.secret_id,
crate::protocol::types::ChannelRecord::Helper(helper),
)
.await?;
transitioned_helper = true;
}
let mut transitioned_replica = false;
let members = self.channel_store.replicas(self.secret_id).await?;
for mut member in members {
if member.channel_id != channel_id
|| member.status != crate::protocol::types::ChannelStatus::Pending
{
continue;
}
if member.role == crate::protocol::types::ReplicaRole::Destination
&& Some(member.replica_id.0) != self.replica_id
{
transitioned_replica = true;
}
member.status = crate::protocol::types::ChannelStatus::Paired;
self.channel_store
.save(
self.secret_id,
crate::protocol::types::ChannelRecord::Replica(member),
)
.await?;
}
if transitioned_replica || transitioned_helper {
let snapshot = self.user_secret_store.load_latest(self.secret_id).await?;
let payload = match snapshot {
Some(s) => Some((s.secrets, s.description)),
None if transitioned_replica || self.has_paired_replica_destination().await? => {
Some((Vec::new(), None))
}
None => None,
};
if let Some((secrets, description)) = payload {
let reply_to = self.auto_reply_to.then(|| self.own_transport.clone());
self.publish_secret(secrets, description, reply_to).await?;
}
}
Ok(true)
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
pub async fn restore(
&mut self,
secret: &crate::protocol::types::Secret,
recovered_version: u32,
) -> Result<Vec<DeRecEvent>> {
handlers::restore::restore(
&mut self.channel_store,
&mut self.share_store,
&mut self.secret_store,
&mut self.user_secret_store,
&self.transport,
&mut self.state_store,
self.secret_id,
secret,
recovered_version,
)
.await
}
async fn start_pairing(
&mut self,
kind: derec_proto::SenderKind,
contact: derec_proto::ContactMessage,
peer_communication_info: HashMap<String, String>,
) -> Result<Vec<DeRecEvent>> {
let channel_id = handlers::pairing::start(
&mut self.channel_store,
&mut self.secret_store,
&self.transport,
&self.own_transport,
&self.communication_info,
self.secret_id,
kind,
contact,
peer_communication_info,
self.replica_id,
self.parameter_range,
)
.await?;
Ok(vec![DeRecEvent::PairingStarted {
channel_id: ChannelId(channel_id),
kind,
}])
}
async fn start_discovery(
&mut self,
target: crate::protocol::types::Target,
reply_to: Option<derec_proto::TransportProtocol>,
) -> Result<Vec<DeRecEvent>> {
let resolved =
handlers::resolve_target(&mut self.channel_store, self.secret_id, target.clone())
.await?;
handlers::require_role(
&self.channel_store,
self.secret_id,
&resolved,
derec_proto::SenderKind::Helper,
)
.await?;
handlers::discovery::start(
&mut self.channel_store,
&mut self.secret_store,
&self.transport,
self.secret_id,
target,
reply_to,
)
.await
}
async fn start_protect_secret(
&mut self,
secrets: Vec<crate::protocol::types::UserSecret>,
description: Option<String>,
reply_to: Option<derec_proto::TransportProtocol>,
) -> Result<Vec<DeRecEvent>> {
self.publish_secret(secrets, description, reply_to).await
}
async fn publish_secret(
&mut self,
secrets: Vec<crate::protocol::types::UserSecret>,
description: Option<String>,
reply_to: Option<derec_proto::TransportProtocol>,
) -> Result<Vec<DeRecEvent>> {
let Some(round) = handlers::sharing::start(
&mut self.channel_store,
&mut self.share_store,
&mut self.secret_store,
&mut self.user_secret_store,
&self.transport,
secrets,
description,
self.threshold,
self.keep_versions_count,
self.secret_id,
&self.own_transport,
reply_to,
self.replica_id,
)
.await?
else {
return Ok(Vec::new());
};
let version = round.version;
let pending: HashSet<ChannelId> = round
.outcomes
.iter()
.filter_map(|(cid, r)| r.as_ref().ok().map(|_| *cid))
.collect();
let pending_replicas: HashSet<crate::types::ReplicaId> = round
.replica_outcomes
.iter()
.filter_map(|(rid, r)| r.as_ref().ok().map(|_| *rid))
.collect();
let behind_replicas: HashSet<crate::types::ReplicaId> = round
.replica_outcomes
.iter()
.filter_map(|(rid, r)| r.as_ref().err().map(|_| *rid))
.collect();
let mut undeliverable: Vec<DeRecEvent> = round
.replica_outcomes
.iter()
.filter_map(|(rid, r)| {
r.as_ref().err().map(|e| DeRecEvent::ReplicaSyncFailed {
replica_id: rid.0,
version,
reason: e.to_string(),
})
})
.collect();
if !pending.is_empty() || !pending_replicas.is_empty() {
self.state_store
.save(
self.secret_id,
StateItem::SharingRound(Box::new(crate::protocol::types::SharingRoundState {
version,
pending,
confirmed: HashSet::new(),
failed: HashSet::new(),
pending_replicas,
synced_replicas: HashSet::new(),
behind_replicas,
started_at: now_secs(),
})),
)
.await?;
}
let mut started: Vec<DeRecEvent> = round
.outcomes
.into_iter()
.map(|(channel_id, res)| match res {
Ok(()) => DeRecEvent::ProtectSecretStarted {
channel_id,
version,
},
Err(e) => DeRecEvent::ProtectSecretFailed {
channel_id,
version,
error: e.to_string(),
},
})
.collect();
started.append(&mut undeliverable);
Ok(started)
}
async fn start_verify_shares(
&mut self,
secret_id: u64,
version: u32,
target: crate::protocol::types::Target,
reply_to: Option<derec_proto::TransportProtocol>,
) -> Result<Vec<DeRecEvent>> {
let resolved =
handlers::resolve_target(&mut self.channel_store, self.secret_id, target.clone())
.await?;
handlers::require_role(
&self.channel_store,
self.secret_id,
&resolved,
derec_proto::SenderKind::Helper,
)
.await?;
handlers::verification::start(
&mut self.channel_store,
&mut self.secret_store,
&self.transport,
&mut self.state_store,
version,
target,
secret_id,
reply_to,
)
.await
}
async fn start_recover_secret(
&mut self,
secret_id: u64,
version: u32,
reply_to: Option<derec_proto::TransportProtocol>,
) -> Result<Vec<DeRecEvent>> {
handlers::recovery::start(
&mut self.channel_store,
&mut self.secret_store,
&mut self.state_store,
&self.transport,
self.secret_id,
secret_id,
version,
reply_to,
)
.await
}
async fn start_unpair(
&mut self,
channel_id: ChannelId,
memo: Option<String>,
reply_to: Option<derec_proto::TransportProtocol>,
) -> Result<Vec<DeRecEvent>> {
handlers::require_role(
&self.channel_store,
self.secret_id,
&[channel_id],
derec_proto::SenderKind::Helper,
)
.await?;
let mut events = vec![DeRecEvent::UnpairStarted { channel_id }];
events.extend(
handlers::unpairing::start(
&mut self.channel_store,
&mut self.share_store,
&mut self.secret_store,
&self.transport,
&mut self.state_store,
self.secret_id,
channel_id,
memo,
self.unpair_ack,
now_secs(),
reply_to,
)
.await?,
);
Ok(events)
}
async fn start_update_channel_info(
&mut self,
target: crate::protocol::types::Target,
communication_info: Option<HashMap<String, String>>,
transport_protocol: Option<derec_proto::TransportProtocol>,
) -> Result<Vec<DeRecEvent>> {
handlers::update_channel_info::start(
&mut self.channel_store,
&mut self.secret_store,
&self.transport,
self.secret_id,
target,
communication_info,
transport_protocol,
)
.await
}
async fn accept_inner(&mut self, action: PendingAction) -> Result<Vec<DeRecEvent>> {
match action {
PendingAction::Pairing {
channel_id,
request,
kind,
trace_id,
..
} => {
handlers::pairing::accept(
&mut self.channel_store,
&mut self.secret_store,
&self.transport,
&self.own_transport,
&self.communication_info,
self.secret_id,
channel_id,
&request,
kind,
trace_id,
self.replica_id,
self.parameter_range,
)
.await
}
PendingAction::StoreShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::sharing::accept(
&mut self.channel_store,
&mut self.share_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
trace_id,
self.replica_id,
)
.await
}
PendingAction::VerifyShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::verification::accept(
&mut self.channel_store,
&mut self.share_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
trace_id,
)
.await
}
PendingAction::Discovery {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::discovery::accept(
&mut self.channel_store,
&mut self.share_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
trace_id,
)
.await
}
PendingAction::GetShare {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::recovery::accept(
&mut self.channel_store,
&mut self.share_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
trace_id,
)
.await
}
PendingAction::Unpair {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::unpairing::accept(
&mut self.channel_store,
&mut self.share_store,
&mut self.secret_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
trace_id,
)
.await
}
PendingAction::UpdateChannelInfo {
channel_id,
request,
shared_key,
trace_id,
} => {
handlers::update_channel_info::accept(
&mut self.channel_store,
&self.transport,
self.secret_id,
channel_id,
&request,
&shared_key,
trace_id,
)
.await
}
PendingAction::PrePair {
channel_id,
request,
trace_id,
} => {
handlers::pairing::accept_pre_pair(
&mut self.secret_store,
&self.transport,
self.secret_id,
channel_id,
&request,
trace_id,
)
.await
}
}
}
async fn maybe_auto_publish_after_pair(
&mut self,
events: &[DeRecEvent],
) -> Result<Vec<DeRecEvent>> {
let mut a_usable_helper_just_paired = false;
for event in events {
let DeRecEvent::PairingCompleted {
kind: derec_proto::SenderKind::Owner,
channel_id,
..
} = event
else {
continue;
};
if self
.channel_store
.load(
self.secret_id,
crate::protocol::types::ChannelQuery::Helper {
channel_id: *channel_id,
},
)
.await?
.is_some_and(|record| {
record.status() == crate::protocol::types::ChannelStatus::Paired
})
{
a_usable_helper_just_paired = true;
break;
}
}
if !a_usable_helper_just_paired {
return Ok(Vec::new());
}
let snapshot = self.user_secret_store.load_latest(self.secret_id).await?;
let (secrets, description) = match snapshot {
Some(s) => (s.secrets, s.description),
None => {
if !self.has_paired_replica_destination().await? {
return Ok(Vec::new());
}
(Vec::new(), None)
}
};
let reply_to = self.auto_reply_to.then(|| self.own_transport.clone());
self.publish_secret(secrets, description, reply_to).await
}
async fn has_paired_replica_destination(&self) -> Result<bool> {
let members = self.channel_store.replicas(self.secret_id).await?;
Ok(members.iter().any(|m| {
m.role == crate::protocol::types::ReplicaRole::Destination
&& m.status == crate::protocol::types::ChannelStatus::Paired
&& Some(m.replica_id.0) != self.replica_id
}))
}
async fn apply_auto_accept(&mut self, events: Vec<DeRecEvent>) -> Result<Vec<DeRecEvent>> {
let mut out = Vec::with_capacity(events.len());
for event in events {
match event {
DeRecEvent::ActionRequired { channel_id, action }
if self.auto_accept.allows(&action) =>
{
let action_kind = action.kind();
out.push(DeRecEvent::AutoAccepted {
channel_id,
action_kind,
});
let accept_events = self.accept_inner(action).await?;
out.extend(accept_events);
}
other => out.push(other),
}
}
Ok(out)
}
async fn process_inner(
&mut self,
message: &DeRecMessage,
channel_id: ChannelId,
) -> Result<Vec<DeRecEvent>> {
if self.is_message_expired(message, channel_id) {
return Ok(vec![DeRecEvent::NoOp]);
}
if let Some(events) = self.process_channel_message(message, channel_id).await? {
return Ok(events);
}
if let Some(events) = self.process_pairing_message(message, channel_id).await? {
return Ok(events);
}
#[cfg(feature = "logging")]
tracing::warn!(channel_id = channel_id.0, "no key material for channel");
Err(Error::InvalidInput(
"unknown channel_id: no shared key or pairing secret found",
))
}
fn is_message_expired(
&self,
envelope: &DeRecMessage,
#[cfg_attr(not(feature = "logging"), allow(unused))] channel_id: ChannelId,
) -> bool {
let Some(ts) = &envelope.timestamp else {
return false;
};
let msg_secs = ts.seconds as u64;
let now = now_secs();
let age = now.saturating_sub(msg_secs);
if age > self.timeouts.inbound_message.as_secs() {
#[cfg(feature = "logging")]
tracing::warn!(
channel_id = channel_id.0,
message_age_secs = age,
timeout_secs = self.timeouts.inbound_message.as_secs(),
"message discarded — older than configured timeout"
);
return true;
}
false
}
async fn process_channel_message(
&mut self,
message: &DeRecMessage,
channel_id: ChannelId,
) -> Result<Option<Vec<DeRecEvent>>> {
let Some(SecretValue::SharedKey(shared_key)) = self
.secret_store
.load(self.secret_id, channel_id, SecretKind::SharedKey)
.await?
else {
return Ok(None);
};
if let Some(record) = self
.channel_store
.load(
self.secret_id,
crate::protocol::types::ChannelQuery::Helper { channel_id },
)
.await?
&& record.status() == crate::protocol::types::ChannelStatus::Pending
{
#[cfg(feature = "logging")]
tracing::warn!(
channel_id = channel_id.0,
"message ignored — channel is pending fingerprint verification"
);
return Ok(Some(vec![DeRecEvent::NoOp]));
}
let transport_policy = self.transport_policy();
let events = handlers::handle(
&mut self.channel_store,
&mut self.share_store,
&mut self.secret_store,
&mut self.user_secret_store,
&self.transport,
&mut self.state_store,
&self.own_transport,
message,
self.secret_id,
channel_id,
&shared_key,
self.replica_id,
transport_policy,
)
.await?;
Ok(Some(events))
}
async fn process_pairing_message(
&mut self,
message: &DeRecMessage,
channel_id: ChannelId,
) -> Result<Option<Vec<DeRecEvent>>> {
use derec_proto::MessageBody;
if let Ok(inner) = crate::derec_message::extract_inner_plaintext_message(&message.message) {
match inner {
inner @ MessageBody::PrePairRequest(_) => {
let has_pairing_secret = matches!(
self.secret_store
.load(self.secret_id, channel_id, SecretKind::PairingSecret)
.await?,
Some(SecretValue::PairingSecret(_))
);
let has_pairing_contact = matches!(
self.secret_store
.load(self.secret_id, channel_id, SecretKind::PairingContact)
.await?,
Some(SecretValue::PairingContact(_))
);
if !has_pairing_secret && !has_pairing_contact {
return Ok(None);
}
let events = handlers::pairing::handle_pre_pair_request(
&inner,
channel_id,
message.trace_id,
)?;
return Ok(Some(events));
}
MessageBody::PrePairResponse(resp) => {
let Some(SecretValue::PairingContact(contact)) = self
.secret_store
.load(self.secret_id, channel_id, SecretKind::PairingContact)
.await?
else {
return Ok(None);
};
let events = handlers::pairing::on_pre_pair_response(
&mut self.channel_store,
&mut self.secret_store,
&self.transport,
&self.own_transport,
&self.communication_info,
self.secret_id,
channel_id,
&contact,
&resp,
self.replica_id,
self.parameter_range,
)
.await?;
return Ok(Some(events));
}
_ => {} }
}
let Some(SecretValue::PairingSecret(pairing_secret)) = self
.secret_store
.load(self.secret_id, channel_id, SecretKind::PairingSecret)
.await?
else {
return Ok(None);
};
let pairing_secret = pairing_secret.to_secret()?;
let transport_policy = self.transport_policy();
let events = handlers::handle_pairing(
&mut self.channel_store,
&mut self.secret_store,
&self.transport,
&self.communication_info,
message,
self.secret_id,
channel_id,
&pairing_secret,
self.replica_id,
self.parameter_range.as_ref(),
transport_policy,
)
.await?;
Ok(Some(events))
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
pub async fn tick(&mut self) -> Vec<DeRecEvent> {
let mut events = self.run_timeout_sweeps().await;
self.update_sharing_round(&mut events).await;
events
}
async fn run_timeout_sweeps(&mut self) -> Vec<DeRecEvent> {
if let crate::protocol::ExpiredChannelCleanup::Enabled { timeout_in_secs } =
self.timeouts.expired_channels
{
let _ = self.remove_expired_channels(timeout_in_secs).await;
}
let mut events = self.check_sharing_round_timeouts().await;
events.append(&mut self.check_unpair_timeouts().await);
events
}
async fn check_sharing_round_timeouts(&mut self) -> Vec<DeRecEvent> {
let Ok(rounds) = self
.state_store
.load_all(self.secret_id, StateKind::SharingRound)
.await
else {
return vec![];
};
let now = now_secs();
let mut events = Vec::new();
for item in rounds {
let StateItem::SharingRound(round) = item else {
continue;
};
let crate::protocol::types::SharingRoundState {
version,
mut pending,
confirmed,
mut failed,
mut pending_replicas,
synced_replicas,
mut behind_replicas,
started_at,
} = *round;
if now.saturating_sub(started_at) <= self.timeouts.sharing_round.as_secs() {
continue;
}
let timed_out: Vec<ChannelId> = pending.drain().collect();
for channel_id in timed_out {
failed.insert(channel_id);
events.push(DeRecEvent::ShareRejected {
channel_id,
version,
status: StatusEnum::Fail as i32,
memo: "timeout".to_owned(),
});
#[cfg(feature = "logging")]
tracing::warn!(
channel_id = channel_id.0,
version,
"sharing round: helper timed out"
);
}
let timed_out_replicas: Vec<crate::types::ReplicaId> =
pending_replicas.drain().collect();
for replica_id in timed_out_replicas {
behind_replicas.insert(replica_id);
events.push(DeRecEvent::ReplicaSyncFailed {
replica_id: replica_id.0,
version,
reason: "timeout".to_owned(),
});
#[cfg(feature = "logging")]
tracing::warn!(
replica_id = replica_id.0,
version,
"sharing round: replica timed out"
);
}
let _ = self
.state_store
.save(
self.secret_id,
StateItem::SharingRound(Box::new(crate::protocol::types::SharingRoundState {
version,
pending,
confirmed,
failed,
pending_replicas,
synced_replicas,
behind_replicas,
started_at,
})),
)
.await;
}
events
}
async fn check_unpair_timeouts(&mut self) -> Vec<DeRecEvent> {
let now = now_secs();
let all = match self
.state_store
.load_all(self.secret_id, StateKind::PendingUnpair)
.await
{
Ok(items) => items,
Err(_) => return Vec::new(),
};
let expired: Vec<ChannelId> = all
.into_iter()
.filter_map(|item| match item {
StateItem::PendingUnpair {
channel_id,
started_at,
} if now.saturating_sub(started_at) > self.timeouts.unpair_ack.as_secs() => {
Some(channel_id)
}
_ => None,
})
.collect();
let mut events = Vec::with_capacity(expired.len());
for cid in expired {
let _ = self
.state_store
.remove(self.secret_id, StateKey::PendingUnpair { channel_id: cid })
.await;
if handlers::unpairing::drop_channel_state(
&mut self.channel_store,
&mut self.share_store,
&mut self.secret_store,
self.secret_id,
cid,
)
.await
.is_ok()
{
events.push(DeRecEvent::Unpaired { channel_id: cid });
}
}
events
}
async fn update_sharing_round(&mut self, events: &mut Vec<DeRecEvent>) {
let Ok(rounds) = self
.state_store
.load_all(self.secret_id, StateKind::SharingRound)
.await
else {
return;
};
let mut produced: Vec<DeRecEvent> = Vec::new();
for item in rounds {
let StateItem::SharingRound(round) = item else {
continue;
};
let crate::protocol::types::SharingRoundState {
version: round_version,
mut pending,
mut confirmed,
mut failed,
mut pending_replicas,
mut synced_replicas,
mut behind_replicas,
started_at,
} = *round;
self.settle_one_round(
events,
&mut produced,
round_version,
&mut pending,
&mut confirmed,
&mut failed,
&mut pending_replicas,
&mut synced_replicas,
&mut behind_replicas,
started_at,
)
.await;
}
events.append(&mut produced);
}
#[allow(clippy::too_many_arguments)]
async fn settle_one_round(
&mut self,
inbound: &[DeRecEvent],
produced: &mut Vec<DeRecEvent>,
round_version: u32,
pending: &mut std::collections::HashSet<ChannelId>,
confirmed: &mut std::collections::HashSet<ChannelId>,
failed: &mut std::collections::HashSet<ChannelId>,
pending_replicas: &mut std::collections::HashSet<crate::types::ReplicaId>,
synced_replicas: &mut std::collections::HashSet<crate::types::ReplicaId>,
behind_replicas: &mut std::collections::HashSet<crate::types::ReplicaId>,
started_at: u64,
) {
let events = inbound;
for event in events.iter() {
match event {
DeRecEvent::ShareConfirmed {
channel_id,
version,
} if *version == round_version => {
pending.remove(channel_id);
confirmed.insert(*channel_id);
}
DeRecEvent::ShareRejected {
channel_id,
version,
..
} if *version == round_version => {
pending.remove(channel_id);
failed.insert(*channel_id);
}
DeRecEvent::ReplicaSecretAcked {
from_replica_id,
version,
..
} if *version == round_version => {
if let Ok(replica_id) = crate::types::ReplicaId::try_from(*from_replica_id) {
pending_replicas.remove(&replica_id);
synced_replicas.insert(replica_id);
}
}
DeRecEvent::ReplicaSyncRejected {
replica_id,
version,
..
} if *version == round_version => {
if let Ok(replica_id) = crate::types::ReplicaId::try_from(*replica_id) {
pending_replicas.remove(&replica_id);
behind_replicas.insert(replica_id);
}
}
_ => {}
}
}
let is_complete = pending.is_empty() && pending_replicas.is_empty();
let confirmed_count = confirmed.len();
let failed_count = failed.len();
if is_complete {
let threshold_met = confirmed_count >= self.threshold;
let _ = self
.state_store
.remove(
self.secret_id,
StateKey::SharingRound {
version: round_version,
},
)
.await;
produced.push(DeRecEvent::SharingComplete {
version: round_version,
confirmed_count,
failed_count,
threshold_met,
});
let mut removed_replicas: Vec<u64> = Vec::new();
if let Ok(roster) = self.channel_store.replicas(self.secret_id).await {
for member in roster {
if member.status != crate::protocol::types::ChannelStatus::Unpairing
|| !synced_replicas.contains(&member.replica_id)
{
continue;
}
if self
.channel_store
.remove(
self.secret_id,
crate::protocol::types::ChannelQuery::Replica {
channel_id: member.channel_id,
replica_id: member.replica_id,
},
)
.await
.is_ok()
{
removed_replicas.push(member.replica_id.0);
}
}
}
if !synced_replicas.is_empty() || !behind_replicas.is_empty() {
let mut synced: Vec<u64> = synced_replicas.iter().map(|r| r.0).collect();
let mut behind: Vec<u64> = behind_replicas.iter().map(|r| r.0).collect();
synced.sort_unstable();
behind.sort_unstable();
#[cfg(feature = "logging")]
tracing::info!(
version = round_version,
synced_count = synced.len(),
behind_count = behind.len(),
"replica sync round complete"
);
produced.push(DeRecEvent::ReplicaSyncComplete {
version: round_version,
synced,
behind,
});
}
removed_replicas.sort_unstable();
for replica_id in removed_replicas {
produced.push(DeRecEvent::ReplicaRemoved { replica_id });
}
#[cfg(feature = "logging")]
tracing::info!(
version = round_version,
confirmed_count,
failed_count,
threshold_met,
"sharing round complete"
);
} else {
let _ = self
.state_store
.save(
self.secret_id,
StateItem::SharingRound(Box::new(crate::protocol::types::SharingRoundState {
version: round_version,
pending: std::mem::take(pending),
confirmed: std::mem::take(confirmed),
failed: std::mem::take(failed),
pending_replicas: std::mem::take(pending_replicas),
synced_replicas: std::mem::take(synced_replicas),
behind_replicas: std::mem::take(behind_replicas),
started_at,
})),
)
.await;
}
}
pub async fn remove_expired_channels(
&mut self,
older_than_secs: u64,
) -> Result<Vec<ChannelId>> {
let now = now_secs();
let timeout = older_than_secs;
let channels = self.channel_store.helpers(self.secret_id).await?;
let mut removed = Vec::new();
for channel in channels {
if channel.status == crate::protocol::types::ChannelStatus::Pending
&& now.saturating_sub(channel.created_at) > timeout
{
self.channel_store
.remove(
self.secret_id,
crate::protocol::types::ChannelQuery::Helper {
channel_id: channel.channel_id,
},
)
.await?;
let _ = self
.secret_store
.remove(
self.secret_id,
channel.channel_id,
SecretKind::PairingSecret,
)
.await;
let _ = self
.secret_store
.remove(
self.secret_id,
channel.channel_id,
SecretKind::PairingContact,
)
.await;
#[cfg(feature = "logging")]
tracing::info!(
channel_id = channel.channel_id.0,
elapsed_secs = now.saturating_sub(channel.created_at),
"expired pending channel removed"
);
removed.push(channel.channel_id);
}
}
for member in self.channel_store.replicas(self.secret_id).await? {
if member.status == crate::protocol::types::ChannelStatus::Pending
&& Some(member.replica_id.0) != self.replica_id
&& now.saturating_sub(member.created_at) > timeout
{
self.channel_store
.remove(
self.secret_id,
crate::protocol::types::ChannelQuery::Replica {
channel_id: member.channel_id,
replica_id: member.replica_id,
},
)
.await?;
#[cfg(feature = "logging")]
tracing::info!(
channel_id = member.channel_id.0,
replica_id = member.replica_id.0,
elapsed_secs = now.saturating_sub(member.created_at),
"expired pending replica member removed"
);
if !removed.contains(&member.channel_id) {
removed.push(member.channel_id);
}
}
}
Ok(removed)
}
}
#[cfg(test)]
mod expired_channel_sweep_tests {
use super::*;
use crate::protocol::test::{
InMemChannelStore, InMemSecretStore, InMemShareStore, InMemStateStore,
InMemUserSecretStore, NoopTransport, run_async,
};
use crate::protocol::types::{
ChannelRecord, ChannelStatus, ExpiredChannelCleanup, HelperChannel, ReplicaMember,
ReplicaRole, SecretValue,
};
const SECRET_ID: u64 = 0xC1;
fn endpoint() -> derec_proto::TransportProtocol {
derec_proto::TransportProtocol {
uri: "https://peer.example.com".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}
}
async fn seed(
channels: &mut InMemChannelStore,
cid: u64,
status: ChannelStatus,
age_secs: u64,
) {
channels
.save(
SECRET_ID,
ChannelRecord::Helper(HelperChannel {
channel_id: ChannelId(cid),
transport: endpoint(),
communication_info: std::collections::HashMap::new(),
status,
created_at: now_secs().saturating_sub(age_secs),
peer_role: derec_proto::SenderKind::Helper,
}),
)
.await
.expect("seed channel");
}
fn build(
channels: InMemChannelStore,
policy: ExpiredChannelCleanup,
timeout_in_secs: u64,
) -> DeRecProtocol<
InMemChannelStore,
InMemShareStore,
InMemSecretStore,
InMemUserSecretStore,
InMemStateStore,
NoopTransport,
> {
DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(channels)
.with_share_store(InMemShareStore::default())
.with_secret_store(InMemSecretStore::default())
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemStateStore)
.with_own_transport("https://owner.example.com")
.with_threshold(2)
.with_timeouts(crate::protocol::types::Timeouts {
sharing_round: std::time::Duration::from_secs(timeout_in_secs),
unpair_ack: std::time::Duration::from_secs(timeout_in_secs),
inbound_message: std::time::Duration::from_secs(timeout_in_secs),
expired_channels: policy,
})
.build()
.expect("test protocol builds")
}
#[test]
fn manual_sweep_works_under_disabled_policy() {
run_async(async {
let channels = InMemChannelStore::default();
let mut seeded = channels.clone();
seed(&mut seeded, 1, ChannelStatus::Pending, 600).await;
let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
let removed = protocol
.remove_expired_channels(60)
.await
.expect("sweep succeeds");
assert_eq!(removed, vec![ChannelId(1)]);
assert!(channels.helper_rows.lock().unwrap().is_empty());
});
}
async fn seed_member(
channels: &mut InMemChannelStore,
replica_id: u64,
status: ChannelStatus,
age_secs: u64,
) {
channels
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: ChannelId(9000),
replica_id: crate::types::ReplicaId(replica_id),
transport: endpoint(),
communication_info: std::collections::HashMap::new(),
role: ReplicaRole::Destination,
status,
created_at: now_secs().saturating_sub(age_secs),
}),
)
.await
.expect("seed member");
}
#[test]
fn sweep_removes_expired_replica_members_but_never_this_device() {
run_async(async {
let channels = InMemChannelStore::default();
let mut seeded = channels.clone();
seed_member(&mut seeded, 7, ChannelStatus::Pending, 600).await;
seed_member(&mut seeded, 8, ChannelStatus::Paired, 600).await;
seed_member(&mut seeded, 9, ChannelStatus::Pending, 600).await;
let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
protocol.replica_id = Some(9);
let removed = protocol
.remove_expired_channels(60)
.await
.expect("sweep succeeds");
assert_eq!(
removed,
vec![ChannelId(9000)],
"members share one channel, so the group is reported once"
);
let rows = channels.member_rows.lock().unwrap();
assert!(
!rows.contains_key(&(SECRET_ID, 7)),
"expired pending member"
);
assert!(rows.contains_key(&(SECRET_ID, 8)), "paired member survives");
assert!(rows.contains_key(&(SECRET_ID, 9)), "own row is exempt");
});
}
#[test]
fn disabled_policy_leaves_channel_for_manual_sweep() {
run_async(async {
let channels = InMemChannelStore::default();
let mut seeded = channels.clone();
seed(&mut seeded, 1, ChannelStatus::Pending, 600).await;
let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
let _ = protocol.process(&[]).await;
assert_eq!(channels.helper_rows.lock().unwrap().len(), 1);
});
}
#[test]
fn policy_timeout_governs_not_protocol_timeout() {
run_async(async {
let channels = InMemChannelStore::default();
let mut seeded = channels.clone();
seed(&mut seeded, 1, ChannelStatus::Pending, 120).await;
let mut protocol = build(
channels.clone(),
ExpiredChannelCleanup::Enabled {
timeout_in_secs: 60,
},
3600,
);
let _ = protocol.process(&[]).await;
assert!(channels.helper_rows.lock().unwrap().is_empty());
});
}
#[test]
fn paired_channels_are_never_removed() {
run_async(async {
let channels = InMemChannelStore::default();
let mut seeded = channels.clone();
seed(&mut seeded, 1, ChannelStatus::Paired, 99_999).await;
let mut protocol = build(channels.clone(), ExpiredChannelCleanup::default(), 300);
let removed = protocol
.remove_expired_channels(1)
.await
.expect("sweep succeeds");
assert!(removed.is_empty());
assert_eq!(channels.helper_rows.lock().unwrap().len(), 1);
});
}
#[test]
fn removal_drops_pairing_material() {
run_async(async {
let channels = InMemChannelStore::default();
let secrets = InMemSecretStore::default();
let mut seeded = channels.clone();
let mut seeded_secrets = secrets.clone();
seed(&mut seeded, 1, ChannelStatus::Pending, 600).await;
seeded_secrets
.save(
SECRET_ID,
ChannelId(1),
SecretValue::PairingContact(Default::default()),
)
.await
.expect("seed pairing contact");
let mut protocol = DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(channels.clone())
.with_share_store(InMemShareStore::default())
.with_secret_store(secrets.clone())
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemStateStore)
.with_own_transport("https://owner.example.com")
.with_threshold(2)
.with_timeouts(crate::protocol::types::Timeouts {
expired_channels: ExpiredChannelCleanup::Disabled,
..Default::default()
})
.build()
.expect("test protocol builds");
let removed = protocol
.remove_expired_channels(60)
.await
.expect("sweep succeeds");
assert_eq!(removed, vec![ChannelId(1)]);
assert!(secrets.data.lock().unwrap().is_empty());
});
}
#[test]
fn explicit_zero_sweeps_pending_from_earlier_seconds() {
run_async(async {
let channels = InMemChannelStore::default();
let mut seeded = channels.clone();
seed(&mut seeded, 1, ChannelStatus::Pending, 1).await;
seed(&mut seeded, 2, ChannelStatus::Paired, 1).await;
let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
let removed = protocol
.remove_expired_channels(0)
.await
.expect("sweep succeeds");
assert_eq!(removed, vec![ChannelId(1)]);
assert_eq!(channels.helper_rows.lock().unwrap().len(), 1);
});
}
#[test]
fn zero_age_channel_survives_zero_threshold() {
run_async(async {
let channels = InMemChannelStore::default();
let mut seeded = channels.clone();
seed(&mut seeded, 1, ChannelStatus::Pending, 0).await;
let mut protocol = build(channels.clone(), ExpiredChannelCleanup::Disabled, 300);
let removed = protocol
.remove_expired_channels(0)
.await
.expect("sweep succeeds");
assert!(removed.is_empty());
assert_eq!(channels.helper_rows.lock().unwrap().len(), 1);
});
}
}
#[cfg(test)]
mod sharing_round_outcome_tests {
use super::*;
use crate::protocol::test::{
InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
InMemUserSecretStore, NoopTransport, run_async,
};
use crate::types::ReplicaId;
const SECRET_ID: u64 = 0xF00D;
type TestProtocol = DeRecProtocol<
InMemChannelStore,
InMemShareStore,
InMemSecretStore,
InMemUserSecretStore,
InMemPersistedStateStore,
NoopTransport,
>;
fn build(threshold: usize) -> TestProtocol {
DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(InMemChannelStore::default())
.with_share_store(InMemShareStore::default())
.with_secret_store(InMemSecretStore::default())
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemPersistedStateStore::default())
.with_own_transport("https://owner.example.com")
.with_threshold(threshold)
.build()
.expect("test protocol builds")
}
async fn seed_round(
protocol: &mut TestProtocol,
version: u32,
helpers: &[u64],
members: &[u64],
) {
protocol
.state_store
.save(
SECRET_ID,
StateItem::SharingRound(Box::new(crate::protocol::types::SharingRoundState {
version,
pending: helpers.iter().copied().map(ChannelId).collect(),
confirmed: HashSet::new(),
failed: HashSet::new(),
pending_replicas: members.iter().copied().map(ReplicaId).collect(),
synced_replicas: HashSet::new(),
behind_replicas: HashSet::new(),
started_at: now_secs(),
})),
)
.await
.expect("seed round");
}
#[test]
fn two_open_rounds_settle_independently() {
run_async(async {
let mut protocol = build(2);
seed_round(&mut protocol, 7, &[9001], &[]).await;
seed_round(&mut protocol, 8, &[9002], &[]).await;
for version in [7u32, 8] {
assert!(
protocol
.state_store
.load(SECRET_ID, StateKey::SharingRound { version })
.await
.expect("load")
.is_some(),
"round v{version} must still be in flight"
);
}
let mut events = vec![DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9001),
version: 7,
}];
protocol.update_sharing_round(&mut events).await;
assert!(
events
.iter()
.any(|e| matches!(e, DeRecEvent::SharingComplete { version: 7, .. })),
"v7 completes once its only helper confirms; got {events:?}"
);
assert!(
!events
.iter()
.any(|e| matches!(e, DeRecEvent::SharingComplete { version: 8, .. })),
"v8 has an outstanding helper and must not complete; got {events:?}"
);
assert!(
protocol
.state_store
.load(SECRET_ID, StateKey::SharingRound { version: 7 })
.await
.expect("load")
.is_none(),
"a completed round leaves no row"
);
let mut events = vec![DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9002),
version: 8,
}];
protocol.update_sharing_round(&mut events).await;
assert!(
events
.iter()
.any(|e| matches!(e, DeRecEvent::SharingComplete { version: 8, .. })),
"v8 completes when its own helper answers; got {events:?}"
);
assert!(
protocol
.state_store
.load(SECRET_ID, StateKey::SharingRound { version: 8 })
.await
.expect("load")
.is_none(),
"a completed round leaves no row"
);
});
}
#[test]
fn tick_closes_a_round_that_no_message_will_ever_finish() {
run_async(async {
let mut protocol = build(2);
protocol.timeouts.sharing_round = std::time::Duration::from_secs(60);
protocol
.state_store
.save(
SECRET_ID,
StateItem::SharingRound(Box::new(crate::protocol::types::SharingRoundState {
version: 3,
pending: [ChannelId(9001)].into_iter().collect(),
confirmed: [ChannelId(9002)].into_iter().collect(),
failed: HashSet::new(),
pending_replicas: [ReplicaId(1002)].into_iter().collect(),
synced_replicas: HashSet::new(),
behind_replicas: HashSet::new(),
started_at: now_secs().saturating_sub(600),
})),
)
.await
.expect("seed round");
let events = protocol.tick().await;
assert!(
events.iter().any(|e| matches!(
e,
DeRecEvent::ShareRejected { channel_id, memo, .. }
if *channel_id == ChannelId(9001) && memo == "timeout"
)),
"the silent helper is failed; got {events:?}"
);
assert!(
events.iter().any(|e| matches!(
e,
DeRecEvent::ReplicaSyncFailed { replica_id, reason, .. }
if *replica_id == 1002 && reason == "timeout"
)),
"the silent member is reported behind; got {events:?}"
);
assert!(
events
.iter()
.any(|e| matches!(e, DeRecEvent::SharingComplete { version: 3, .. })),
"the round must actually close, not just report failures; got {events:?}"
);
assert!(
protocol
.state_store
.load(SECRET_ID, StateKey::SharingRound { version: 3 })
.await
.expect("load")
.is_none(),
"a closed round leaves no state row behind"
);
});
}
#[test]
fn tick_expires_an_unacknowledged_unpair() {
run_async(async {
let mut protocol = build(2);
protocol.timeouts.unpair_ack = std::time::Duration::from_secs(60);
protocol
.state_store
.save(
SECRET_ID,
StateItem::PendingUnpair {
channel_id: ChannelId(4242),
started_at: now_secs().saturating_sub(600),
},
)
.await
.expect("seed pending unpair");
let events = protocol.tick().await;
assert!(
events.iter().any(|e| matches!(
e,
DeRecEvent::Unpaired { channel_id } if *channel_id == ChannelId(4242)
)),
"the unacknowledged unpair completes on the timeout; got {events:?}"
);
assert!(
protocol
.state_store
.load(
SECRET_ID,
StateKey::PendingUnpair {
channel_id: ChannelId(4242)
}
)
.await
.expect("load")
.is_none(),
"the pending row is consumed"
);
});
}
#[test]
fn tick_leaves_a_recent_unpair_pending() {
run_async(async {
let mut protocol = build(2);
protocol.timeouts.unpair_ack = std::time::Duration::from_secs(600);
protocol
.state_store
.save(
SECRET_ID,
StateItem::PendingUnpair {
channel_id: ChannelId(4242),
started_at: now_secs(),
},
)
.await
.expect("seed pending unpair");
let events = protocol.tick().await;
assert!(events.is_empty(), "got {events:?}");
assert!(
protocol
.state_store
.load(
SECRET_ID,
StateKey::PendingUnpair {
channel_id: ChannelId(4242)
}
)
.await
.expect("load")
.is_some(),
"the acknowledgement window has not elapsed"
);
});
}
#[test]
fn tick_honours_the_expired_channel_policy() {
run_async(async {
for (cleanup, expect_removed) in [
(crate::protocol::ExpiredChannelCleanup::Disabled, false),
(
crate::protocol::ExpiredChannelCleanup::Enabled { timeout_in_secs: 1 },
true,
),
] {
let mut protocol = build(2);
protocol.timeouts.expired_channels = cleanup;
protocol
.channel_store
.save(
SECRET_ID,
crate::protocol::types::ChannelRecord::Helper(
crate::protocol::types::HelperChannel {
channel_id: ChannelId(77),
transport: derec_proto::TransportProtocol {
uri: "https://stale.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
},
communication_info: std::collections::HashMap::new(),
peer_role: derec_proto::SenderKind::Helper,
status: crate::protocol::types::ChannelStatus::Pending,
created_at: now_secs().saturating_sub(3600),
},
),
)
.await
.expect("seed stale pending channel");
let _ = protocol.tick().await;
let gone = protocol
.channel_store
.helpers(SECRET_ID)
.await
.expect("helpers")
.is_empty();
assert_eq!(
gone, expect_removed,
"cleanup {cleanup:?}: expected removed={expect_removed}"
);
}
});
}
#[test]
fn tick_on_an_idle_protocol_does_nothing() {
run_async(async {
let mut protocol = build(2);
let events = protocol.tick().await;
assert!(events.is_empty(), "got {events:?}");
});
}
#[test]
fn tick_leaves_a_round_inside_its_window_open() {
run_async(async {
let mut protocol = build(2);
protocol.timeouts.sharing_round = std::time::Duration::from_secs(600);
seed_round(&mut protocol, 4, &[9001], &[1002]).await;
let events = protocol.tick().await;
assert!(events.is_empty(), "got {events:?}");
assert!(
protocol
.state_store
.load(SECRET_ID, StateKey::SharingRound { version: 4 })
.await
.expect("load")
.is_some(),
"the round is still in flight"
);
});
}
#[test]
fn the_publisher_drops_a_departing_member_once_it_acknowledges() {
run_async(async {
let mut protocol = build(2);
seed_round(&mut protocol, 7, &[9001], &[1002, 1003]).await;
for (id, status) in [
(1002u64, crate::protocol::types::ChannelStatus::Paired),
(1003, crate::protocol::types::ChannelStatus::Unpairing),
] {
protocol
.channel_store
.save(
SECRET_ID,
crate::protocol::types::ChannelRecord::Replica(
crate::protocol::types::ReplicaMember {
channel_id: ChannelId(5001),
replica_id: ReplicaId(id),
transport: derec_proto::TransportProtocol {
uri: "https://peer.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
},
communication_info: std::collections::HashMap::new(),
role: crate::protocol::types::ReplicaRole::Destination,
status,
created_at: 0,
},
),
)
.await
.expect("seed member");
}
let mut events = vec![
DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9001),
version: 7,
},
DeRecEvent::ReplicaSecretAcked {
channel_id: ChannelId(5001),
from_replica_id: 1002,
secret_id: SECRET_ID,
version: 7,
status: 0,
memo: String::new(),
},
DeRecEvent::ReplicaSecretAcked {
channel_id: ChannelId(5001),
from_replica_id: 1003,
secret_id: SECRET_ID,
version: 7,
status: 0,
memo: String::new(),
},
];
protocol.update_sharing_round(&mut events).await;
let remaining: Vec<u64> = protocol
.channel_store
.replicas(SECRET_ID)
.await
.expect("roster")
.into_iter()
.map(|m| m.replica_id.0)
.collect();
assert_eq!(
remaining,
vec![1002],
"the acknowledged departing member is gone; the other survives"
);
assert!(
events.iter().any(|e| matches!(
e,
DeRecEvent::ReplicaRemoved { replica_id } if *replica_id == 1003
)),
"the removal is reported to the application; got {events:?}"
);
});
}
#[test]
fn a_departing_member_that_has_not_answered_is_kept() {
run_async(async {
let mut protocol = build(2);
seed_round(&mut protocol, 7, &[9001], &[1002]).await;
protocol
.channel_store
.save(
SECRET_ID,
crate::protocol::types::ChannelRecord::Replica(
crate::protocol::types::ReplicaMember {
channel_id: ChannelId(5001),
replica_id: ReplicaId(1003),
transport: derec_proto::TransportProtocol {
uri: "https://peer.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
},
communication_info: std::collections::HashMap::new(),
role: crate::protocol::types::ReplicaRole::Destination,
status: crate::protocol::types::ChannelStatus::Unpairing,
created_at: 0,
},
),
)
.await
.expect("seed member");
let mut events = vec![
DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9001),
version: 7,
},
DeRecEvent::ReplicaSecretAcked {
channel_id: ChannelId(5001),
from_replica_id: 1002,
secret_id: SECRET_ID,
version: 7,
status: 0,
memo: String::new(),
},
];
protocol.update_sharing_round(&mut events).await;
let remaining: Vec<u64> = protocol
.channel_store
.replicas(SECRET_ID)
.await
.expect("roster")
.into_iter()
.map(|m| m.replica_id.0)
.collect();
assert_eq!(
remaining,
vec![1003],
"an unacknowledged departure leaves the row in place"
);
});
}
#[test]
fn members_on_one_channel_settle_independently() {
run_async(async {
let mut protocol = build(2);
seed_round(&mut protocol, 4, &[9001], &[1002, 1003]).await;
let mut events = vec![
DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9001),
version: 4,
},
DeRecEvent::ReplicaSecretAcked {
channel_id: ChannelId(5001),
from_replica_id: 1002,
secret_id: SECRET_ID,
version: 4,
status: 0,
memo: String::new(),
},
];
protocol.update_sharing_round(&mut events).await;
assert!(
!events
.iter()
.any(|e| matches!(e, DeRecEvent::SharingComplete { .. })),
"the round must stay open while member 1003 has not answered"
);
let mut events = vec![DeRecEvent::ReplicaSecretAcked {
channel_id: ChannelId(5001),
from_replica_id: 1003,
secret_id: SECRET_ID,
version: 4,
status: 0,
memo: String::new(),
}];
protocol.update_sharing_round(&mut events).await;
let sync = events
.iter()
.find_map(|e| match e {
DeRecEvent::ReplicaSyncComplete { synced, behind, .. } => {
Some((synced.clone(), behind.clone()))
}
_ => None,
})
.expect("replica leg must report its own completion");
assert_eq!(sync, (vec![1002, 1003], vec![]));
});
}
#[test]
fn an_unreachable_member_leaves_the_round_successful() {
run_async(async {
let mut protocol = build(2);
seed_round(&mut protocol, 4, &[9001, 9002], &[1003]).await;
let mut events = vec![
DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9001),
version: 4,
},
DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9002),
version: 4,
},
DeRecEvent::ReplicaSyncFailed {
replica_id: 1003,
version: 4,
reason: "transport unreachable".to_owned(),
},
];
protocol
.state_store
.save(
SECRET_ID,
StateItem::SharingRound(Box::new(crate::protocol::types::SharingRoundState {
version: 4,
pending: HashSet::from([ChannelId(9001), ChannelId(9002)]),
confirmed: HashSet::new(),
failed: HashSet::new(),
pending_replicas: HashSet::new(),
synced_replicas: HashSet::new(),
behind_replicas: HashSet::from([ReplicaId(1003)]),
started_at: now_secs(),
})),
)
.await
.expect("seed");
protocol.update_sharing_round(&mut events).await;
let complete = events
.iter()
.find_map(|e| match e {
DeRecEvent::SharingComplete { threshold_met, .. } => Some(*threshold_met),
_ => None,
})
.expect("helper leg must complete");
assert!(
complete,
"an unreachable replica must not fail the helper round"
);
let sync = events
.iter()
.find_map(|e| match e {
DeRecEvent::ReplicaSyncComplete { synced, behind, .. } => {
Some((synced.clone(), behind.clone()))
}
_ => None,
})
.expect("replica leg must report its own completion");
assert_eq!(sync, (vec![], vec![1003]), "the member is reported behind");
});
}
#[test]
fn a_conflicting_member_is_reported_behind() {
run_async(async {
let mut protocol = build(3);
seed_round(&mut protocol, 4, &[9001, 9002, 9003], &[1002, 1003]).await;
let mut events = vec![
DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9001),
version: 4,
},
DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9002),
version: 4,
},
DeRecEvent::ShareRejected {
channel_id: ChannelId(9003),
version: 4,
status: derec_proto::StatusEnum::VersionConflict as i32,
memo: "conflict".to_owned(),
},
DeRecEvent::ReplicaSyncRejected {
replica_id: 1002,
secret_id: SECRET_ID,
version: 4,
status: derec_proto::StatusEnum::VersionConflict as i32,
memo: "conflict".to_owned(),
},
DeRecEvent::ReplicaSecretAcked {
channel_id: ChannelId(5001),
from_replica_id: 1003,
secret_id: SECRET_ID,
version: 4,
status: 0,
memo: String::new(),
},
];
protocol.update_sharing_round(&mut events).await;
let (confirmed, failed, threshold_met) = events
.iter()
.find_map(|e| match e {
DeRecEvent::SharingComplete {
confirmed_count,
failed_count,
threshold_met,
..
} => Some((*confirmed_count, *failed_count, *threshold_met)),
_ => None,
})
.expect("helper leg must complete");
assert_eq!((confirmed, failed), (2, 1));
assert!(!threshold_met, "2 of 3 helpers is under a threshold of 3");
let sync = events
.iter()
.find_map(|e| match e {
DeRecEvent::ReplicaSyncComplete { synced, behind, .. } => {
Some((synced.clone(), behind.clone()))
}
_ => None,
})
.expect("replica leg must report its own completion");
assert_eq!(sync, (vec![1003], vec![1002]));
});
}
#[test]
fn a_helpers_only_round_emits_no_replica_summary() {
run_async(async {
let mut protocol = build(2);
seed_round(&mut protocol, 2, &[9001], &[]).await;
let mut events = vec![DeRecEvent::ShareConfirmed {
channel_id: ChannelId(9001),
version: 2,
}];
protocol.update_sharing_round(&mut events).await;
assert!(
events
.iter()
.any(|e| matches!(e, DeRecEvent::SharingComplete { .. })),
"the helper leg still completes"
);
assert!(
!events
.iter()
.any(|e| matches!(e, DeRecEvent::ReplicaSyncComplete { .. })),
"a round with no replica leg must not report one"
);
});
}
}
#[cfg(test)]
mod helper_fingerprint_gate_tests {
use super::*;
use crate::protocol::test::{
InMemChannelStore, InMemSecretStore, InMemShareStore, InMemStateStore,
InMemUserSecretStore, NoopTransport, run_async,
};
use crate::protocol::types::{ChannelRecord, ChannelStatus, HelperChannel, SecretValue};
const SECRET_ID: u64 = 0xF1;
const CHANNEL: ChannelId = ChannelId(77);
fn endpoint() -> derec_proto::TransportProtocol {
derec_proto::TransportProtocol {
uri: "https://helper.example.com".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}
}
async fn seed_pending_helper(
channels: &mut InMemChannelStore,
secrets: &mut InMemSecretStore,
status: ChannelStatus,
) {
channels
.save(
SECRET_ID,
ChannelRecord::Helper(HelperChannel {
channel_id: CHANNEL,
transport: endpoint(),
communication_info: std::collections::HashMap::new(),
status,
created_at: now_secs(),
peer_role: derec_proto::SenderKind::Helper,
}),
)
.await
.expect("seed helper channel");
secrets
.save(SECRET_ID, CHANNEL, SecretValue::SharedKey([7u8; 32]))
.await
.expect("seed shared key");
}
fn build(
channels: InMemChannelStore,
secrets: InMemSecretStore,
) -> DeRecProtocol<
InMemChannelStore,
InMemShareStore,
InMemSecretStore,
InMemUserSecretStore,
InMemStateStore,
NoopTransport,
> {
DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(channels)
.with_share_store(InMemShareStore::default())
.with_secret_store(secrets)
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemStateStore)
.with_own_transport("https://owner.example.com")
.with_threshold(2)
.build()
.expect("test protocol builds")
}
async fn status_of(channels: &mut InMemChannelStore) -> ChannelStatus {
channels
.load(
SECRET_ID,
crate::protocol::types::ChannelQuery::Helper {
channel_id: CHANNEL,
},
)
.await
.expect("load helper")
.expect("helper row present")
.status()
}
#[test]
fn a_matching_fingerprint_promotes_a_pending_helper() {
run_async(async {
let channels = InMemChannelStore::default();
let secrets = InMemSecretStore::default();
let (mut seeded_ch, mut seeded_se) = (channels.clone(), secrets.clone());
seed_pending_helper(&mut seeded_ch, &mut seeded_se, ChannelStatus::Pending).await;
let mut protocol = build(channels.clone(), secrets.clone());
let fingerprint = protocol
.get_fingerprint(CHANNEL)
.await
.expect("fingerprint derives from the shared key");
assert!(
protocol
.verify_fingerprint(CHANNEL, &fingerprint)
.await
.expect("verify_fingerprint"),
"a matching fingerprint must verify"
);
let mut check = channels.clone();
assert_eq!(
status_of(&mut check).await,
ChannelStatus::Paired,
"a verified helper channel must become usable"
);
});
}
#[test]
fn a_wrong_fingerprint_leaves_the_helper_pending() {
run_async(async {
let channels = InMemChannelStore::default();
let secrets = InMemSecretStore::default();
let (mut seeded_ch, mut seeded_se) = (channels.clone(), secrets.clone());
seed_pending_helper(&mut seeded_ch, &mut seeded_se, ChannelStatus::Pending).await;
let mut protocol = build(channels.clone(), secrets.clone());
assert!(
!protocol
.verify_fingerprint(CHANNEL, "not-the-fingerprint")
.await
.expect("verify_fingerprint"),
"a mismatched fingerprint must not verify"
);
let mut check = channels.clone();
assert_eq!(
status_of(&mut check).await,
ChannelStatus::Pending,
"a failed comparison must leave the channel inert"
);
});
}
#[test]
fn verifying_an_already_paired_helper_changes_nothing() {
run_async(async {
let channels = InMemChannelStore::default();
let secrets = InMemSecretStore::default();
let (mut seeded_ch, mut seeded_se) = (channels.clone(), secrets.clone());
seed_pending_helper(&mut seeded_ch, &mut seeded_se, ChannelStatus::Paired).await;
let mut protocol = build(channels.clone(), secrets.clone());
let fingerprint = protocol
.get_fingerprint(CHANNEL)
.await
.expect("fingerprint");
assert!(
protocol
.verify_fingerprint(CHANNEL, &fingerprint)
.await
.expect("verify_fingerprint")
);
let mut check = channels.clone();
assert_eq!(status_of(&mut check).await, ChannelStatus::Paired);
});
}
}
#[cfg(test)]
mod timeout_tests {
use super::*;
use crate::protocol::test::{
InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
InMemUserSecretStore, NoopTransport, run_async,
};
use crate::protocol::types::Timeouts;
use std::time::Duration;
const SECRET_ID: u64 = 0x7180;
type TestProtocol = DeRecProtocol<
InMemChannelStore,
InMemShareStore,
InMemSecretStore,
InMemUserSecretStore,
InMemPersistedStateStore,
NoopTransport,
>;
fn build_with(timeouts: Timeouts) -> TestProtocol {
DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(InMemChannelStore::default())
.with_share_store(InMemShareStore::default())
.with_secret_store(InMemSecretStore::default())
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemPersistedStateStore::default())
.with_own_transport("https://owner.example.com")
.with_threshold(2)
.with_timeouts(timeouts)
.build()
.expect("test protocol builds")
}
fn envelope_aged(age_secs: u64) -> DeRecMessage {
DeRecMessage {
timestamp: Some(prost_types::Timestamp {
seconds: now_secs().saturating_sub(age_secs) as i64,
nanos: 0,
}),
..Default::default()
}
}
#[test]
fn defaults_are_the_documented_values() {
let d = Timeouts::default();
assert_eq!(d.inbound_message, Duration::from_secs(300));
assert_eq!(d.sharing_round, Duration::from_secs(60));
assert_eq!(d.unpair_ack, Duration::from_secs(60));
assert_eq!(
d.expired_channels,
crate::protocol::ExpiredChannelCleanup::Enabled {
timeout_in_secs: 300
}
);
}
#[test]
fn inbound_message_bounds_how_stale_an_envelope_may_be() {
let protocol = build_with(Timeouts {
inbound_message: Duration::from_secs(120),
..Default::default()
});
assert!(
!protocol.is_message_expired(&envelope_aged(60), ChannelId(1)),
"an envelope inside the window is accepted"
);
assert!(
!protocol.is_message_expired(&envelope_aged(120), ChannelId(1)),
"the boundary itself is inclusive"
);
assert!(
protocol.is_message_expired(&envelope_aged(121), ChannelId(1)),
"an envelope past the window is discarded"
);
}
#[test]
fn an_envelope_without_a_timestamp_is_not_expired() {
let protocol = build_with(Timeouts::default());
let envelope = DeRecMessage {
timestamp: None,
..Default::default()
};
assert!(!protocol.is_message_expired(&envelope, ChannelId(1)));
}
#[test]
fn shortening_the_liveness_budgets_leaves_the_replay_window_alone() {
let protocol = build_with(Timeouts {
sharing_round: Duration::from_secs(1),
unpair_ack: Duration::from_secs(1),
..Default::default()
});
assert_eq!(protocol.timeouts.inbound_message, Duration::from_secs(300));
assert!(
!protocol.is_message_expired(&envelope_aged(290), ChannelId(1)),
"a message well inside the default replay window is still accepted \
even though both liveness budgets are one second"
);
}
#[test]
fn a_long_replay_window_does_not_extend_the_sharing_round() {
run_async(async {
let mut protocol = build_with(Timeouts {
inbound_message: Duration::from_secs(3600),
sharing_round: Duration::from_secs(1),
..Default::default()
});
protocol
.state_store
.save(
SECRET_ID,
StateItem::SharingRound(Box::new(crate::protocol::types::SharingRoundState {
version: 1,
pending: [ChannelId(9001)].into_iter().collect(),
confirmed: HashSet::new(),
failed: HashSet::new(),
pending_replicas: HashSet::new(),
synced_replicas: HashSet::new(),
behind_replicas: HashSet::new(),
started_at: now_secs().saturating_sub(30),
})),
)
.await
.expect("seed round");
let events = protocol.tick().await;
assert!(
events
.iter()
.any(|e| matches!(e, DeRecEvent::SharingComplete { version: 1, .. })),
"the round times out on its own budget, not the replay window; got {events:?}"
);
});
}
}
#[cfg(test)]
mod transport_gate_tests {
use super::*;
use crate::protocol::test::{
InMemChannelStore, InMemPersistedStateStore, InMemSecretStore, InMemShareStore,
InMemUserSecretStore, NoopTransport, run_async,
};
const SECRET_ID: u64 = 0x60A7;
fn builder_with(
own: &str,
unsafe_http: bool,
) -> crate::Result<
DeRecProtocol<
InMemChannelStore,
InMemShareStore,
InMemSecretStore,
InMemUserSecretStore,
InMemPersistedStateStore,
NoopTransport,
>,
> {
DeRecProtocolBuilder::new(SECRET_ID)
.with_channel_store(InMemChannelStore::default())
.with_share_store(InMemShareStore::default())
.with_secret_store(InMemSecretStore::default())
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemPersistedStateStore::default())
.with_own_transport(own)
.with_threshold(2)
.with_unsafe_http(unsafe_http)
.build()
}
#[test]
fn own_loopback_needs_no_configuration() {
run_async(async {
for uri in [
"http://localhost:8080",
"http://127.0.0.1:8080",
"http://[::1]:8080",
] {
assert!(builder_with(uri, false).is_ok(), "{uri} should build");
}
});
}
#[test]
fn own_lan_plaintext_needs_the_flag() {
run_async(async {
let Err(err) = builder_with("http://192.168.1.42:8080", false) else {
panic!("LAN plaintext must not build by default");
};
assert!(
matches!(
err,
crate::Error::Transport(
crate::transport::TransportValidationError::PlaintextRefused { .. }
)
),
"expected a plaintext refusal, got {err:?}"
);
assert!(builder_with("http://192.168.1.42:8080", true).is_ok());
});
}
#[test]
fn setter_order_does_not_matter() {
run_async(async {
let built = DeRecProtocolBuilder::new(SECRET_ID)
.with_unsafe_http(true)
.with_channel_store(InMemChannelStore::default())
.with_share_store(InMemShareStore::default())
.with_secret_store(InMemSecretStore::default())
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemPersistedStateStore::default())
.with_own_transport("http://192.168.1.42:8080")
.with_threshold(2)
.build();
assert!(built.is_ok(), "unsafe_http set before the endpoint");
});
}
#[test]
fn https_builds_under_either_setting() {
run_async(async {
assert!(builder_with("https://owner.example.com", false).is_ok());
assert!(builder_with("https://owner.example.com", true).is_ok());
});
}
#[test]
fn every_peer_supplied_endpoint_is_reachable_from_the_funnel() {
use derec_proto::{MessageBody, TransportProtocol};
let ep = || {
Some(TransportProtocol {
uri: "http://127.0.0.1:9999".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
})
};
let bodies = [
MessageBody::StoreShareRequest(derec_proto::StoreShareRequestMessage {
reply_to: ep(),
..Default::default()
}),
MessageBody::VerifyShareRequest(derec_proto::VerifyShareRequestMessage {
reply_to: ep(),
..Default::default()
}),
MessageBody::GetSecretIdsVersionsRequest(
derec_proto::GetSecretIdsVersionsRequestMessage {
reply_to: ep(),
..Default::default()
},
),
MessageBody::GetShareRequest(derec_proto::GetShareRequestMessage {
reply_to: ep(),
..Default::default()
}),
MessageBody::UnpairRequest(derec_proto::UnpairRequestMessage {
reply_to: ep(),
..Default::default()
}),
MessageBody::UpdateChannelInfoRequest(derec_proto::UpdateChannelInfoRequestMessage {
transport_protocol: ep(),
..Default::default()
}),
MessageBody::PairRequest(derec_proto::PairRequestMessage {
transport_protocol: ep(),
..Default::default()
}),
MessageBody::PrePairRequest(derec_proto::PrePairRequestMessage {
transport_protocol: ep(),
..Default::default()
}),
];
for body in &bodies {
let found: Vec<_> = handlers::peer_supplied_endpoints(body).collect();
assert_eq!(
found.len(),
1,
"the funnel missed the peer endpoint on {body:?}"
);
assert!(
crate::transport::TransportPolicy::new(false)
.check_peer(found[0])
.is_err()
);
}
}
}