use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::Arc;
use crate::connect::proto::{
ConnectError, ConnectionDetails, EndpointDescription, HmacBinding, NodeId, PairingAccepted,
PairingAttemptId, PairingErrorMessage, PairingRefused, PairingRequest, PairingServer,
};
use crate::connect::tls::Fingerprint;
use crate::types::Timestamp;
use super::store::{PairedNode, Store};
pub struct PairingService {
store: Arc<dyn Store>,
attempts: std::sync::Mutex<BTreeMap<NodeId, Arc<tokio::sync::Mutex<PairingServer>>>>,
endpoint: EndpointDescription,
binding: HmacBinding,
details: Option<ConnectionDetails>,
}
impl core::fmt::Debug for PairingService {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PairingService")
.field("endpoint", &self.endpoint)
.field("binding", &self.binding)
.finish_non_exhaustive()
}
}
impl PairingService {
#[must_use]
pub fn lan(store: Arc<dyn Store>, endpoint: EndpointDescription, leaf: Fingerprint) -> Self {
Self {
store,
attempts: std::sync::Mutex::new(BTreeMap::new()),
endpoint,
binding: leaf.binding(),
details: None,
}
}
#[must_use]
pub fn wan(
store: Arc<dyn Store>,
endpoint: EndpointDescription,
domain: impl Into<String>,
) -> Self {
Self {
store,
attempts: std::sync::Mutex::new(BTreeMap::new()),
endpoint,
binding: HmacBinding::DomainName(domain.into()),
details: None,
}
}
#[must_use]
pub fn with_connection_details(mut self, details: ConnectionDetails) -> Self {
self.details = Some(details);
self
}
#[must_use]
pub fn store(&self) -> &Arc<dyn Store> {
&self.store
}
#[must_use]
pub fn endpoint(&self) -> &EndpointDescription {
&self.endpoint
}
fn target(&self, request: &PairingRequest) -> Result<NodeId, ConnectError> {
match (&request.node_id, &request.node_id_alias) {
(Some(_), Some(_)) => Err(refused(PairingErrorMessage::ParsingError)),
(Some(id), None) => self
.store
.node(*id)
.map(|n| n.id)
.ok_or_else(|| refused(PairingErrorMessage::NodeNotFound)),
(None, Some(alias)) => self
.store
.resolve_alias(alias)
.ok_or_else(|| refused(PairingErrorMessage::NodeNotFound)),
(None, None) => self
.store
.sole_node()
.ok_or_else(|| refused(PairingErrorMessage::NoNodeIdProvided)),
}
}
fn machine(
&self,
node: NodeId,
) -> Result<Arc<tokio::sync::Mutex<PairingServer>>, ConnectError> {
let description = self
.store
.node(node)
.ok_or_else(|| refused(PairingErrorMessage::NodeNotFound))?;
let mut attempts = self
.attempts
.lock()
.map_err(|_| refused(PairingErrorMessage::Other))?;
Ok(attempts
.entry(node)
.or_insert_with(|| {
Arc::new(tokio::sync::Mutex::new(PairingServer::new(
description,
self.endpoint.clone(),
self.binding.clone(),
)))
})
.clone())
}
pub fn request_pairing(
&self,
request: &PairingRequest,
server_nonce: &[u8],
attempt_id: PairingAttemptId,
now: Timestamp,
) -> Result<(NodeId, Timestamp, PairingAccepted), ConnectError> {
let node = self.target(request)?;
let token = self
.store
.pairing_token(node)
.ok_or_else(|| refused(PairingErrorMessage::NoValidPairingTokenOnPairingServer))?;
let machine = self.machine(node)?;
let Ok(mut guard) = machine.try_lock() else {
return Err(ConnectError::RateLimited);
};
let (send_after, accepted) =
guard.request_pairing(request, &token, server_nonce, attempt_id, now)?;
Ok((node, send_after, accepted))
}
pub async fn request_connection_details(
&self,
node: NodeId,
bearer: &str,
response: &str,
now: Timestamp,
) -> Result<ConnectionDetails, ConnectError> {
let machine = self.machine(node)?;
let mut guard = machine.lock().await;
if !guard.authenticates(bearer) {
return Err(ConnectError::NotPaired);
}
guard.verify_client(response, now)?;
let details = self
.details
.clone()
.ok_or_else(|| refused(PairingErrorMessage::IncompatibleCommunicationProtocols))?;
guard.connection_details(details)
}
pub async fn post_connection_details(
&self,
node: NodeId,
bearer: &str,
response: &str,
details: ConnectionDetails,
now: Timestamp,
) -> Result<(), ConnectError> {
let machine = self.machine(node)?;
let mut guard = machine.lock().await;
if !guard.authenticates(bearer) {
return Err(ConnectError::NotPaired);
}
guard.verify_client(response, now)?;
guard.accept_connection_details(details)
}
pub async fn finalize(
&self,
node: NodeId,
bearer: &str,
success: bool,
now: Timestamp,
) -> Result<(), ConnectError> {
let machine = self.machine(node)?;
let mut guard = machine.lock().await;
if !guard.authenticates(bearer) {
return Err(ConnectError::NotPaired);
}
let pairing = guard.finalize(crate::connect::proto::FinalizePairing { success }, now)?;
drop(guard);
if let Some(pairing) = pairing {
let local_role = self.store.node(pairing.local).map(|n| n.role);
self.store.pair(PairedNode {
local: pairing.local,
remote: pairing.remote.clone(),
tokens: crate::connect::proto::TokenStore::new(
pairing.details.access_token.clone(),
),
details: Some(pairing.details),
});
if local_role == Some(crate::connect::proto::Role::Rm) {
for previous in self.store.paired_with(pairing.local) {
if previous != pairing.remote.id {
crate::trace::event!(
info,
node = %pairing.local,
unpaired = %previous,
"a Resource Manager pairs with one CEM at a time"
);
self.store.unpair(previous);
}
}
}
}
Ok(())
}
}
fn refused(message: PairingErrorMessage) -> ConnectError {
ConnectError::Refused(PairingRefused {
error_message: message,
additional_info: None,
})
}