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 const API_VERSIONS: &[&str] = &["v1"];
247
248pub fn router(endpoint: Endpoint) -> axum::Router {
258 axum::Router::new()
259 .route("/", get(versions))
260 .nest("/v1", authenticated_routes(endpoint))
261 .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
262}
263
264async fn versions() -> Response {
265 (StatusCode::OK, Json(API_VERSIONS)).into_response()
266}
267
268pub const MAX_BODY_BYTES: usize = 64 * 1024;
277
278pub fn lan_router(endpoint: Endpoint, subnets: LocalSubnets) -> axum::Router {
298 let lan_only = axum::Router::new()
299 .route("/endpoint", get(get_endpoint))
300 .route("/nodes", get(get_nodes))
301 .route("/preparePairing", post(prepare_pairing))
302 .route("/cancelPreparePairing", post(cancel_prepare_pairing))
303 .route("/waitForPairing", post(wait_for_pairing))
304 .with_state(endpoint.clone())
305 .layer(axum::middleware::from_fn_with_state(
306 subnets,
307 super::subnet::same_subnet,
308 ));
309
310 axum::Router::new()
311 .route("/", get(versions))
312 .nest("/v1", authenticated_routes(endpoint).merge(lan_only))
313 .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
314}
315
316fn authenticated_routes(endpoint: Endpoint) -> axum::Router {
321 axum::Router::new()
322 .route("/requestPairing", post(request_pairing))
323 .route(
324 "/requestConnectionDetails",
325 post(request_connection_details),
326 )
327 .route("/postConnectionDetails", post(post_connection_details))
328 .route("/finalizePairing", post(finalize_pairing))
329 .route("/initiateSession", post(initiate_session))
330 .route("/confirmAccessToken", post(confirm_access_token))
331 .route("/unpair", post(unpair))
332 .with_state(endpoint)
333}
334
335async fn request_pairing(
340 State(endpoint): State<Endpoint>,
341 PairingBody(request): PairingBody<PairingRequest>,
342) -> Response {
343 let mut nonce = [0u8; 32];
344 let mut attempt = [0u8; 24];
345 if fill_random(&mut nonce).is_err() || fill_random(&mut attempt).is_err() {
346 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
347 }
348 let Ok(attempt_id) = PairingAttemptId::from_entropy(&attempt) else {
349 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
350 };
351 let bearer = attempt_id.clone();
352 let now = (endpoint.clock)();
353
354 match endpoint
355 .pairing
356 .request_pairing(&request, &nonce, attempt_id, now)
357 {
358 Ok((node, send_after, accepted)) => {
359 let wait = send_after.saturating_duration_since((endpoint.clock)());
362 if !wait.is_zero() {
363 tokio::time::sleep(core::time::Duration::from(wait)).await;
364 }
365 endpoint.remember(bearer, node, now);
366 crate::trace::event!(info, node = %node, "answered a pairing request");
367 (StatusCode::OK, Json(accepted)).into_response()
368 }
369 Err(e) => {
370 crate::trace::event!(warn, error = %e, "refused a pairing request");
371 pairing_error(e)
372 }
373 }
374}
375
376async fn request_connection_details(
377 State(endpoint): State<Endpoint>,
378 bearer: Bearer,
379 PairingBody(request): PairingBody<ConnectionDetailsRequest>,
380) -> Response {
381 let now = (endpoint.clock)();
382 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
383 return StatusCode::UNAUTHORIZED.into_response();
384 };
385 match endpoint
386 .pairing
387 .request_connection_details(
388 node,
389 &bearer.0,
390 &request.server_hmac_challenge_response,
391 now,
392 )
393 .await
394 {
395 Ok(details) => (StatusCode::OK, Json(details)).into_response(),
396 Err(e) => {
397 if matches!(e, ConnectError::ChallengeFailed) {
398 endpoint.forget(&bearer.0);
399 }
400 pairing_error(e)
401 }
402 }
403}
404
405async fn post_connection_details(
406 State(endpoint): State<Endpoint>,
407 bearer: Bearer,
408 PairingBody(request): PairingBody<ConnectionDetailsPost>,
409) -> Response {
410 let now = (endpoint.clock)();
411 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
412 return StatusCode::UNAUTHORIZED.into_response();
413 };
414 match endpoint
415 .pairing
416 .post_connection_details(
417 node,
418 &bearer.0,
419 &request.server_hmac_challenge_response,
420 request.connection_details,
421 now,
422 )
423 .await
424 {
425 Ok(()) => StatusCode::NO_CONTENT.into_response(),
426 Err(e) => {
427 if matches!(e, ConnectError::ChallengeFailed) {
428 endpoint.forget(&bearer.0);
429 }
430 pairing_error(e)
431 }
432 }
433}
434
435async fn finalize_pairing(
436 State(endpoint): State<Endpoint>,
437 bearer: Bearer,
438 PairingBody(body): PairingBody<FinalizePairing>,
439) -> Response {
440 let now = (endpoint.clock)();
441 let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
442 return StatusCode::UNAUTHORIZED.into_response();
443 };
444 let result = endpoint
445 .pairing
446 .finalize(node, &bearer.0, body.success, now)
447 .await;
448 endpoint.forget(&bearer.0);
451 match result {
452 Ok(finalized) => {
453 for key in &finalized.displaced {
454 endpoint.session.end_sessions(*key);
455 }
456 crate::trace::event!(
457 info,
458 node = %node,
459 success = body.success,
460 "pairing finalized"
461 );
462 StatusCode::NO_CONTENT.into_response()
463 }
464 Err(e) => {
465 crate::trace::event!(warn, error = %e, "finalization refused");
466 pairing_error(e)
467 }
468 }
469}
470
471async fn get_endpoint(State(endpoint): State<Endpoint>) -> Response {
476 (StatusCode::OK, Json(endpoint.pairing.endpoint().clone())).into_response()
478}
479
480async fn get_nodes(State(endpoint): State<Endpoint>) -> Response {
481 let nodes: Vec<crate::connect::proto::NodeDescription> = endpoint
484 .pairing
485 .store()
486 .nodes()
487 .into_iter()
488 .map(|(node, _alias)| node)
489 .collect();
490 (StatusCode::OK, Json(nodes)).into_response()
491}
492
493async fn prepare_pairing(
494 State(endpoint): State<Endpoint>,
495 PairingBody(body): PairingBody<crate::connect::proto::PreparePairing>,
496) -> Response {
497 if let Some(handler) = &endpoint.on_prepare {
501 handler(PrepareSignal::Prepare(body));
502 }
503 StatusCode::NO_CONTENT.into_response()
504}
505
506async fn cancel_prepare_pairing(
507 State(endpoint): State<Endpoint>,
508 PairingBody(body): PairingBody<crate::connect::proto::CancelPreparePairing>,
509) -> Response {
510 if let Some(handler) = &endpoint.on_prepare {
511 handler(PrepareSignal::Cancel(body));
512 }
513 StatusCode::NO_CONTENT.into_response()
514}
515
516async fn wait_for_pairing(
523 State(endpoint): State<Endpoint>,
524 PairingBody(nodes): PairingBody<Vec<crate::connect::proto::WaitForPairing>>,
525) -> Response {
526 let instructions = endpoint.long_poll.poll(&nodes).await;
527 if instructions.is_empty() {
528 return StatusCode::NO_CONTENT.into_response();
529 }
530 (StatusCode::OK, Json(instructions)).into_response()
531}
532
533async fn initiate_session(
538 State(endpoint): State<Endpoint>,
539 bearer: Bearer,
540 SessionBody(request): SessionBody<crate::connect::proto::SessionRequest>,
541) -> Response {
542 let mut entropy = [0u8; 32];
543 if fill_random(&mut entropy).is_err() {
544 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
545 }
546 let token = AccessToken::new(bearer.0);
547 let now = (endpoint.clock)();
548 match endpoint
549 .session
550 .initiate_session(&token, &request, &entropy, now)
551 {
552 Ok(grant) => (StatusCode::OK, Json(grant)).into_response(),
553 Err(e) => session_error(e),
554 }
555}
556
557async fn confirm_access_token(State(endpoint): State<Endpoint>, bearer: Bearer) -> Response {
558 let mut entropy = [0u8; 32];
559 if fill_random(&mut entropy).is_err() {
560 return StatusCode::INTERNAL_SERVER_ERROR.into_response();
561 }
562 let token = AccessToken::new(bearer.0);
563 let now = (endpoint.clock)();
564 match endpoint.session.confirm_access_token(&token, &entropy, now) {
565 Ok((key, details)) => {
566 crate::trace::event!(info, node = %key.remote, "issued a communication token");
567 (StatusCode::OK, Json(details)).into_response()
568 }
569 Err(_) => StatusCode::UNAUTHORIZED.into_response(),
573 }
574}
575
576async fn unpair(
577 State(endpoint): State<Endpoint>,
578 bearer: Bearer,
579 SessionBody(request): SessionBody<crate::connect::proto::UnpairRequest>,
580) -> Response {
581 let token = AccessToken::new(bearer.0);
582 match endpoint.session.unpair(&token, &request) {
583 Ok(()) => StatusCode::NO_CONTENT.into_response(),
584 Err(_) => StatusCode::UNAUTHORIZED.into_response(),
585 }
586}
587
588pub(super) struct Bearer(String);
594
595impl Bearer {
596 pub(super) fn as_str(&self) -> &str {
598 &self.0
599 }
600}
601
602impl<S: Send + Sync> axum::extract::FromRequestParts<S> for Bearer {
603 type Rejection = StatusCode;
604
605 #[allow(clippy::unused_async_trait_impl)]
607 async fn from_request_parts(
608 parts: &mut axum::http::request::Parts,
609 _state: &S,
610 ) -> Result<Self, Self::Rejection> {
611 parts
612 .headers
613 .get(axum::http::header::AUTHORIZATION)
614 .and_then(|value| value.to_str().ok())
615 .and_then(|value| {
618 let (scheme, token) = value.split_once(' ')?;
619 scheme.eq_ignore_ascii_case("Bearer").then_some(token)
620 })
621 .map(|token| Self(token.trim().to_string()))
622 .filter(|bearer| !bearer.0.is_empty())
623 .ok_or(StatusCode::UNAUTHORIZED)
624 }
625}
626
627pub(super) struct PairingBody<T>(pub T);
633
634pub(super) struct SessionBody<T>(pub T);
636
637fn parsing_error_pairing() -> Response {
638 (
639 StatusCode::BAD_REQUEST,
640 Json(crate::connect::proto::PairingRefused {
641 error_message: crate::connect::proto::PairingErrorMessage::ParsingError,
642 additional_info: None,
643 }),
644 )
645 .into_response()
646}
647
648fn parsing_error_session() -> Response {
649 (
650 StatusCode::BAD_REQUEST,
651 Json(crate::connect::proto::SessionRefused {
652 error_message: crate::connect::proto::SessionErrorMessage::ParsingError,
653 additional_info: None,
654 }),
655 )
656 .into_response()
657}
658
659impl<S, T> axum::extract::FromRequest<S> for PairingBody<T>
660where
661 S: Send + Sync,
662 T: serde::de::DeserializeOwned,
663{
664 type Rejection = Response;
665
666 async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
667 match Json::<T>::from_request(req, state).await {
668 Ok(Json(value)) => Ok(Self(value)),
669 Err(rejection) if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE => {
670 Err(rejection.into_response())
671 }
672 Err(_) => Err(parsing_error_pairing()),
673 }
674 }
675}
676
677impl<S, T> axum::extract::FromRequest<S> for SessionBody<T>
678where
679 S: Send + Sync,
680 T: serde::de::DeserializeOwned,
681{
682 type Rejection = Response;
683
684 async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
685 match Json::<T>::from_request(req, state).await {
686 Ok(Json(value)) => Ok(Self(value)),
687 Err(rejection) if rejection.status() == StatusCode::PAYLOAD_TOO_LARGE => {
688 Err(rejection.into_response())
689 }
690 Err(_) => Err(parsing_error_session()),
691 }
692 }
693}
694
695fn pairing_error(error: ConnectError) -> Response {
697 match error {
698 ConnectError::RateLimited => StatusCode::SERVICE_UNAVAILABLE.into_response(),
701 ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
704 ConnectError::ChallengeFailed => StatusCode::FORBIDDEN.into_response(),
707 ConnectError::Refused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
708 ConnectError::Expired { .. } | ConnectError::OutOfOrder { .. } => {
709 StatusCode::BAD_REQUEST.into_response()
710 }
711 _ => StatusCode::BAD_REQUEST.into_response(),
712 }
713}
714
715fn session_error(error: ConnectError) -> Response {
716 match error {
717 ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
719 ConnectError::SessionRefused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
720 _ => StatusCode::BAD_REQUEST.into_response(),
721 }
722}
723
724use super::fill_random;
725
726#[cfg(test)]
727mod tests {
728 use super::*;
729
730 fn at(secs: i64) -> Timestamp {
731 Timestamp::from_unix(1_700_000_000 + secs, 0)
732 }
733
734 fn endpoint() -> Endpoint {
735 let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
736 Endpoint::new(
737 Arc::new(PairingService::wan(
738 store.clone(),
739 crate::connect::proto::EndpointDescription::default(),
740 "pairing.example.com",
741 )),
742 Arc::new(SessionService::new(store, "wss://example.com/s2")),
743 )
744 }
745
746 #[test]
747 fn an_attempt_stops_authenticating_when_its_budget_runs_out() {
748 let endpoint = endpoint();
749 let node = NodeId::parse("cem-1").expect("a legal id");
750 endpoint.remember(PairingAttemptId::new("bearer-one"), node, at(0));
751
752 assert_eq!(endpoint.attempt_node("bearer-one", at(0)), Some(node));
753 assert_eq!(endpoint.attempt_node("bearer-one", at(14)), Some(node));
754 assert_eq!(endpoint.attempt_node("bearer-one", at(15)), None);
757 assert_eq!(endpoint.attempt_node("bearer-one", at(16)), None);
758 assert_eq!(endpoint.attempt_node("not-a-bearer", at(0)), None);
760 }
761
762 #[test]
763 fn abandoned_attempts_are_swept_rather_than_accumulated() {
764 let endpoint = endpoint();
769 let node = NodeId::parse("cem-1").expect("a legal id");
770
771 for i in 0..100 {
772 endpoint.remember(
773 PairingAttemptId::new(alloc::format!("abandoned-{i}")),
774 node,
775 at(i),
776 );
777 }
778 assert!(
780 endpoint.live_attempts() <= 16,
781 "expected at most one budget's worth, got {}",
782 endpoint.live_attempts()
783 );
784
785 endpoint.remember(PairingAttemptId::new("fresh"), node, at(1_000));
787 assert_eq!(endpoint.live_attempts(), 1);
788 assert_eq!(
789 endpoint.attempt_node("fresh", at(1_000)),
790 Some(node),
791 "and the new one is the survivor"
792 );
793 }
794
795 #[test]
796 fn finalizing_forgets_the_attempt_immediately() {
797 let endpoint = endpoint();
800 let node = NodeId::parse("cem-1").expect("a legal id");
801 endpoint.remember(PairingAttemptId::new("bearer"), node, at(0));
802 assert_eq!(endpoint.live_attempts(), 1);
803 endpoint.forget("bearer");
804 assert_eq!(endpoint.live_attempts(), 0);
805 assert_eq!(endpoint.attempt_node("bearer", at(0)), None);
806 }
807
808 #[test]
809 fn the_status_codes_are_the_ones_the_specification_distinguishes() {
810 let code = |e: ConnectError| pairing_error(e).status();
813 assert_eq!(
814 code(ConnectError::RateLimited),
815 StatusCode::SERVICE_UNAVAILABLE
816 );
817 assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
818 assert_eq!(code(ConnectError::ChallengeFailed), StatusCode::FORBIDDEN);
819 assert_eq!(
820 code(ConnectError::Refused(
821 crate::connect::proto::PairingRefused {
822 error_message: crate::connect::proto::PairingErrorMessage::NodeNotFound,
823 additional_info: None,
824 }
825 )),
826 StatusCode::BAD_REQUEST
827 );
828
829 let code = |e: ConnectError| session_error(e).status();
831 assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
832 assert_eq!(
833 code(ConnectError::SessionRefused(
834 crate::connect::proto::SessionRefused {
835 error_message: crate::connect::proto::SessionErrorMessage::NoLongerPaired,
836 additional_info: None,
837 }
838 )),
839 StatusCode::BAD_REQUEST
840 );
841 }
842}
843
844#[cfg(test)]
845mod subnet_wiring {
846 use super::*;
847 use tower::ServiceExt as _;
848
849 fn endpoint() -> Endpoint {
850 let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
851 Endpoint::new(
852 Arc::new(PairingService::lan(
853 store.clone(),
854 crate::connect::proto::EndpointDescription::default(),
855 crate::connect::tls::Fingerprint::parse(&"AA".repeat(32)).expect("a fingerprint"),
856 )),
857 Arc::new(SessionService::new(store, "wss://example.com/s2")),
858 )
859 }
860
861 async fn get(app: axum::Router, peer: Option<std::net::SocketAddr>) -> StatusCode {
862 let mut request = axum::http::Request::builder()
863 .uri("/v1/endpoint")
864 .body(axum::body::Body::empty())
865 .expect("a request");
866 if let Some(peer) = peer {
867 request
868 .extensions_mut()
869 .insert(axum::extract::ConnectInfo(peer));
870 }
871 app.oneshot(request)
872 .await
873 .expect("the router answers")
874 .status()
875 }
876
877 #[tokio::test]
878 async fn the_lan_routes_admit_a_local_peer_and_refuse_a_remote_one() {
879 let subnets =
880 LocalSubnets::from_prefixes([("192.168.1.10".parse().expect("an address"), 24)]);
881 let app = lan_router(endpoint(), subnets);
882
883 let local: std::net::SocketAddr = "192.168.1.50:9000".parse().expect("an address");
884 assert_eq!(get(app.clone(), Some(local)).await, StatusCode::OK);
885
886 let remote: std::net::SocketAddr = "8.8.8.8:9000".parse().expect("an address");
887 assert_eq!(
888 get(app.clone(), Some(remote)).await,
889 StatusCode::UNAUTHORIZED
890 );
891
892 assert_eq!(get(app, None).await, StatusCode::UNAUTHORIZED);
896 }
897
898 async fn body(response: axum::response::Response) -> String {
899 let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)
900 .await
901 .expect("a body");
902 String::from_utf8(bytes.to_vec()).expect("UTF-8")
903 }
904
905 #[tokio::test(start_paused = true)]
906 async fn a_long_poll_with_nothing_to_say_is_no_content() {
907 let subnets =
910 LocalSubnets::from_prefixes([("192.168.1.10".parse().expect("an address"), 24)]);
911 let app = lan_router(endpoint(), subnets);
912 let mut request = axum::http::Request::builder()
913 .method("POST")
914 .uri("/v1/waitForPairing")
915 .header("content-type", "application/json")
916 .body(axum::body::Body::from(r#"[{"clientNodeId":"rm-1"}]"#))
917 .expect("a request");
918 let peer: std::net::SocketAddr = "192.168.1.50:9000".parse().expect("an address");
919 request
920 .extensions_mut()
921 .insert(axum::extract::ConnectInfo(peer));
922 let response = app.oneshot(request).await.expect("an answer");
923 assert_eq!(response.status(), StatusCode::NO_CONTENT);
924 }
925
926 #[tokio::test]
927 async fn the_version_index_answers_at_the_root() {
928 let request = axum::http::Request::builder()
929 .uri("/")
930 .body(axum::body::Body::empty())
931 .expect("a request");
932 let response = router(endpoint())
933 .oneshot(request)
934 .await
935 .expect("an answer");
936 assert_eq!(response.status(), StatusCode::OK);
937 assert_eq!(body(response).await, r#"["v1"]"#);
938 }
939
940 #[tokio::test]
941 async fn a_body_that_does_not_parse_is_a_named_parsing_error() {
942 for (path, field) in [
944 ("/v1/requestPairing", "PairingResponseErrorMessage"),
945 ("/v1/initiateSession", "CommunicationDetailsErrorMessage"),
946 ] {
947 let request = axum::http::Request::builder()
948 .method("POST")
949 .uri(path)
950 .header("content-type", "application/json")
951 .header("authorization", "Bearer x")
952 .body(axum::body::Body::from("{\"not\": \"a request\"}"))
953 .expect("a request");
954 let response = router(endpoint())
955 .oneshot(request)
956 .await
957 .expect("an answer");
958 assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{path}");
959 let text = body(response).await;
960 assert!(text.contains("ParsingError"), "{path} ({field}): {text}");
961 }
962 }
963
964 #[tokio::test]
965 async fn the_wan_router_has_no_lan_routes_to_admit_anyone_to() {
966 let app = router(endpoint());
967 let local: std::net::SocketAddr = "127.0.0.1:9000".parse().expect("an address");
968 assert_eq!(get(app, Some(local)).await, StatusCode::NOT_FOUND);
971 }
972}