use crate::protocol::{DeRecChannelStore, DeRecTransport};
use crate::transport::TransportPolicy;
use crate::{
Error, Result,
derec_message::{DeRecMessageBuilder, current_timestamp},
protocol::types::{
ChannelQuery, ChannelStatus, HelperChannel, HelperFilter, ReplicaFilter, ReplicaMember,
Target,
},
types::{ChannelId, SharedKey},
};
use derec_proto::{MessageBody, SenderKind, TransportProtocol};
use prost::Message;
pub(crate) trait ChannelStoreExt: DeRecChannelStore {
async fn helpers_matching(
&self,
secret_id: u64,
filter: HelperFilter,
) -> Result<Vec<HelperChannel>> {
let rows = self.helpers(secret_id, filter.clone()).await?;
Ok(retain_matching(rows, "helpers", |c| {
filter.matches(&c.channel_id, c.status, &c.peer_role)
}))
}
async fn replicas_matching(
&self,
secret_id: u64,
filter: ReplicaFilter,
) -> Result<Vec<ReplicaMember>> {
let rows = self.replicas(secret_id, filter.clone()).await?;
Ok(retain_matching(rows, "replicas", |m| {
filter.matches(&m.replica_id, m.status, &m.role)
}))
}
async fn require_role(
&self,
secret_id: u64,
channel_ids: &[ChannelId],
expected: SenderKind,
) -> Result<()> {
for channel_id in channel_ids {
let channel = self
.load(
secret_id,
ChannelQuery::Helper {
channel_id: *channel_id,
},
)
.await?
.and_then(|r| r.as_helper().cloned())
.ok_or(Error::InvalidInput(
"channel id not present in channel store",
))?;
if channel.peer_role != expected {
return Err(Error::RoleMismatch {
channel_id: *channel_id,
expected,
actual: channel.peer_role,
});
}
}
Ok(())
}
async fn resolve_target(&self, secret_id: u64, target: Target) -> Result<Vec<ChannelId>> {
let known: Vec<ChannelId> = self
.helpers_matching(
secret_id,
HelperFilter {
ids: target.ids(),
status: vec![ChannelStatus::Paired],
..Default::default()
},
)
.await?
.iter()
.map(|c| c.channel_id)
.collect();
Ok(target.filter(&known))
}
async fn peer_endpoints(
&self,
secret_id: u64,
channel_id: ChannelId,
) -> Result<Vec<TransportProtocol>> {
let channel = self
.load(secret_id, ChannelQuery::Helper { channel_id })
.await?;
channel
.map(|ch| ch.transports().to_vec())
.filter(|endpoints| !endpoints.is_empty())
.ok_or(Error::InvalidInput("no transport endpoint for channel"))
}
async fn resolve_response_endpoints(
&self,
secret_id: u64,
channel_id: ChannelId,
policy: TransportPolicy,
reply_to: &[TransportProtocol],
) -> Result<Vec<TransportProtocol>> {
let allowed = filter_reply_to(policy, reply_to);
if !allowed.is_empty() {
return Ok(allowed);
}
self.peer_endpoints(secret_id, channel_id).await
}
async fn load_replica_member(
&self,
secret_id: u64,
channel_id: ChannelId,
author: u64,
) -> Result<ReplicaMember> {
let replica_id = crate::types::ReplicaId::try_from(author)?;
self.load(
secret_id,
ChannelQuery::Replica {
channel_id,
replica_id,
},
)
.await?
.and_then(|r| r.as_replica().cloned())
.ok_or(Error::InvalidInput(
"replica sync names a member that is not in the group",
))
}
}
impl<T: DeRecChannelStore> ChannelStoreExt for T {}
pub(crate) fn filter_reply_to(
policy: TransportPolicy,
reply_to: &[TransportProtocol],
) -> Vec<TransportProtocol> {
reply_to
.iter()
.filter(|endpoint| policy.check_peer(endpoint).is_ok())
.cloned()
.collect()
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn send_channel_message<Ch: DeRecChannelStore, T: DeRecTransport>(
channel_store: &Ch,
transport: &T,
secret_id: u64,
channel_id: ChannelId,
mut body: MessageBody,
shared_key: &SharedKey,
inbound_trace_id: u64,
policy: TransportPolicy,
reply_to: &[TransportProtocol],
obligation: Option<&crate::protocol::obligation::Obligation>,
status: derec_proto::StatusEnum,
memo: &str,
) -> Result<()> {
use crate::extensions::message_body::MessageBodyExt as _;
let timestamp = current_timestamp();
body.set_timestamp(timestamp);
let envelope = DeRecMessageBuilder::channel()
.channel_id(channel_id)
.timestamp(timestamp)
.message_body(body)
.trace_id(inbound_trace_id)
.encrypt(shared_key)?
.build()?;
let wire_bytes = envelope.encode_to_vec();
let endpoint = channel_store
.resolve_response_endpoints(secret_id, channel_id, policy, reply_to)
.await?;
crate::protocol::obligation::deliver(obligation, transport, &endpoint, wire_bytes, status, memo)
.await
}
fn retain_matching<T>(rows: Vec<T>, listing: &str, keep: impl Fn(&T) -> bool) -> Vec<T> {
let before = rows.len();
let kept: Vec<T> = rows.into_iter().filter(keep).collect();
#[cfg(feature = "logging")]
if kept.len() != before {
tracing::warn!(
listing,
returned = before,
kept = kept.len(),
"channel store did not apply the filter it was given; the excluded \
rows were dropped here, but the store is transferring rows the \
protocol discards and must apply the filter in its query"
);
}
#[cfg(not(feature = "logging"))]
let _ = (before, listing);
kept
}
#[cfg(test)]
mod defiant_store_tests {
use super::*;
use crate::protocol::tests::{InMemChannelStore, run_async};
use crate::protocol::traits::{ChannelStoreFuture, DeRecChannelStore};
use crate::protocol::types::{
ChannelQuery, ChannelRecord, ChannelStatus, HelperChannel, ReplicaMember, ReplicaRole,
};
use crate::types::ReplicaId;
const SECRET_ID: u64 = 0xDEF1;
const GROUP: ChannelId = ChannelId(500);
#[derive(Default)]
struct DefiantStore(InMemChannelStore);
impl DeRecChannelStore for DefiantStore {
fn load(
&self,
secret_id: u64,
query: ChannelQuery,
) -> ChannelStoreFuture<'_, Option<ChannelRecord>> {
self.0.load(secret_id, query)
}
fn save(&mut self, secret_id: u64, record: ChannelRecord) -> ChannelStoreFuture<'_, ()> {
self.0.save(secret_id, record)
}
fn remove(&mut self, secret_id: u64, query: ChannelQuery) -> ChannelStoreFuture<'_, bool> {
self.0.remove(secret_id, query)
}
fn helpers(
&self,
secret_id: u64,
_filter: HelperFilter,
) -> ChannelStoreFuture<'_, Vec<HelperChannel>> {
self.0.helpers(secret_id, HelperFilter::default())
}
fn replicas(
&self,
secret_id: u64,
_filter: ReplicaFilter,
) -> ChannelStoreFuture<'_, Vec<ReplicaMember>> {
self.0.replicas(secret_id, ReplicaFilter::default())
}
fn link_channel(
&mut self,
secret_id: u64,
a: ChannelId,
b: ChannelId,
) -> ChannelStoreFuture<'_, ()> {
self.0.link_channel(secret_id, a, b)
}
fn linked_channels(
&self,
secret_id: u64,
channel_id: ChannelId,
) -> ChannelStoreFuture<'_, Vec<ChannelId>> {
self.0.linked_channels(secret_id, channel_id)
}
}
async fn seed(store: &mut DefiantStore, replica_id: u64, status: ChannelStatus) {
store
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: GROUP,
replica_id: ReplicaId(replica_id),
transports: vec![TransportProtocol {
uri: "https://peer.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}],
communication_info: std::collections::HashMap::new(),
role: ReplicaRole::Destination,
status,
created_at: 0,
}),
)
.await
.expect("seed");
}
#[test]
fn a_by_id_filter_yields_only_that_member_even_when_the_store_ignores_it() {
run_async(async {
let mut store = DefiantStore::default();
for id in [7001u64, 7002, 7003] {
seed(&mut store, id, ChannelStatus::Paired).await;
}
let rows = store
.replicas_matching(
SECRET_ID,
ReplicaFilter {
ids: vec![ReplicaId(7002)],
..Default::default()
},
)
.await
.expect("listing");
assert_eq!(
rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
vec![7002],
"the defiant store returned the whole roster; only the named member may survive"
);
});
}
#[test]
fn a_status_filter_holds_even_when_the_store_ignores_it() {
run_async(async {
let mut store = DefiantStore::default();
seed(&mut store, 8001, ChannelStatus::Pending).await;
seed(&mut store, 8002, ChannelStatus::Paired).await;
seed(&mut store, 8003, ChannelStatus::Paired).await;
let rows = store
.replicas_matching(
SECRET_ID,
ReplicaFilter {
status: vec![ChannelStatus::Pending],
..Default::default()
},
)
.await
.expect("listing");
assert_eq!(
rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
vec![8001],
"a paired member must never reach a sweep that asked for pending ones"
);
});
}
#[test]
fn exclude_holds_even_when_the_store_ignores_it() {
run_async(async {
let mut store = DefiantStore::default();
for id in [9001u64, 9002] {
seed(&mut store, id, ChannelStatus::Paired).await;
}
let rows = store
.replicas_matching(
SECRET_ID,
ReplicaFilter {
exclude: vec![ReplicaId(9001)],
..Default::default()
},
)
.await
.expect("listing");
assert_eq!(
rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
vec![9002]
);
});
}
#[test]
fn a_conforming_store_is_unaffected() {
run_async(async {
let mut store = InMemChannelStore::default();
for (id, status) in [(1u64, ChannelStatus::Pending), (2, ChannelStatus::Paired)] {
store
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: GROUP,
replica_id: ReplicaId(id),
transports: Vec::new(),
communication_info: std::collections::HashMap::new(),
role: ReplicaRole::Destination,
status,
created_at: 0,
}),
)
.await
.expect("seed");
}
let rows = store
.replicas_matching(
SECRET_ID,
ReplicaFilter {
status: vec![ChannelStatus::Paired],
..Default::default()
},
)
.await
.expect("listing");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].replica_id.0, 2);
});
}
}
#[cfg(test)]
mod send_channel_message_tests {
use super::*;
use crate::extensions::derec_result::DeRecResultExt as _;
use crate::extensions::message_body::MessageBodyExt as _;
use crate::protocol::tests::{InMemChannelStore, RecordingTransport, run_async};
use crate::protocol::types::{ChannelRecord, HelperChannel};
const SECRET_ID: u64 = 0x5E4D;
const CHANNEL: ChannelId = ChannelId(77);
const KEY: SharedKey = [3u8; 32];
#[test]
fn send_channel_message_stamps_envelope_and_body_with_one_timestamp() {
run_async(async {
let mut channels = InMemChannelStore::default();
channels
.save(
SECRET_ID,
ChannelRecord::Helper(HelperChannel {
channel_id: CHANNEL,
transports: vec![TransportProtocol {
uri: "https://peer.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}],
communication_info: std::collections::HashMap::new(),
peer_role: SenderKind::Owner,
status: ChannelStatus::Paired,
created_at: 0,
weight: 1,
}),
)
.await
.expect("seed channel");
let transport = RecordingTransport::default();
let body = MessageBody::UpdateChannelInfoResponse(
derec_proto::UpdateChannelInfoResponseMessage {
result: Some(derec_proto::DeRecResult::ok()),
timestamp: Some(prost_types::Timestamp {
seconds: 1,
nanos: 0,
}),
},
);
send_channel_message(
&channels,
&transport,
SECRET_ID,
CHANNEL,
body,
&KEY,
0,
TransportPolicy::new(false),
&[],
None,
derec_proto::StatusEnum::Ok,
"",
)
.await
.expect("send");
let sent = transport.sent_envelopes();
assert_eq!(sent.len(), 1);
let envelope = derec_proto::DeRecMessage::decode(sent[0].as_slice()).expect("decode");
let inner = crate::derec_message::extract_inner_message(&envelope.message, &KEY)
.expect("decrypt");
assert!(envelope.timestamp.is_some());
assert_eq!(envelope.timestamp.as_ref(), inner.timestamp());
});
}
}
#[cfg(test)]
mod resolve_response_endpoints_tests {
use super::*;
use crate::protocol::tests::{InMemChannelStore, run_async};
use crate::protocol::types::{ChannelRecord, ChannelStatus, HelperChannel};
use crate::transport::TransportPolicy;
use derec_proto::Protocol;
const SECRET_ID: u64 = 0x1234;
const CHANNEL: ChannelId = ChannelId(42);
const STRICT: TransportPolicy = TransportPolicy::new(false);
fn endpoint(uri: &str) -> TransportProtocol {
TransportProtocol {
uri: uri.to_owned(),
protocol: Protocol::Https as i32,
}
}
async fn seeded_store() -> InMemChannelStore {
let mut store = InMemChannelStore::default();
store
.save(
SECRET_ID,
ChannelRecord::Helper(HelperChannel {
channel_id: CHANNEL,
transports: vec![endpoint("https://recorded.example")],
communication_info: std::collections::HashMap::new(),
peer_role: SenderKind::Owner,
status: ChannelStatus::Paired,
created_at: 0,
weight: 1,
}),
)
.await
.expect("seed channel");
store
}
#[test]
fn mixed_reply_to_keeps_only_the_allowed_entries() {
run_async(async {
let store = seeded_store().await;
let reply_to = vec![
endpoint("http://peer.example"),
endpoint("https://peer.example"),
];
let resolved = store
.resolve_response_endpoints(SECRET_ID, CHANNEL, STRICT, &reply_to)
.await
.expect("resolve");
assert_eq!(resolved, vec![endpoint("https://peer.example")]);
});
}
#[test]
fn all_refused_falls_back_to_recorded_endpoints() {
run_async(async {
let store = seeded_store().await;
let reply_to = vec![endpoint("http://peer.example")];
let resolved = store
.resolve_response_endpoints(SECRET_ID, CHANNEL, STRICT, &reply_to)
.await
.expect("resolve");
assert_eq!(resolved, vec![endpoint("https://recorded.example")]);
});
}
#[test]
fn all_allowed_reply_to_is_used_unfiltered() {
run_async(async {
let store = seeded_store().await;
let reply_to = vec![
endpoint("https://peer-a.example"),
endpoint("https://peer-b.example"),
];
let resolved = store
.resolve_response_endpoints(SECRET_ID, CHANNEL, STRICT, &reply_to)
.await
.expect("resolve");
assert_eq!(resolved, reply_to);
});
}
}