use alloc::string::{String, ToString};
use alloc::vec::Vec;
use crate::connect::proto::{
ConnectionDetails, Deployment, EndpointDescription, HmacBinding, NextStep, NodeDescription,
Pairing as ProtoPairing, PairingClient, PairingCode,
};
use crate::connect::tls::{CapturedIdentity, Fingerprint, TlsPolicy};
use crate::types::{ProtocolVersion, Timestamp};
use super::http::{Error, Http};
const REQUEST_PAIRING: &str = "requestPairing";
const REQUEST_CONNECTION_DETAILS: &str = "requestConnectionDetails";
const POST_CONNECTION_DETAILS: &str = "postConnectionDetails";
const FINALIZE_PAIRING: &str = "finalizePairing";
#[derive(Debug)]
pub struct Paired {
pub pairing: ProtoPairing,
pub identity: Option<CapturedIdentity>,
}
impl Paired {
#[must_use]
pub fn pin(&self) -> Option<Fingerprint> {
self.identity.as_ref().map(|identity| identity.root)
}
#[must_use]
pub fn policy(&self) -> TlsPolicy {
self.pin().map_or(TlsPolicy::Web, TlsPolicy::Pinned)
}
}
#[derive(Debug)]
pub struct Pairing {
http: Http,
local: NodeDescription,
local_endpoint: EndpointDescription,
deployment: Deployment,
domain: Option<String>,
s2_message_versions: Option<Vec<ProtocolVersion>>,
force: bool,
clock: fn() -> Timestamp,
}
impl Pairing {
pub const REQUEST_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(10);
pub fn lan(
base_url: &str,
local: NodeDescription,
local_endpoint: EndpointDescription,
) -> Result<Self, Error> {
Ok(Self {
http: Http::new(base_url, &TlsPolicy::LanPairingOnly, Self::REQUEST_TIMEOUT)?,
local,
local_endpoint,
deployment: Deployment::Lan,
domain: None,
s2_message_versions: None,
force: false,
clock: Timestamp::now,
})
}
pub fn wan(
base_url: &str,
local: NodeDescription,
local_endpoint: EndpointDescription,
) -> Result<Self, Error> {
let http = Http::new(base_url, &TlsPolicy::Web, Self::REQUEST_TIMEOUT)?;
let domain = http
.base()
.host_str()
.ok_or_else(|| Error::Url(base_url.to_string()))?
.to_string();
Ok(Self {
http,
local,
local_endpoint,
deployment: Deployment::Wan,
domain: Some(domain),
s2_message_versions: None,
force: false,
clock: Timestamp::now,
})
}
#[must_use]
pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
self.s2_message_versions = Some(versions);
self
}
#[must_use]
pub fn forcing(mut self) -> Self {
self.force = true;
self
}
#[must_use]
pub fn with_clock(mut self, clock: fn() -> Timestamp) -> Self {
self.clock = clock;
self
}
pub async fn run(&self, code: PairingCode, now: Timestamp) -> Result<Paired, Error> {
let mut nonce = [0u8; 32];
fill_random(&mut nonce)?;
self.run_with_entropy(code, now, &nonce, None).await
}
pub async fn run_with_entropy(
&self,
code: PairingCode,
now: Timestamp,
client_nonce: &[u8],
own_details: Option<ConnectionDetails>,
) -> Result<Paired, Error> {
let mut machine = self.machine(code, now);
let body = machine.request_pairing(client_nonce)?;
crate::trace::event!(
info,
deployment = ?self.deployment,
alias = ?body.node_id_alias,
"requesting pairing"
);
let accepted: crate::connect::proto::PairingAccepted = self
.http
.post("requestPairing", REQUEST_PAIRING, None, &body)
.await?;
let bearer_of = |machine: &PairingClient| {
machine
.attempt_id()
.map(|id| id.as_str().to_string())
.unwrap_or_default()
};
match self.finish(&mut machine, accepted, own_details).await {
Ok(paired) => Ok(paired),
Err(e) => {
let bearer = bearer_of(&machine);
if !bearer.is_empty() {
crate::trace::event!(
info,
error = %e,
"releasing the pairing attempt after a failure"
);
self.abandon(&bearer).await;
}
Err(e)
}
}
}
async fn finish(
&self,
machine: &mut PairingClient,
accepted: crate::connect::proto::PairingAccepted,
own_details: Option<ConnectionDetails>,
) -> Result<Paired, Error> {
let identity = self.http.tls().captured();
if !self.http.tls().identity_is_stable() {
return Err(Error::IdentityChanged);
}
let binding = match &self.domain {
Some(domain) => HmacBinding::DomainName(domain.clone()),
None => identity
.as_ref()
.map(|i| i.leaf.binding())
.ok_or(Error::IdentityChanged)?,
};
crate::trace::event!(debug, binding = ?binding, "checking the server's response");
let next = machine.accept(accepted, binding, self.deployment, (self.clock)())?;
crate::trace::event!(info, next = ?next, "the server authenticated");
let bearer = machine
.attempt_id()
.map(|id| id.as_str().to_string())
.unwrap_or_default();
match next {
NextStep::RequestConnectionDetails => {
let ask = machine.request_connection_details()?;
let details: ConnectionDetails = self
.http
.post(
"requestConnectionDetails",
REQUEST_CONNECTION_DETAILS,
Some(&bearer),
&ask,
)
.await?;
machine.connection_details(details, (self.clock)())?;
}
NextStep::PostConnectionDetails => {
let details = own_details.ok_or(Error::Protocol(
crate::connect::proto::ConnectError::OutOfOrder {
got: "a pairing in which this node is the communication server",
expected: "connection details to offer",
},
))?;
let post = machine.post_connection_details(details, (self.clock)())?;
self.http
.post_empty(
"postConnectionDetails",
POST_CONNECTION_DETAILS,
Some(&bearer),
Some(&post),
)
.await?;
}
}
if !self.http.tls().identity_is_stable() {
return Err(Error::IdentityChanged);
}
let (body, pairing) = machine.finalize((self.clock)())?;
crate::trace::event!(
info,
remote = %pairing.remote.id,
communication_server = ?pairing.communication_server,
"pairing complete"
);
self.http
.post_empty(
"finalizePairing",
FINALIZE_PAIRING,
Some(&bearer),
Some(&body),
)
.await?;
Ok(Paired {
pairing,
identity: (self.deployment == Deployment::Lan)
.then_some(identity)
.flatten(),
})
}
pub async fn abandon(&self, bearer: &str) {
let body = crate::connect::proto::FinalizePairing { success: false };
let _ = self
.http
.post_empty(
"finalizePairing",
FINALIZE_PAIRING,
Some(bearer),
Some(&body),
)
.await;
}
fn machine(&self, code: PairingCode, now: Timestamp) -> PairingClient {
let mut machine =
PairingClient::start(self.local.clone(), self.local_endpoint.clone(), code, now);
if let Some(versions) = &self.s2_message_versions {
machine = machine.with_s2_message_versions(versions.clone());
}
if self.force {
machine = machine.forcing();
}
machine
}
}
pub(crate) fn fill_random(buffer: &mut [u8]) -> Result<(), Error> {
use rand::TryRng as _;
rand::rngs::SysRng
.try_fill_bytes(buffer)
.map_err(|e| Error::Transport {
operation: "drawing randomness",
source: Box::new(e),
})
}