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 max_message_bytes: usize,
56 on_prepare: Option<Arc<dyn Fn(PrepareSignal) + Send + Sync>>,
58}
59
60#[derive(Debug, Clone)]
71#[non_exhaustive]
72pub enum PrepareSignal {
73 Prepare(crate::connect::proto::PreparePairing),
75 Cancel(crate::connect::proto::CancelPreparePairing),
77}
78
79#[derive(Debug, Clone, Copy)]
81struct Attempt {
82 node: NodeId,
83 expires: Timestamp,
85}
86
87impl core::fmt::Debug for Endpoint {
88 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
89 f.debug_struct("Endpoint")
90 .field("pairing", &self.pairing)
91 .field("session", &self.session)
92 .finish_non_exhaustive()
93 }
94}
95
96impl Endpoint {
97 #[must_use]
99 pub fn new(pairing: Arc<PairingService>, session: Arc<SessionService>) -> Self {
100 Self {
101 pairing,
102 session,
103 attempts: Arc::new(std::sync::Mutex::new(Vec::new())),
104 long_poll: Arc::new(LongPoll::default()),
105 clock: Timestamp::now,
106 max_message_bytes: crate::codec::DecodeOptions::DEFAULT_MAX_BYTES,
107 on_prepare: None,
108 }
109 }
110
111 #[must_use]
119 pub const fn with_max_message_bytes(mut self, bytes: usize) -> Self {
120 self.max_message_bytes = bytes;
121 self
122 }
123
124 #[must_use]
126 pub const fn max_message_bytes(&self) -> usize {
127 self.max_message_bytes
128 }
129
130 #[must_use]
137 pub fn on_prepare_pairing(
138 mut self,
139 handler: impl Fn(PrepareSignal) + Send + Sync + 'static,
140 ) -> Self {
141 self.on_prepare = Some(Arc::new(handler));
142 self
143 }
144
145 #[must_use]
147 pub fn with_clock(mut self, clock: fn() -> Timestamp) -> Self {
148 self.clock = clock;
149 self
150 }
151
152 #[must_use]
154 pub fn session(&self) -> &Arc<SessionService> {
155 &self.session
156 }
157
158 fn remember(&self, id: PairingAttemptId, node: NodeId, now: Timestamp) {
159 let Ok(mut attempts) = self.attempts.lock() else {
160 return;
161 };
162 attempts.retain(|(_, attempt)| attempt.expires > now);
165 attempts.push((
166 id,
167 Attempt {
168 node,
169 expires: now
170 .checked_add(crate::connect::proto::PAIRING_BUDGET)
171 .unwrap_or(now),
172 },
173 ));
174 }
175
176 fn attempt_node(&self, bearer: &str, now: Timestamp) -> Option<NodeId> {
188 let attempts = self.attempts.lock().ok()?;
189 let mut found = None;
191 for (id, attempt) in attempts.iter() {
192 if id.verify(bearer) && attempt.expires > now {
193 found = Some(attempt.node);
194 }
195 }
196 found
197 }
198
199 fn forget(&self, bearer: &str) {
200 if let Ok(mut attempts) = self.attempts.lock() {
201 attempts.retain(|(id, _)| !id.verify(bearer));
202 }
203 }
204
205 pub const MAX_WAITING_NODES: usize = LongPoll::MAX_WAITING;
210
211 pub const MAX_NODES_PER_POLL: usize = LongPoll::MAX_PER_POLL;
213
214 pub fn instruct_waiting_node(&self, client: NodeId, action: crate::connect::proto::WaitAction) {
221 self.long_poll.instruct(client, action);
222 }
223
224 #[must_use]
229 pub fn waiting_nodes(&self) -> Vec<(NodeId, WaitingNode)> {
230 self.long_poll.waiting()
231 }
232
233 pub(super) fn now(&self) -> Timestamp {
235 (self.clock)()
236 }
237
238 #[must_use]
240 pub fn live_attempts(&self) -> usize {
241 self.attempts.lock().map_or(0, |attempts| attempts.len())
242 }
243}
244
245pub fn router(endpoint: Endpoint) -> axum::Router {
251 axum::Router::new()
252 .nest("/v1", authenticated_routes(endpoint))
253 .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
254}
255
256pub const MAX_BODY_BYTES: usize = 64 * 1024;
265
266pub fn lan_router(endpoint: Endpoint, subnets: LocalSubnets) -> axum::Router {
286 let lan_only = axum::Router::new()
287 .route("/endpoint", get(get_endpoint))
288 .route("/nodes", get(get_nodes))
289 .route("/preparePairing", post(prepare_pairing))
290 .route("/cancelPreparePairing", post(cancel_prepare_pairing))
291 .route("/waitForPairing", post(wait_for_pairing))
292 .with_state(endpoint.clone())
293 .layer(axum::middleware::from_fn_with_state(
294 subnets,
295 super::subnet::same_subnet,
296 ));
297
298 axum::Router::new()
299 .nest("/v1", authenticated_routes(endpoint).merge(lan_only))
300 .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
301}
302
303fn authenticated_routes(endpoint: Endpoint) -> axum::Router {
308 axum::Router::new()
309 .route("/requestPairing", post(request_pairing))
310 .route(
311 "/requestConnectionDetails",
312 post(request_connection_details),
313 )
314 .route("/postConnectionDetails", post(post_connection_details))
315 .route("/finalizePairing", post(finalize_pairing))
316 .route("/initiateSession", post(initiate_session))
317 .route("/confirmAccessToken", post(confirm_access_token))
318 .route("/unpair", post(unpair))
319 .with_state(endpoint)
320}
321
322async fn request_pairing(
327 State(endpoint): State<Endpoint>,
328 Json(request): Json<PairingRequest>,
329) -> Response {
330 let mut nonce = [0u8; 32];
331 let mut attempt = [0u8; 24];
332 if fill_random(&mut nonce).is_err() || fill_random(&mut attempt).is_err() {
333 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
334 }
335 let Ok(attempt_id) = PairingAttemptId::from_entropy(&attempt) else {
336 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
337 };
338 let bearer = attempt_id.clone();
339 let now = (endpoint.clock)();
340
341 match endpoint
342 .pairing
343 .request_pairing(&request, &nonce, attempt_id, now)
344 {
345 Ok((node, send_after, accepted)) => {
346 let wait = send_after.saturating_duration_since((endpoint.clock)());
349 if !wait.is_zero() {
350 tokio::time::sleep(core::time::Duration::from(wait)).await;
351 }
352 endpoint.remember(bearer, node, now);
353 crate::trace::event!(info, node = %node, "answered a pairing request");
354 (StatusCode::OK, Json(accepted)).into_response()
355 }
356 Err(e) => {
357 crate::trace::event!(warn, error = %e, "refused a pairing request");
358 pairing_error(e)
359 }
360 }
361}
362
363async fn request_connection_details(
364 State(endpoint): State<Endpoint>,
365 bearer: Bearer,
366 Json(request): Json<ConnectionDetailsRequest>,
367) -> Response {
368 let now = (endpoint.clock)();
369 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
370 return StatusCode::UNAUTHORIZED.into_response();
371 };
372 match endpoint
373 .pairing
374 .request_connection_details(
375 node,
376 &bearer.0,
377 &request.server_hmac_challenge_response,
378 now,
379 )
380 .await
381 {
382 Ok(details) => (StatusCode::OK, Json(details)).into_response(),
383 Err(e) => {
384 if matches!(e, ConnectError::ChallengeFailed) {
385 endpoint.forget(&bearer.0);
386 }
387 pairing_error(e)
388 }
389 }
390}
391
392async fn post_connection_details(
393 State(endpoint): State<Endpoint>,
394 bearer: Bearer,
395 Json(request): Json<ConnectionDetailsPost>,
396) -> Response {
397 let now = (endpoint.clock)();
398 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
399 return StatusCode::UNAUTHORIZED.into_response();
400 };
401 match endpoint
402 .pairing
403 .post_connection_details(
404 node,
405 &bearer.0,
406 &request.server_hmac_challenge_response,
407 request.connection_details,
408 now,
409 )
410 .await
411 {
412 Ok(()) => StatusCode::NO_CONTENT.into_response(),
413 Err(e) => {
414 if matches!(e, ConnectError::ChallengeFailed) {
415 endpoint.forget(&bearer.0);
416 }
417 pairing_error(e)
418 }
419 }
420}
421
422async fn finalize_pairing(
423 State(endpoint): State<Endpoint>,
424 bearer: Bearer,
425 Json(body): Json<FinalizePairing>,
426) -> Response {
427 let now = (endpoint.clock)();
428 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
429 return StatusCode::UNAUTHORIZED.into_response();
430 };
431 let result = endpoint
432 .pairing
433 .finalize(node, &bearer.0, body.success, now)
434 .await;
435 endpoint.forget(&bearer.0);
438 match result {
439 Ok(()) => {
440 crate::trace::event!(
441 info,
442 node = %node,
443 success = body.success,
444 "pairing finalized"
445 );
446 StatusCode::NO_CONTENT.into_response()
447 }
448 Err(e) => {
449 crate::trace::event!(warn, error = %e, "finalization refused");
450 pairing_error(e)
451 }
452 }
453}
454
455async fn get_endpoint(State(endpoint): State<Endpoint>) -> Response {
460 (StatusCode::OK, Json(endpoint.pairing.endpoint().clone())).into_response()
462}
463
464async fn get_nodes(State(endpoint): State<Endpoint>) -> Response {
465 let nodes: Vec<crate::connect::proto::NodeDescription> = endpoint
468 .pairing
469 .store()
470 .nodes()
471 .into_iter()
472 .map(|(node, _alias)| node)
473 .collect();
474 (StatusCode::OK, Json(nodes)).into_response()
475}
476
477async fn prepare_pairing(
478 State(endpoint): State<Endpoint>,
479 Json(body): Json<crate::connect::proto::PreparePairing>,
480) -> Response {
481 if let Some(handler) = &endpoint.on_prepare {
485 handler(PrepareSignal::Prepare(body));
486 }
487 StatusCode::NO_CONTENT.into_response()
488}
489
490async fn cancel_prepare_pairing(
491 State(endpoint): State<Endpoint>,
492 Json(body): Json<crate::connect::proto::CancelPreparePairing>,
493) -> Response {
494 if let Some(handler) = &endpoint.on_prepare {
495 handler(PrepareSignal::Cancel(body));
496 }
497 StatusCode::NO_CONTENT.into_response()
498}
499
500async fn wait_for_pairing(
506 State(endpoint): State<Endpoint>,
507 Json(nodes): Json<Vec<crate::connect::proto::WaitForPairing>>,
508) -> Response {
509 let instructions = endpoint.long_poll.poll(&nodes).await;
510 (StatusCode::OK, Json(instructions)).into_response()
511}
512
513async fn initiate_session(
518 State(endpoint): State<Endpoint>,
519 bearer: Bearer,
520 Json(request): Json<crate::connect::proto::SessionRequest>,
521) -> Response {
522 let mut entropy = [0u8; 32];
523 if fill_random(&mut entropy).is_err() {
524 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
525 }
526 let token = AccessToken::new(bearer.0);
527 let now = (endpoint.clock)();
528 match endpoint
529 .session
530 .initiate_session(&token, &request, &entropy, now)
531 {
532 Ok(grant) => (StatusCode::OK, Json(grant)).into_response(),
533 Err(e) => session_error(e),
534 }
535}
536
537async fn confirm_access_token(State(endpoint): State<Endpoint>, bearer: Bearer) -> Response {
538 let mut entropy = [0u8; 32];
539 if fill_random(&mut entropy).is_err() {
540 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
541 }
542 let token = AccessToken::new(bearer.0);
543 let now = (endpoint.clock)();
544 match endpoint.session.confirm_access_token(&token, &entropy, now) {
545 Ok((remote, details)) => {
546 crate::trace::event!(info, node = %remote, "issued a communication token");
547 (StatusCode::OK, Json(details)).into_response()
548 }
549 Err(_) => StatusCode::UNAUTHORIZED.into_response(),
553 }
554}
555
556async fn unpair(
557 State(endpoint): State<Endpoint>,
558 bearer: Bearer,
559 Json(request): Json<crate::connect::proto::UnpairRequest>,
560) -> Response {
561 let token = AccessToken::new(bearer.0);
562 match endpoint.session.unpair(&token, &request) {
563 Ok(()) => StatusCode::NO_CONTENT.into_response(),
564 Err(_) => StatusCode::UNAUTHORIZED.into_response(),
565 }
566}
567
568pub(super) struct Bearer(String);
574
575impl Bearer {
576 pub(super) fn as_str(&self) -> &str {
578 &self.0
579 }
580}
581
582impl<S: Send + Sync> axum::extract::FromRequestParts<S> for Bearer {
583 type Rejection = StatusCode;
584
585 #[allow(clippy::unused_async_trait_impl)]
587 async fn from_request_parts(
588 parts: &mut axum::http::request::Parts,
589 _state: &S,
590 ) -> Result<Self, Self::Rejection> {
591 parts
592 .headers
593 .get(axum::http::header::AUTHORIZATION)
594 .and_then(|value| value.to_str().ok())
595 .and_then(|value| {
598 let (scheme, token) = value.split_once(' ')?;
599 scheme.eq_ignore_ascii_case("Bearer").then_some(token)
600 })
601 .map(|token| Self(token.trim().to_string()))
602 .filter(|bearer| !bearer.0.is_empty())
603 .ok_or(StatusCode::UNAUTHORIZED)
604 }
605}
606
607fn pairing_error(error: ConnectError) -> Response {
609 match error {
610 ConnectError::RateLimited => StatusCode::SERVICE_UNAVAILABLE.into_response(),
613 ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
616 ConnectError::ChallengeFailed => StatusCode::FORBIDDEN.into_response(),
619 ConnectError::Refused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
620 ConnectError::Expired { .. } | ConnectError::OutOfOrder { .. } => {
621 StatusCode::BAD_REQUEST.into_response()
622 }
623 _ => StatusCode::BAD_REQUEST.into_response(),
624 }
625}
626
627fn session_error(error: ConnectError) -> Response {
628 match error {
629 ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
631 ConnectError::SessionRefused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
632 _ => StatusCode::BAD_REQUEST.into_response(),
633 }
634}
635
636fn fill_random(buffer: &mut [u8]) -> Result<(), rand::rngs::SysError> {
637 use rand::TryRng as _;
638 rand::rngs::SysRng.try_fill_bytes(buffer)
639}
640
641#[cfg(test)]
642mod tests {
643 use super::*;
644
645 fn at(secs: i64) -> Timestamp {
646 Timestamp::from_unix(1_700_000_000 + secs, 0)
647 }
648
649 fn endpoint() -> Endpoint {
650 let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
651 Endpoint::new(
652 Arc::new(PairingService::wan(
653 store.clone(),
654 crate::connect::proto::EndpointDescription::default(),
655 "pairing.example.com",
656 )),
657 Arc::new(SessionService::new(store, "wss://example.com/s2")),
658 )
659 }
660
661 #[test]
662 fn an_attempt_stops_authenticating_when_its_budget_runs_out() {
663 let endpoint = endpoint();
664 let node = NodeId::parse("cem-1").expect("a legal id");
665 endpoint.remember(PairingAttemptId::new("bearer-one"), node, at(0));
666
667 assert_eq!(endpoint.attempt_node("bearer-one", at(0)), Some(node));
668 assert_eq!(endpoint.attempt_node("bearer-one", at(14)), Some(node));
669 assert_eq!(endpoint.attempt_node("bearer-one", at(15)), None);
672 assert_eq!(endpoint.attempt_node("bearer-one", at(16)), None);
673 assert_eq!(endpoint.attempt_node("not-a-bearer", at(0)), None);
675 }
676
677 #[test]
678 fn abandoned_attempts_are_swept_rather_than_accumulated() {
679 let endpoint = endpoint();
684 let node = NodeId::parse("cem-1").expect("a legal id");
685
686 for i in 0..100 {
687 endpoint.remember(
688 PairingAttemptId::new(alloc::format!("abandoned-{i}")),
689 node,
690 at(i),
691 );
692 }
693 assert!(
695 endpoint.live_attempts() <= 16,
696 "expected at most one budget's worth, got {}",
697 endpoint.live_attempts()
698 );
699
700 endpoint.remember(PairingAttemptId::new("fresh"), node, at(1_000));
702 assert_eq!(endpoint.live_attempts(), 1);
703 assert_eq!(
704 endpoint.attempt_node("fresh", at(1_000)),
705 Some(node),
706 "and the new one is the survivor"
707 );
708 }
709
710 #[test]
711 fn finalizing_forgets_the_attempt_immediately() {
712 let endpoint = endpoint();
715 let node = NodeId::parse("cem-1").expect("a legal id");
716 endpoint.remember(PairingAttemptId::new("bearer"), node, at(0));
717 assert_eq!(endpoint.live_attempts(), 1);
718 endpoint.forget("bearer");
719 assert_eq!(endpoint.live_attempts(), 0);
720 assert_eq!(endpoint.attempt_node("bearer", at(0)), None);
721 }
722
723 #[test]
724 fn the_status_codes_are_the_ones_the_specification_distinguishes() {
725 let code = |e: ConnectError| pairing_error(e).status();
728 assert_eq!(
729 code(ConnectError::RateLimited),
730 StatusCode::SERVICE_UNAVAILABLE
731 );
732 assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
733 assert_eq!(code(ConnectError::ChallengeFailed), StatusCode::FORBIDDEN);
734 assert_eq!(
735 code(ConnectError::Refused(
736 crate::connect::proto::PairingRefused {
737 error_message: crate::connect::proto::PairingErrorMessage::NodeNotFound,
738 additional_info: None,
739 }
740 )),
741 StatusCode::BAD_REQUEST
742 );
743
744 let code = |e: ConnectError| session_error(e).status();
746 assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
747 assert_eq!(
748 code(ConnectError::SessionRefused(
749 crate::connect::proto::SessionRefused {
750 error_message: crate::connect::proto::SessionErrorMessage::NoLongerPaired,
751 additional_info: None,
752 }
753 )),
754 StatusCode::BAD_REQUEST
755 );
756 }
757}
758
759#[cfg(test)]
760mod subnet_wiring {
761 use super::*;
762 use tower::ServiceExt as _;
763
764 fn endpoint() -> Endpoint {
765 let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
766 Endpoint::new(
767 Arc::new(PairingService::lan(
768 store.clone(),
769 crate::connect::proto::EndpointDescription::default(),
770 crate::connect::tls::Fingerprint::parse(&"AA".repeat(32)).expect("a fingerprint"),
771 )),
772 Arc::new(SessionService::new(store, "wss://example.com/s2")),
773 )
774 }
775
776 async fn get(app: axum::Router, peer: Option<std::net::SocketAddr>) -> StatusCode {
777 let mut request = axum::http::Request::builder()
778 .uri("/v1/endpoint")
779 .body(axum::body::Body::empty())
780 .expect("a request");
781 if let Some(peer) = peer {
782 request
783 .extensions_mut()
784 .insert(axum::extract::ConnectInfo(peer));
785 }
786 app.oneshot(request)
787 .await
788 .expect("the router answers")
789 .status()
790 }
791
792 #[tokio::test]
793 async fn the_lan_routes_admit_a_local_peer_and_refuse_a_remote_one() {
794 let subnets =
795 LocalSubnets::from_prefixes([("192.168.1.10".parse().expect("an address"), 24)]);
796 let app = lan_router(endpoint(), subnets);
797
798 let local: std::net::SocketAddr = "192.168.1.50:9000".parse().expect("an address");
799 assert_eq!(get(app.clone(), Some(local)).await, StatusCode::OK);
800
801 let remote: std::net::SocketAddr = "8.8.8.8:9000".parse().expect("an address");
802 assert_eq!(
803 get(app.clone(), Some(remote)).await,
804 StatusCode::UNAUTHORIZED
805 );
806
807 assert_eq!(get(app, None).await, StatusCode::UNAUTHORIZED);
811 }
812
813 #[tokio::test]
814 async fn the_wan_router_has_no_lan_routes_to_admit_anyone_to() {
815 let app = router(endpoint());
816 let local: std::net::SocketAddr = "127.0.0.1:9000".parse().expect("an address");
817 assert_eq!(get(app, Some(local)).await, StatusCode::NOT_FOUND);
820 }
821}