use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use crate::connect::proto::{
AccessToken, ConnectError, ConnectionDetailsPost, ConnectionDetailsRequest, FinalizePairing,
NodeId, PairingAttemptId, PairingRequest,
};
use crate::types::Timestamp;
use super::longpoll::{LongPoll, WaitingNode};
use super::pairing::PairingService;
use super::session::SessionService;
use super::subnet::LocalSubnets;
#[derive(Clone)]
pub struct Endpoint {
pairing: Arc<PairingService>,
session: Arc<SessionService>,
attempts: Arc<std::sync::Mutex<Vec<(PairingAttemptId, Attempt)>>>,
long_poll: Arc<LongPoll>,
clock: fn() -> Timestamp,
max_message_bytes: usize,
on_prepare: Option<Arc<dyn Fn(PrepareSignal) + Send + Sync>>,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PrepareSignal {
Prepare(crate::connect::proto::PreparePairing),
Cancel(crate::connect::proto::CancelPreparePairing),
}
#[derive(Debug, Clone, Copy)]
struct Attempt {
node: NodeId,
expires: Timestamp,
}
impl core::fmt::Debug for Endpoint {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Endpoint")
.field("pairing", &self.pairing)
.field("session", &self.session)
.finish_non_exhaustive()
}
}
impl Endpoint {
#[must_use]
pub fn new(pairing: Arc<PairingService>, session: Arc<SessionService>) -> Self {
Self {
pairing,
session,
attempts: Arc::new(std::sync::Mutex::new(Vec::new())),
long_poll: Arc::new(LongPoll::default()),
clock: Timestamp::now,
max_message_bytes: crate::codec::DecodeOptions::DEFAULT_MAX_BYTES,
on_prepare: None,
}
}
#[must_use]
pub const fn with_max_message_bytes(mut self, bytes: usize) -> Self {
self.max_message_bytes = bytes;
self
}
#[must_use]
pub const fn max_message_bytes(&self) -> usize {
self.max_message_bytes
}
#[must_use]
pub fn on_prepare_pairing(
mut self,
handler: impl Fn(PrepareSignal) + Send + Sync + 'static,
) -> Self {
self.on_prepare = Some(Arc::new(handler));
self
}
#[must_use]
pub fn with_clock(mut self, clock: fn() -> Timestamp) -> Self {
self.clock = clock;
self
}
#[must_use]
pub fn session(&self) -> &Arc<SessionService> {
&self.session
}
fn remember(&self, id: PairingAttemptId, node: NodeId, now: Timestamp) {
let Ok(mut attempts) = self.attempts.lock() else {
return;
};
attempts.retain(|(_, attempt)| attempt.expires > now);
attempts.push((
id,
Attempt {
node,
expires: now
.checked_add(crate::connect::proto::PAIRING_BUDGET)
.unwrap_or(now),
},
));
}
fn attempt_node(&self, bearer: &str, now: Timestamp) -> Option<NodeId> {
let attempts = self.attempts.lock().ok()?;
let mut found = None;
for (id, attempt) in attempts.iter() {
if id.verify(bearer) && attempt.expires > now {
found = Some(attempt.node);
}
}
found
}
fn forget(&self, bearer: &str) {
if let Ok(mut attempts) = self.attempts.lock() {
attempts.retain(|(id, _)| !id.verify(bearer));
}
}
pub const MAX_WAITING_NODES: usize = LongPoll::MAX_WAITING;
pub const MAX_NODES_PER_POLL: usize = LongPoll::MAX_PER_POLL;
pub fn instruct_waiting_node(&self, client: NodeId, action: crate::connect::proto::WaitAction) {
self.long_poll.instruct(client, action);
}
#[must_use]
pub fn waiting_nodes(&self) -> Vec<(NodeId, WaitingNode)> {
self.long_poll.waiting()
}
pub(super) fn now(&self) -> Timestamp {
(self.clock)()
}
#[must_use]
pub fn live_attempts(&self) -> usize {
self.attempts.lock().map_or(0, |attempts| attempts.len())
}
}
pub const API_VERSIONS: &[&str] = &["v1"];
pub fn router(endpoint: Endpoint) -> axum::Router {
axum::Router::new()
.route("/", get(versions))
.nest("/v1", authenticated_routes(endpoint))
.layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
}
async fn versions() -> Response {
(StatusCode::OK, Json(API_VERSIONS)).into_response()
}
pub const MAX_BODY_BYTES: usize = 64 * 1024;
pub fn lan_router(endpoint: Endpoint, subnets: LocalSubnets) -> axum::Router {
let lan_only = axum::Router::new()
.route("/endpoint", get(get_endpoint))
.route("/nodes", get(get_nodes))
.route("/preparePairing", post(prepare_pairing))
.route("/cancelPreparePairing", post(cancel_prepare_pairing))
.route("/waitForPairing", post(wait_for_pairing))
.with_state(endpoint.clone())
.layer(axum::middleware::from_fn_with_state(
subnets,
super::subnet::same_subnet,
));
axum::Router::new()
.route("/", get(versions))
.nest("/v1", authenticated_routes(endpoint).merge(lan_only))
.layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
}
fn authenticated_routes(endpoint: Endpoint) -> axum::Router {
axum::Router::new()
.route("/requestPairing", post(request_pairing))
.route(
"/requestConnectionDetails",
post(request_connection_details),
)
.route("/postConnectionDetails", post(post_connection_details))
.route("/finalizePairing", post(finalize_pairing))
.route("/initiateSession", post(initiate_session))
.route("/confirmAccessToken", post(confirm_access_token))
.route("/unpair", post(unpair))
.with_state(endpoint)
}
async fn request_pairing(
State(endpoint): State<Endpoint>,
PairingBody(request): PairingBody<PairingRequest>,
) -> Response {
let mut nonce = [0u8; 32];
let mut attempt = [0u8; 24];
if fill_random(&mut nonce).is_err() || fill_random(&mut attempt).is_err() {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
let Ok(attempt_id) = PairingAttemptId::from_entropy(&attempt) else {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
};
let bearer = attempt_id.clone();
let now = (endpoint.clock)();
match endpoint
.pairing
.request_pairing(&request, &nonce, attempt_id, now)
{
Ok((node, send_after, accepted)) => {
let wait = send_after.saturating_duration_since((endpoint.clock)());
if !wait.is_zero() {
tokio::time::sleep(core::time::Duration::from(wait)).await;
}
endpoint.remember(bearer, node, now);
crate::trace::event!(info, node = %node, "answered a pairing request");
(StatusCode::OK, Json(accepted)).into_response()
}
Err(e) => {
crate::trace::event!(warn, error = %e, "refused a pairing request");
pairing_error(e)
}
}
}
async fn request_connection_details(
State(endpoint): State<Endpoint>,
bearer: Bearer,
PairingBody(request): PairingBody<ConnectionDetailsRequest>,
) -> Response {
let now = (endpoint.clock)();
let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
return StatusCode::UNAUTHORIZED.into_response();
};
match endpoint
.pairing
.request_connection_details(
node,
&bearer.0,
&request.server_hmac_challenge_response,
now,
)
.await
{
Ok(details) => (StatusCode::OK, Json(details)).into_response(),
Err(e) => {
if matches!(e, ConnectError::ChallengeFailed) {
endpoint.forget(&bearer.0);
}
pairing_error(e)
}
}
}
async fn post_connection_details(
State(endpoint): State<Endpoint>,
bearer: Bearer,
PairingBody(request): PairingBody<ConnectionDetailsPost>,
) -> Response {
let now = (endpoint.clock)();
let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
return StatusCode::UNAUTHORIZED.into_response();
};
match endpoint
.pairing
.post_connection_details(
node,
&bearer.0,
&request.server_hmac_challenge_response,
request.connection_details,
now,
)
.await
{
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(e) => {
if matches!(e, ConnectError::ChallengeFailed) {
endpoint.forget(&bearer.0);
}
pairing_error(e)
}
}
}
async fn finalize_pairing(
State(endpoint): State<Endpoint>,
bearer: Bearer,
PairingBody(body): PairingBody<FinalizePairing>,
) -> Response {
let now = (endpoint.clock)();
let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
return StatusCode::UNAUTHORIZED.into_response();
};
let result = endpoint
.pairing
.finalize(node, &bearer.0, body.success, now)
.await;
endpoint.forget(&bearer.0);
match result {
Ok(finalized) => {
for key in &finalized.displaced {
endpoint.session.end_sessions(*key);
}
crate::trace::event!(
info,
node = %node,
success = body.success,
"pairing finalized"
);
StatusCode::NO_CONTENT.into_response()
}
Err(e) => {
crate::trace::event!(warn, error = %e, "finalization refused");
pairing_error(e)
}
}
}
async fn get_endpoint(State(endpoint): State<Endpoint>) -> Response {
(StatusCode::OK, Json(endpoint.pairing.endpoint().clone())).into_response()
}
async fn get_nodes(State(endpoint): State<Endpoint>) -> Response {
let nodes: Vec<crate::connect::proto::NodeDescription> = endpoint
.pairing
.store()
.nodes()
.into_iter()
.map(|(node, _alias)| node)
.collect();
(StatusCode::OK, Json(nodes)).into_response()
}
async fn prepare_pairing(
State(endpoint): State<Endpoint>,
PairingBody(body): PairingBody<crate::connect::proto::PreparePairing>,
) -> Response {
if let Some(handler) = &endpoint.on_prepare {
handler(PrepareSignal::Prepare(body));
}
StatusCode::NO_CONTENT.into_response()
}
async fn cancel_prepare_pairing(
State(endpoint): State<Endpoint>,
PairingBody(body): PairingBody<crate::connect::proto::CancelPreparePairing>,
) -> Response {
if let Some(handler) = &endpoint.on_prepare {
handler(PrepareSignal::Cancel(body));
}
StatusCode::NO_CONTENT.into_response()
}
async fn wait_for_pairing(
State(endpoint): State<Endpoint>,
PairingBody(nodes): PairingBody<Vec<crate::connect::proto::WaitForPairing>>,
) -> Response {
let instructions = endpoint.long_poll.poll(&nodes).await;
if instructions.is_empty() {
return StatusCode::NO_CONTENT.into_response();
}
(StatusCode::OK, Json(instructions)).into_response()
}
async fn initiate_session(
State(endpoint): State<Endpoint>,
bearer: Bearer,
SessionBody(request): SessionBody<crate::connect::proto::SessionRequest>,
) -> Response {
let mut entropy = [0u8; 32];
if fill_random(&mut entropy).is_err() {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
let token = AccessToken::new(bearer.0);
let now = (endpoint.clock)();
match endpoint
.session
.initiate_session(&token, &request, &entropy, now)
{
Ok(grant) => (StatusCode::OK, Json(grant)).into_response(),
Err(e) => session_error(e),
}
}
async fn confirm_access_token(State(endpoint): State<Endpoint>, bearer: Bearer) -> Response {
let mut entropy = [0u8; 32];
if fill_random(&mut entropy).is_err() {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
let token = AccessToken::new(bearer.0);
let now = (endpoint.clock)();
match endpoint.session.confirm_access_token(&token, &entropy, now) {
Ok((key, details)) => {
crate::trace::event!(info, node = %key.remote, "issued a communication token");
(StatusCode::OK, Json(details)).into_response()
}
Err(_) => StatusCode::UNAUTHORIZED.into_response(),
}
}
async fn unpair(
State(endpoint): State<Endpoint>,
bearer: Bearer,
SessionBody(request): SessionBody<crate::connect::proto::UnpairRequest>,
) -> Response {
let token = AccessToken::new(bearer.0);
match endpoint.session.unpair(&token, &request) {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(_) => StatusCode::UNAUTHORIZED.into_response(),
}
}
pub(super) struct Bearer(String);
impl Bearer {
pub(super) fn as_str(&self) -> &str {
&self.0
}
}
impl<S: Send + Sync> axum::extract::FromRequestParts<S> for Bearer {
type Rejection = StatusCode;
#[allow(clippy::unused_async_trait_impl)]
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
_state: &S,
) -> Result<Self, Self::Rejection> {
parts
.headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| {
let (scheme, token) = value.split_once(' ')?;
scheme.eq_ignore_ascii_case("Bearer").then_some(token)
})
.map(|token| Self(token.trim().to_string()))
.filter(|bearer| !bearer.0.is_empty())
.ok_or(StatusCode::UNAUTHORIZED)
}
}
pub(super) struct PairingBody<T>(pub T);
pub(super) struct SessionBody<T>(pub T);
fn parsing_error_pairing() -> Response {
(
StatusCode::BAD_REQUEST,
Json(crate::connect::proto::PairingRefused {
error_message: crate::connect::proto::PairingErrorMessage::ParsingError,
additional_info: None,
}),
)
.into_response()
}
fn parsing_error_session() -> Response {
(
StatusCode::BAD_REQUEST,
Json(crate::connect::proto::SessionRefused {
error_message: crate::connect::proto::SessionErrorMessage::ParsingError,
additional_info: None,
}),
)
.into_response()
}
impl<S, T> axum::extract::FromRequest<S> for PairingBody<T>
where
S: Send + Sync,
T: serde::de::DeserializeOwned,
{
type Rejection = Response;
async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
match Json::<T>::from_request(req, state).await {
Ok(Json(value)) => Ok(Self(value)),
Err(rejection) if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE => {
Err(rejection.into_response())
}
Err(_) => Err(parsing_error_pairing()),
}
}
}
impl<S, T> axum::extract::FromRequest<S> for SessionBody<T>
where
S: Send + Sync,
T: serde::de::DeserializeOwned,
{
type Rejection = Response;
async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
match Json::<T>::from_request(req, state).await {
Ok(Json(value)) => Ok(Self(value)),
Err(rejection) if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE => {
Err(rejection.into_response())
}
Err(_) => Err(parsing_error_session()),
}
}
}
fn pairing_error(error: ConnectError) -> Response {
match error {
ConnectError::RateLimited => StatusCode::SERVICE_UNAVAILABLE.into_response(),
ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
ConnectError::ChallengeFailed => StatusCode::FORBIDDEN.into_response(),
ConnectError::Refused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
ConnectError::Expired { .. } | ConnectError::OutOfOrder { .. } => {
StatusCode::BAD_REQUEST.into_response()
}
_ => StatusCode::BAD_REQUEST.into_response(),
}
}
fn session_error(error: ConnectError) -> Response {
match error {
ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
ConnectError::SessionRefused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
_ => StatusCode::BAD_REQUEST.into_response(),
}
}
use super::fill_random;
#[cfg(test)]
mod tests {
use super::*;
fn at(secs: i64) -> Timestamp {
Timestamp::from_unix(1_700_000_000 + secs, 0)
}
fn endpoint() -> Endpoint {
let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
Endpoint::new(
Arc::new(PairingService::wan(
store.clone(),
crate::connect::proto::EndpointDescription::default(),
"pairing.example.com",
)),
Arc::new(SessionService::new(store, "wss://example.com/s2")),
)
}
#[test]
fn an_attempt_stops_authenticating_when_its_budget_runs_out() {
let endpoint = endpoint();
let node = NodeId::parse("cem-1").expect("a legal id");
endpoint.remember(PairingAttemptId::new("bearer-one"), node, at(0));
assert_eq!(endpoint.attempt_node("bearer-one", at(0)), Some(node));
assert_eq!(endpoint.attempt_node("bearer-one", at(14)), Some(node));
assert_eq!(endpoint.attempt_node("bearer-one", at(15)), None);
assert_eq!(endpoint.attempt_node("bearer-one", at(16)), None);
assert_eq!(endpoint.attempt_node("not-a-bearer", at(0)), None);
}
#[test]
fn abandoned_attempts_are_swept_rather_than_accumulated() {
let endpoint = endpoint();
let node = NodeId::parse("cem-1").expect("a legal id");
for i in 0..100 {
endpoint.remember(
PairingAttemptId::new(alloc::format!("abandoned-{i}")),
node,
at(i),
);
}
assert!(
endpoint.live_attempts() <= 16,
"expected at most one budget's worth, got {}",
endpoint.live_attempts()
);
endpoint.remember(PairingAttemptId::new("fresh"), node, at(1_000));
assert_eq!(endpoint.live_attempts(), 1);
assert_eq!(
endpoint.attempt_node("fresh", at(1_000)),
Some(node),
"and the new one is the survivor"
);
}
#[test]
fn finalizing_forgets_the_attempt_immediately() {
let endpoint = endpoint();
let node = NodeId::parse("cem-1").expect("a legal id");
endpoint.remember(PairingAttemptId::new("bearer"), node, at(0));
assert_eq!(endpoint.live_attempts(), 1);
endpoint.forget("bearer");
assert_eq!(endpoint.live_attempts(), 0);
assert_eq!(endpoint.attempt_node("bearer", at(0)), None);
}
#[test]
fn the_status_codes_are_the_ones_the_specification_distinguishes() {
let code = |e: ConnectError| pairing_error(e).status();
assert_eq!(
code(ConnectError::RateLimited),
StatusCode::SERVICE_UNAVAILABLE
);
assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
assert_eq!(code(ConnectError::ChallengeFailed), StatusCode::FORBIDDEN);
assert_eq!(
code(ConnectError::Refused(
crate::connect::proto::PairingRefused {
error_message: crate::connect::proto::PairingErrorMessage::NodeNotFound,
additional_info: None,
}
)),
StatusCode::BAD_REQUEST
);
let code = |e: ConnectError| session_error(e).status();
assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
assert_eq!(
code(ConnectError::SessionRefused(
crate::connect::proto::SessionRefused {
error_message: crate::connect::proto::SessionErrorMessage::NoLongerPaired,
additional_info: None,
}
)),
StatusCode::BAD_REQUEST
);
}
}
#[cfg(test)]
mod subnet_wiring {
use super::*;
use tower::ServiceExt as _;
fn endpoint() -> Endpoint {
let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
Endpoint::new(
Arc::new(PairingService::lan(
store.clone(),
crate::connect::proto::EndpointDescription::default(),
crate::connect::tls::Fingerprint::parse(&"AA".repeat(32)).expect("a fingerprint"),
)),
Arc::new(SessionService::new(store, "wss://example.com/s2")),
)
}
async fn get(app: axum::Router, peer: Option<std::net::SocketAddr>) -> StatusCode {
let mut request = axum::http::Request::builder()
.uri("/v1/endpoint")
.body(axum::body::Body::empty())
.expect("a request");
if let Some(peer) = peer {
request
.extensions_mut()
.insert(axum::extract::ConnectInfo(peer));
}
app.oneshot(request)
.await
.expect("the router answers")
.status()
}
#[tokio::test]
async fn the_lan_routes_admit_a_local_peer_and_refuse_a_remote_one() {
let subnets =
LocalSubnets::from_prefixes([("192.168.1.10".parse().expect("an address"), 24)]);
let app = lan_router(endpoint(), subnets);
let local: std::net::SocketAddr = "192.168.1.50:9000".parse().expect("an address");
assert_eq!(get(app.clone(), Some(local)).await, StatusCode::OK);
let remote: std::net::SocketAddr = "8.8.8.8:9000".parse().expect("an address");
assert_eq!(
get(app.clone(), Some(remote)).await,
StatusCode::UNAUTHORIZED
);
assert_eq!(get(app, None).await, StatusCode::UNAUTHORIZED);
}
async fn body(response: axum::response::Response) -> String {
let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)
.await
.expect("a body");
String::from_utf8(bytes.to_vec()).expect("UTF-8")
}
#[tokio::test(start_paused = true)]
async fn a_long_poll_with_nothing_to_say_is_no_content() {
let subnets =
LocalSubnets::from_prefixes([("192.168.1.10".parse().expect("an address"), 24)]);
let app = lan_router(endpoint(), subnets);
let mut request = axum::http::Request::builder()
.method("POST")
.uri("/v1/waitForPairing")
.header("content-type", "application/json")
.body(axum::body::Body::from(r#"[{"clientNodeId":"rm-1"}]"#))
.expect("a request");
let peer: std::net::SocketAddr = "192.168.1.50:9000".parse().expect("an address");
request
.extensions_mut()
.insert(axum::extract::ConnectInfo(peer));
let response = app.oneshot(request).await.expect("an answer");
assert_eq!(response.status(), StatusCode::NO_CONTENT);
}
#[tokio::test]
async fn the_version_index_answers_at_the_root() {
let request = axum::http::Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.expect("a request");
let response = router(endpoint())
.oneshot(request)
.await
.expect("an answer");
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(body(response).await, r#"["v1"]"#);
}
#[tokio::test]
async fn a_body_that_does_not_parse_is_a_named_parsing_error() {
for (path, field) in [
("/v1/requestPairing", "PairingResponseErrorMessage"),
("/v1/initiateSession", "CommunicationDetailsErrorMessage"),
] {
let request = axum::http::Request::builder()
.method("POST")
.uri(path)
.header("content-type", "application/json")
.header("authorization", "Bearer x")
.body(axum::body::Body::from("{\"not\": \"a request\"}"))
.expect("a request");
let response = router(endpoint())
.oneshot(request)
.await
.expect("an answer");
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{path}");
let text = body(response).await;
assert!(text.contains("ParsingError"), "{path} ({field}): {text}");
}
}
#[tokio::test]
async fn the_wan_router_has_no_lan_routes_to_admit_anyone_to() {
let app = router(endpoint());
let local: std::net::SocketAddr = "127.0.0.1:9000".parse().expect("an address");
assert_eq!(get(app, Some(local)).await, StatusCode::NOT_FOUND);
}
}