use super::super::{
DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecShareStore, DeRecStateStore,
DeRecTransport, PendingAction, SecretKind, SecretValue, StateItem, StateKey, events::UnpairAck,
};
use super::replicas::unpairing as replica;
use crate::derec_message::current_timestamp;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::extensions::message_body::{MessageBodyExt as _, Route};
use crate::protocol::context::{Exchange, Local, Round};
use crate::protocol::stores::{StoreSet, Stores};
use crate::protocol::types::{ChannelQuery, ChannelRecord, ChannelStatus};
use crate::{
Error, Result,
primitives::unpairing::{
request::produce as produce_unpair_request,
response::{self as unpairing_response, process as process_unpair_response},
},
types::ChannelId,
};
use derec_proto::{
DeRecResult, MessageBody, SenderKind, StatusEnum, UnpairRequestMessage, UnpairResponseMessage,
};
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
pub(in crate::protocol) async fn handle<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
exchange: &Exchange<'_>,
inner: MessageBody,
) -> Result<Vec<DeRecEvent>> {
match (inner.route(), inner) {
(Route::Replica(target), inner) => replica::handle(stores, local, target, inner).await,
(_, MessageBody::UnpairRequest(request)) => {
stores
.channels
.require_role(local.secret_id, &[exchange.channel_id], SenderKind::Owner)
.await?;
on_request(exchange, request)
}
(_, MessageBody::UnpairResponse(response)) => {
on_response(stores, local, exchange, &response).await
}
_ => Err(Error::Invariant(
"unexpected MessageBody variant in unpairing handler",
)),
}
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = round.trace_id)))]
pub(in crate::protocol) async fn start<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
channel_id: ChannelId,
memo: Option<String>,
unpair_ack: UnpairAck,
now: u64,
round: &Round<'_>,
) -> Result<Vec<DeRecEvent>> {
let secret_id = local.secret_id;
let memo_str = memo.unwrap_or_default();
let mut events = vec![DeRecEvent::UnpairStarted {
channel_id,
trace_id: round.trace_id,
}];
let shared_key = match stores
.secrets
.load(secret_id, channel_id, SecretKind::SharedKey)
.await?
{
Some(SecretValue::SharedKey(k)) => k,
_ => {
return Err(crate::Error::InvalidInput(
"channel has no shared key — not yet paired",
));
}
};
let request = produce_unpair_request(channel_id, &memo_str, &shared_key, round.reply_to, None)?;
let envelope = crate::derec_message::apply_trace_id(&request.envelope, round.trace_id)?;
let endpoint = stores
.channels
.peer_endpoints(secret_id, channel_id)
.await?;
stores.transport.send(&endpoint, envelope).await?;
match unpair_ack {
UnpairAck::NotRequired => {
drop_channel_state(stores, local, channel_id).await?;
events.push(DeRecEvent::Unpaired { channel_id });
}
UnpairAck::Required => {
stores
.state
.save(
secret_id,
StateItem::PendingUnpair {
channel_id,
started_at: now,
},
)
.await?;
set_status(
stores,
local,
channel_id,
ChannelStatus::Paired,
ChannelStatus::Unpairing,
)
.await?;
}
}
#[cfg(feature = "logging")]
tracing::debug!(
channel_id = channel_id.0,
ack = ?unpair_ack,
"unpair request sent"
);
Ok(events)
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
pub(in crate::protocol) async fn accept<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
exchange: &Exchange<'_>,
request: &UnpairRequestMessage,
) -> Result<Vec<DeRecEvent>> {
let channel_id = exchange.channel_id;
let resp = unpairing_response::produce(channel_id, exchange.shared_key)?;
let envelope = crate::derec_message::apply_trace_id(&resp.envelope, exchange.trace_id)?;
let endpoint = stores
.channels
.resolve_response_endpoints(
local.secret_id,
channel_id,
local.policy,
&crate::extensions::advertised_endpoints::reply_to_owned(request),
)
.await?;
let sent = crate::protocol::obligation::deliver(
exchange.obligation,
stores.transport,
&endpoint,
envelope,
StatusEnum::Ok,
"",
)
.await;
if sent.is_err() && !crate::protocol::obligation::attempted(exchange.obligation) {
return sent.map(|()| Vec::new());
}
let dropped = drop_channel_state(stores, local, channel_id).await;
#[cfg(feature = "logging")]
tracing::info!("unpair accepted; local state dropped");
crate::protocol::obligation::reported(
exchange.obligation,
vec![DeRecEvent::Unpaired { channel_id }],
sent.and(dropped),
)
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0, status = status as i32))
)]
pub(in crate::protocol) async fn reject<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
exchange: &Exchange<'_>,
request: &UnpairRequestMessage,
status: StatusEnum,
memo: &str,
) -> Result<()> {
crate::extensions::channel_store::send_channel_message(
stores.channels,
stores.transport,
local.secret_id,
exchange.channel_id,
failure_response(status, memo),
exchange.shared_key,
exchange.trace_id,
local.policy,
&crate::extensions::advertised_endpoints::reply_to_owned(request),
exchange.obligation,
status,
memo,
)
.await
}
pub(in crate::protocol) fn failure_response(status: StatusEnum, memo: &str) -> MessageBody {
MessageBody::UnpairResponse(UnpairResponseMessage {
result: Some(DeRecResult {
status: status as i32,
memo: memo.to_owned(),
}),
timestamp: Some(current_timestamp()),
})
}
pub(in crate::protocol) async fn drop_channel_state<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
channel_id: ChannelId,
) -> Result<()> {
let secret_id = local.secret_id;
stores.shares.remove_channel(secret_id, channel_id).await?;
let _ = stores
.secrets
.remove(secret_id, channel_id, SecretKind::SharedKey)
.await;
let _ = stores
.secrets
.remove(secret_id, channel_id, SecretKind::PairingSecret)
.await;
let _ = stores
.secrets
.remove(secret_id, channel_id, SecretKind::PairingContact)
.await;
let _ = stores
.channels
.remove(
secret_id,
crate::protocol::types::ChannelQuery::Helper { channel_id },
)
.await?;
Ok(())
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
fn on_request(exchange: &Exchange<'_>, request: UnpairRequestMessage) -> Result<Vec<DeRecEvent>> {
Ok(vec![DeRecEvent::ActionRequired {
channel_id: exchange.channel_id,
action: PendingAction::Unpair {
channel_id: exchange.channel_id,
request,
shared_key: *exchange.shared_key,
trace_id: exchange.trace_id,
},
}])
}
#[cfg_attr(
feature = "logging",
tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
async fn on_response<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
exchange: &Exchange<'_>,
response: &UnpairResponseMessage,
) -> Result<Vec<DeRecEvent>> {
if !stores
.state
.remove(
local.secret_id,
StateKey::PendingUnpair {
channel_id: exchange.channel_id,
},
)
.await?
{
return Ok(vec![DeRecEvent::NoOp]);
}
match process_unpair_response(response) {
Ok(_) => {
drop_channel_state(stores, local, exchange.channel_id).await?;
Ok(vec![DeRecEvent::Unpaired {
channel_id: exchange.channel_id,
}])
}
Err(Error::Unpairing(crate::primitives::unpairing::UnpairingError::NonOkStatus {
status,
memo,
})) => {
set_status(
stores,
local,
exchange.channel_id,
ChannelStatus::Unpairing,
ChannelStatus::Paired,
)
.await?;
Ok(vec![DeRecEvent::UnpairRejected {
channel_id: exchange.channel_id,
status,
memo,
}])
}
Err(e) => Err(e),
}
}
async fn set_status<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
channel_id: ChannelId,
from: ChannelStatus,
to: ChannelStatus,
) -> Result<()> {
let Some(mut helper) = stores
.channels
.load(local.secret_id, ChannelQuery::Helper { channel_id })
.await?
.and_then(|record| record.as_helper().cloned())
.filter(|helper| helper.status == from)
else {
return Ok(());
};
helper.status = to;
stores
.channels
.save(local.secret_id, ChannelRecord::Helper(helper))
.await?;
Ok(())
}