1use alloc::string::{String, ToString};
7use alloc::sync::Arc;
8use alloc::vec::Vec;
9
10use axum::Json;
11use axum::extract::State;
12use axum::http::StatusCode;
13use axum::response::{IntoResponse, Response};
14use axum::routing::{get, post};
15
16use crate::connect::proto::{
17 AccessToken, ConnectError, ConnectionDetailsPost, ConnectionDetailsRequest, FinalizePairing,
18 NodeId, PairingAttemptId, PairingRequest,
19};
20use crate::types::Timestamp;
21
22use super::longpoll::{LongPoll, WaitingNode};
23use super::pairing::PairingService;
24use super::session::SessionService;
25use super::subnet::LocalSubnets;
26
27#[derive(Clone)]
31pub struct Endpoint {
32 pairing: Arc<PairingService>,
33 session: Arc<SessionService>,
34 attempts: Arc<std::sync::Mutex<Vec<(PairingAttemptId, Attempt)>>>,
47 long_poll: Arc<LongPoll>,
49 clock: fn() -> Timestamp,
50 on_prepare: Option<Arc<dyn Fn(PrepareSignal) + Send + Sync>>,
52}
53
54#[derive(Debug, Clone)]
65#[non_exhaustive]
66pub enum PrepareSignal {
67 Prepare(crate::connect::proto::PreparePairing),
69 Cancel(crate::connect::proto::CancelPreparePairing),
71}
72
73#[derive(Debug, Clone, Copy)]
75struct Attempt {
76 node: NodeId,
77 expires: Timestamp,
79}
80
81impl core::fmt::Debug for Endpoint {
82 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
83 f.debug_struct("Endpoint")
84 .field("pairing", &self.pairing)
85 .field("session", &self.session)
86 .finish_non_exhaustive()
87 }
88}
89
90impl Endpoint {
91 #[must_use]
93 pub fn new(pairing: Arc<PairingService>, session: Arc<SessionService>) -> Self {
94 Self {
95 pairing,
96 session,
97 attempts: Arc::new(std::sync::Mutex::new(Vec::new())),
98 long_poll: Arc::new(LongPoll::default()),
99 clock: Timestamp::now,
100 on_prepare: None,
101 }
102 }
103
104 #[must_use]
111 pub fn on_prepare_pairing(
112 mut self,
113 handler: impl Fn(PrepareSignal) + Send + Sync + 'static,
114 ) -> Self {
115 self.on_prepare = Some(Arc::new(handler));
116 self
117 }
118
119 #[must_use]
121 pub fn with_clock(mut self, clock: fn() -> Timestamp) -> Self {
122 self.clock = clock;
123 self
124 }
125
126 #[must_use]
128 pub fn session(&self) -> &Arc<SessionService> {
129 &self.session
130 }
131
132 fn remember(&self, id: PairingAttemptId, node: NodeId, now: Timestamp) {
133 let Ok(mut attempts) = self.attempts.lock() else {
134 return;
135 };
136 attempts.retain(|(_, attempt)| attempt.expires > now);
139 attempts.push((
140 id,
141 Attempt {
142 node,
143 expires: now
144 .checked_add(crate::connect::proto::PAIRING_BUDGET)
145 .unwrap_or(now),
146 },
147 ));
148 }
149
150 fn attempt_node(&self, bearer: &str, now: Timestamp) -> Option<NodeId> {
162 let attempts = self.attempts.lock().ok()?;
163 let mut found = None;
165 for (id, attempt) in attempts.iter() {
166 if id.verify(bearer) && attempt.expires > now {
167 found = Some(attempt.node);
168 }
169 }
170 found
171 }
172
173 fn forget(&self, bearer: &str) {
174 if let Ok(mut attempts) = self.attempts.lock() {
175 attempts.retain(|(id, _)| !id.verify(bearer));
176 }
177 }
178
179 pub const MAX_WAITING_NODES: usize = LongPoll::MAX_WAITING;
184
185 pub const MAX_NODES_PER_POLL: usize = LongPoll::MAX_PER_POLL;
187
188 pub fn instruct_waiting_node(&self, client: NodeId, action: crate::connect::proto::WaitAction) {
195 self.long_poll.instruct(client, action);
196 }
197
198 #[must_use]
203 pub fn waiting_nodes(&self) -> Vec<(NodeId, WaitingNode)> {
204 self.long_poll.waiting()
205 }
206
207 pub(super) fn now(&self) -> Timestamp {
209 (self.clock)()
210 }
211
212 #[must_use]
214 pub fn live_attempts(&self) -> usize {
215 self.attempts.lock().map_or(0, |attempts| attempts.len())
216 }
217}
218
219pub fn router(endpoint: Endpoint) -> axum::Router {
225 axum::Router::new()
226 .nest("/v1", authenticated_routes(endpoint))
227 .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
228}
229
230pub const MAX_BODY_BYTES: usize = 64 * 1024;
239
240pub fn lan_router(endpoint: Endpoint, subnets: LocalSubnets) -> axum::Router {
260 let lan_only = axum::Router::new()
261 .route("/endpoint", get(get_endpoint))
262 .route("/nodes", get(get_nodes))
263 .route("/preparePairing", post(prepare_pairing))
264 .route("/cancelPreparePairing", post(cancel_prepare_pairing))
265 .route("/waitForPairing", post(wait_for_pairing))
266 .with_state(endpoint.clone())
267 .layer(axum::middleware::from_fn_with_state(
268 subnets,
269 super::subnet::same_subnet,
270 ));
271
272 axum::Router::new()
273 .nest("/v1", authenticated_routes(endpoint).merge(lan_only))
274 .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
275}
276
277fn authenticated_routes(endpoint: Endpoint) -> axum::Router {
282 axum::Router::new()
283 .route("/requestPairing", post(request_pairing))
284 .route(
285 "/requestConnectionDetails",
286 post(request_connection_details),
287 )
288 .route("/postConnectionDetails", post(post_connection_details))
289 .route("/finalizePairing", post(finalize_pairing))
290 .route("/initiateSession", post(initiate_session))
291 .route("/confirmAccessToken", post(confirm_access_token))
292 .route("/unpair", post(unpair))
293 .with_state(endpoint)
294}
295
296async fn request_pairing(
301 State(endpoint): State<Endpoint>,
302 Json(request): Json<PairingRequest>,
303) -> Response {
304 let mut nonce = [0u8; 32];
305 let mut attempt = [0u8; 24];
306 if fill_random(&mut nonce).is_err() || fill_random(&mut attempt).is_err() {
307 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
308 }
309 let Ok(attempt_id) = PairingAttemptId::from_entropy(&attempt) else {
310 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
311 };
312 let bearer = attempt_id.clone();
313 let now = (endpoint.clock)();
314
315 match endpoint
316 .pairing
317 .request_pairing(&request, &nonce, attempt_id, now)
318 {
319 Ok((node, send_after, accepted)) => {
320 let wait = send_after.saturating_duration_since((endpoint.clock)());
323 if !wait.is_zero() {
324 tokio::time::sleep(core::time::Duration::from(wait)).await;
325 }
326 endpoint.remember(bearer, node, now);
327 crate::trace::event!(info, node = %node, "answered a pairing request");
328 (StatusCode::OK, Json(accepted)).into_response()
329 }
330 Err(e) => {
331 crate::trace::event!(warn, error = %e, "refused a pairing request");
332 pairing_error(e)
333 }
334 }
335}
336
337async fn request_connection_details(
338 State(endpoint): State<Endpoint>,
339 bearer: Bearer,
340 Json(request): Json<ConnectionDetailsRequest>,
341) -> Response {
342 let now = (endpoint.clock)();
343 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
344 return StatusCode::UNAUTHORIZED.into_response();
345 };
346 match endpoint
347 .pairing
348 .request_connection_details(
349 node,
350 &bearer.0,
351 &request.server_hmac_challenge_response,
352 now,
353 )
354 .await
355 {
356 Ok(details) => (StatusCode::OK, Json(details)).into_response(),
357 Err(e) => {
358 if matches!(e, ConnectError::ChallengeFailed) {
359 endpoint.forget(&bearer.0);
360 }
361 pairing_error(e)
362 }
363 }
364}
365
366async fn post_connection_details(
367 State(endpoint): State<Endpoint>,
368 bearer: Bearer,
369 Json(request): Json<ConnectionDetailsPost>,
370) -> Response {
371 let now = (endpoint.clock)();
372 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
373 return StatusCode::UNAUTHORIZED.into_response();
374 };
375 match endpoint
376 .pairing
377 .post_connection_details(
378 node,
379 &bearer.0,
380 &request.server_hmac_challenge_response,
381 request.connection_details,
382 now,
383 )
384 .await
385 {
386 Ok(()) => StatusCode::NO_CONTENT.into_response(),
387 Err(e) => {
388 if matches!(e, ConnectError::ChallengeFailed) {
389 endpoint.forget(&bearer.0);
390 }
391 pairing_error(e)
392 }
393 }
394}
395
396async fn finalize_pairing(
397 State(endpoint): State<Endpoint>,
398 bearer: Bearer,
399 Json(body): Json<FinalizePairing>,
400) -> Response {
401 let now = (endpoint.clock)();
402 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
403 return StatusCode::UNAUTHORIZED.into_response();
404 };
405 let result = endpoint
406 .pairing
407 .finalize(node, &bearer.0, body.success, now)
408 .await;
409 endpoint.forget(&bearer.0);
412 match result {
413 Ok(()) => {
414 crate::trace::event!(
415 info,
416 node = %node,
417 success = body.success,
418 "pairing finalized"
419 );
420 StatusCode::NO_CONTENT.into_response()
421 }
422 Err(e) => {
423 crate::trace::event!(warn, error = %e, "finalization refused");
424 pairing_error(e)
425 }
426 }
427}
428
429async fn get_endpoint(State(endpoint): State<Endpoint>) -> Response {
434 (StatusCode::OK, Json(endpoint.pairing.endpoint().clone())).into_response()
436}
437
438async fn get_nodes(State(endpoint): State<Endpoint>) -> Response {
439 let nodes: Vec<crate::connect::proto::NodeDescription> = endpoint
442 .pairing
443 .store()
444 .nodes()
445 .into_iter()
446 .map(|(node, _alias)| node)
447 .collect();
448 (StatusCode::OK, Json(nodes)).into_response()
449}
450
451async fn prepare_pairing(
452 State(endpoint): State<Endpoint>,
453 Json(body): Json<crate::connect::proto::PreparePairing>,
454) -> Response {
455 if let Some(handler) = &endpoint.on_prepare {
459 handler(PrepareSignal::Prepare(body));
460 }
461 StatusCode::NO_CONTENT.into_response()
462}
463
464async fn cancel_prepare_pairing(
465 State(endpoint): State<Endpoint>,
466 Json(body): Json<crate::connect::proto::CancelPreparePairing>,
467) -> Response {
468 if let Some(handler) = &endpoint.on_prepare {
469 handler(PrepareSignal::Cancel(body));
470 }
471 StatusCode::NO_CONTENT.into_response()
472}
473
474async fn wait_for_pairing(
480 State(endpoint): State<Endpoint>,
481 Json(nodes): Json<Vec<crate::connect::proto::WaitForPairing>>,
482) -> Response {
483 let instructions = endpoint.long_poll.poll(&nodes).await;
484 (StatusCode::OK, Json(instructions)).into_response()
485}
486
487async fn initiate_session(
492 State(endpoint): State<Endpoint>,
493 bearer: Bearer,
494 Json(request): Json<crate::connect::proto::SessionRequest>,
495) -> Response {
496 let mut entropy = [0u8; 32];
497 if fill_random(&mut entropy).is_err() {
498 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
499 }
500 let token = AccessToken::new(bearer.0);
501 let now = (endpoint.clock)();
502 match endpoint
503 .session
504 .initiate_session(&token, &request, &entropy, now)
505 {
506 Ok(grant) => (StatusCode::OK, Json(grant)).into_response(),
507 Err(e) => session_error(e),
508 }
509}
510
511async fn confirm_access_token(State(endpoint): State<Endpoint>, bearer: Bearer) -> Response {
512 let mut entropy = [0u8; 32];
513 if fill_random(&mut entropy).is_err() {
514 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
515 }
516 let token = AccessToken::new(bearer.0);
517 let now = (endpoint.clock)();
518 match endpoint.session.confirm_access_token(&token, &entropy, now) {
519 Ok((remote, details)) => {
520 crate::trace::event!(info, node = %remote, "issued a communication token");
521 (StatusCode::OK, Json(details)).into_response()
522 }
523 Err(_) => StatusCode::UNAUTHORIZED.into_response(),
527 }
528}
529
530async fn unpair(
531 State(endpoint): State<Endpoint>,
532 bearer: Bearer,
533 Json(request): Json<crate::connect::proto::UnpairRequest>,
534) -> Response {
535 let token = AccessToken::new(bearer.0);
536 match endpoint.session.unpair(&token, &request) {
537 Ok(()) => StatusCode::NO_CONTENT.into_response(),
538 Err(_) => StatusCode::UNAUTHORIZED.into_response(),
539 }
540}
541
542pub(super) struct Bearer(String);
548
549impl Bearer {
550 pub(super) fn as_str(&self) -> &str {
552 &self.0
553 }
554}
555
556impl<S: Send + Sync> axum::extract::FromRequestParts<S> for Bearer {
557 type Rejection = StatusCode;
558
559 #[allow(clippy::unused_async_trait_impl)]
561 async fn from_request_parts(
562 parts: &mut axum::http::request::Parts,
563 _state: &S,
564 ) -> Result<Self, Self::Rejection> {
565 parts
566 .headers
567 .get(axum::http::header::AUTHORIZATION)
568 .and_then(|value| value.to_str().ok())
569 .and_then(|value| {
572 let (scheme, token) = value.split_once(' ')?;
573 scheme.eq_ignore_ascii_case("Bearer").then_some(token)
574 })
575 .map(|token| Self(token.trim().to_string()))
576 .filter(|bearer| !bearer.0.is_empty())
577 .ok_or(StatusCode::UNAUTHORIZED)
578 }
579}
580
581fn pairing_error(error: ConnectError) -> Response {
583 match error {
584 ConnectError::RateLimited => StatusCode::SERVICE_UNAVAILABLE.into_response(),
587 ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
590 ConnectError::ChallengeFailed => StatusCode::FORBIDDEN.into_response(),
593 ConnectError::Refused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
594 ConnectError::Expired { .. } | ConnectError::OutOfOrder { .. } => {
595 StatusCode::BAD_REQUEST.into_response()
596 }
597 _ => StatusCode::BAD_REQUEST.into_response(),
598 }
599}
600
601fn session_error(error: ConnectError) -> Response {
602 match error {
603 ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
605 ConnectError::SessionRefused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
606 _ => StatusCode::BAD_REQUEST.into_response(),
607 }
608}
609
610fn fill_random(buffer: &mut [u8]) -> Result<(), rand::rngs::SysError> {
611 use rand::TryRng as _;
612 rand::rngs::SysRng.try_fill_bytes(buffer)
613}
614
615#[cfg(test)]
616mod tests {
617 use super::*;
618
619 fn at(secs: i64) -> Timestamp {
620 Timestamp::from_unix(1_700_000_000 + secs, 0)
621 }
622
623 fn endpoint() -> Endpoint {
624 let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
625 Endpoint::new(
626 Arc::new(PairingService::wan(
627 store.clone(),
628 crate::connect::proto::EndpointDescription::default(),
629 "pairing.example.com",
630 )),
631 Arc::new(SessionService::new(store, "wss://example.com/s2")),
632 )
633 }
634
635 #[test]
636 fn an_attempt_stops_authenticating_when_its_budget_runs_out() {
637 let endpoint = endpoint();
638 let node = NodeId::parse("cem-1").expect("a legal id");
639 endpoint.remember(PairingAttemptId::new("bearer-one"), node, at(0));
640
641 assert_eq!(endpoint.attempt_node("bearer-one", at(0)), Some(node));
642 assert_eq!(endpoint.attempt_node("bearer-one", at(14)), Some(node));
643 assert_eq!(endpoint.attempt_node("bearer-one", at(15)), None);
646 assert_eq!(endpoint.attempt_node("bearer-one", at(16)), None);
647 assert_eq!(endpoint.attempt_node("not-a-bearer", at(0)), None);
649 }
650
651 #[test]
652 fn abandoned_attempts_are_swept_rather_than_accumulated() {
653 let endpoint = endpoint();
658 let node = NodeId::parse("cem-1").expect("a legal id");
659
660 for i in 0..100 {
661 endpoint.remember(
662 PairingAttemptId::new(alloc::format!("abandoned-{i}")),
663 node,
664 at(i),
665 );
666 }
667 assert!(
669 endpoint.live_attempts() <= 16,
670 "expected at most one budget's worth, got {}",
671 endpoint.live_attempts()
672 );
673
674 endpoint.remember(PairingAttemptId::new("fresh"), node, at(1_000));
676 assert_eq!(endpoint.live_attempts(), 1);
677 assert_eq!(
678 endpoint.attempt_node("fresh", at(1_000)),
679 Some(node),
680 "and the new one is the survivor"
681 );
682 }
683
684 #[test]
685 fn finalizing_forgets_the_attempt_immediately() {
686 let endpoint = endpoint();
689 let node = NodeId::parse("cem-1").expect("a legal id");
690 endpoint.remember(PairingAttemptId::new("bearer"), node, at(0));
691 assert_eq!(endpoint.live_attempts(), 1);
692 endpoint.forget("bearer");
693 assert_eq!(endpoint.live_attempts(), 0);
694 assert_eq!(endpoint.attempt_node("bearer", at(0)), None);
695 }
696
697 #[test]
698 fn the_status_codes_are_the_ones_the_specification_distinguishes() {
699 let code = |e: ConnectError| pairing_error(e).status();
702 assert_eq!(
703 code(ConnectError::RateLimited),
704 StatusCode::SERVICE_UNAVAILABLE
705 );
706 assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
707 assert_eq!(code(ConnectError::ChallengeFailed), StatusCode::FORBIDDEN);
708 assert_eq!(
709 code(ConnectError::Refused(
710 crate::connect::proto::PairingRefused {
711 error_message: crate::connect::proto::PairingErrorMessage::NodeNotFound,
712 additional_info: None,
713 }
714 )),
715 StatusCode::BAD_REQUEST
716 );
717
718 let code = |e: ConnectError| session_error(e).status();
720 assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
721 assert_eq!(
722 code(ConnectError::SessionRefused(
723 crate::connect::proto::SessionRefused {
724 error_message: crate::connect::proto::SessionErrorMessage::NoLongerPaired,
725 additional_info: None,
726 }
727 )),
728 StatusCode::BAD_REQUEST
729 );
730 }
731}
732
733#[cfg(test)]
734mod subnet_wiring {
735 use super::*;
736 use tower::ServiceExt as _;
737
738 fn endpoint() -> Endpoint {
739 let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
740 Endpoint::new(
741 Arc::new(PairingService::lan(
742 store.clone(),
743 crate::connect::proto::EndpointDescription::default(),
744 crate::connect::tls::Fingerprint::parse(&"AA".repeat(32)).expect("a fingerprint"),
745 )),
746 Arc::new(SessionService::new(store, "wss://example.com/s2")),
747 )
748 }
749
750 async fn get(app: axum::Router, peer: Option<std::net::SocketAddr>) -> StatusCode {
751 let mut request = axum::http::Request::builder()
752 .uri("/v1/endpoint")
753 .body(axum::body::Body::empty())
754 .expect("a request");
755 if let Some(peer) = peer {
756 request
757 .extensions_mut()
758 .insert(axum::extract::ConnectInfo(peer));
759 }
760 app.oneshot(request)
761 .await
762 .expect("the router answers")
763 .status()
764 }
765
766 #[tokio::test]
767 async fn the_lan_routes_admit_a_local_peer_and_refuse_a_remote_one() {
768 let subnets =
769 LocalSubnets::from_prefixes([("192.168.1.10".parse().expect("an address"), 24)]);
770 let app = lan_router(endpoint(), subnets);
771
772 let local: std::net::SocketAddr = "192.168.1.50:9000".parse().expect("an address");
773 assert_eq!(get(app.clone(), Some(local)).await, StatusCode::OK);
774
775 let remote: std::net::SocketAddr = "8.8.8.8:9000".parse().expect("an address");
776 assert_eq!(
777 get(app.clone(), Some(remote)).await,
778 StatusCode::UNAUTHORIZED
779 );
780
781 assert_eq!(get(app, None).await, StatusCode::UNAUTHORIZED);
785 }
786
787 #[tokio::test]
788 async fn the_wan_router_has_no_lan_routes_to_admit_anyone_to() {
789 let app = router(endpoint());
790 let local: std::net::SocketAddr = "127.0.0.1:9000".parse().expect("an address");
791 assert_eq!(get(app, Some(local)).await, StatusCode::NOT_FOUND);
794 }
795}