Skip to main content

s2_kit/connect/server/
routes.rs

1//! The router: URLs in, status codes out.
2//!
3//! The mapping from a protocol outcome to a status code is the whole content of this
4//! file, and it is not mechanical — see the table in the [module documentation](super).
5
6use 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/// Everything the routes need.
28///
29/// Cloneable and cheap: an `Arc` of each service.
30#[derive(Clone)]
31pub struct Endpoint {
32    pairing: Arc<PairingService>,
33    session: Arc<SessionService>,
34    /// Which node each live pairing attempt is for, keyed by its bearer, and when that
35    /// attempt stops being live.
36    ///
37    /// The attempt id authenticates steps 6–8 and the node is what routes them; keeping
38    /// the map here rather than in the service leaves the service free of HTTP concerns.
39    ///
40    /// The deadline is not decoration. `requestPairing` needs no bearer, so anyone who
41    /// can reach the endpoint can add an entry, and a client that opens an attempt and
42    /// then vanishes never reaches `finalizePairing` to remove it. Without expiry this
43    /// map is unbounded growth driven by unauthenticated input — slow, because the
44    /// per-node rate limit caps it at one entry per second per node, but a device that
45    /// runs for years does not get to leak slowly.
46    attempts: Arc<std::sync::Mutex<Vec<(PairingAttemptId, Attempt)>>>,
47    /// What this endpoint has to tell nodes that are long-polling it.
48    long_poll: Arc<LongPoll>,
49    clock: fn() -> Timestamp,
50    /// The largest WebSocket frame this endpoint will buffer.
51    ///
52    /// Here rather than on the route because it is the *endpoint's* budget: the same
53    /// number the codec and the session engine use, applied where it bounds memory rather
54    /// than where it bounds parsing.
55    max_message_bytes: usize,
56    /// What to do when a client says the user has started pairing on their side.
57    on_prepare: Option<Arc<dyn Fn(PrepareSignal) + Send + Sync>>,
58}
59
60/// The "a user is about to pair with you" signal, and its cancellation.
61///
62/// `S2C §preparePairing`: "It is up to the server implementation to decide what to do with
63/// this signal, but it can be used to display a pop-up with the pairing token in its UI to
64/// improve the user experience." A device with a screen shows the code at the moment
65/// somebody is looking for it, rather than making them go and find it.
66///
67/// Best effort by design: "When a preparePairing is called, it is not guaranteed that a
68/// call to pairingRequest or cancelPreparePairing will follow." Anything a handler starts
69/// needs its own timeout.
70#[derive(Debug, Clone)]
71#[non_exhaustive]
72pub enum PrepareSignal {
73    /// The user has started pairing on the client and wants this node's code.
74    Prepare(crate::connect::proto::PreparePairing),
75    /// They changed their mind.
76    Cancel(crate::connect::proto::CancelPreparePairing),
77}
78
79/// A pairing attempt in flight, from the router's point of view.
80#[derive(Debug, Clone, Copy)]
81struct Attempt {
82    node: NodeId,
83    /// After this, the state machine would refuse the attempt anyway.
84    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    /// An endpoint serving both APIs.
98    #[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    /// Buffer no WebSocket frame larger than this.
112    ///
113    /// Defaults to
114    /// [`DecodeOptions::DEFAULT_MAX_BYTES`](crate::codec::DecodeOptions::DEFAULT_MAX_BYTES),
115    /// the mebibyte the codec and the session engines already use. Raise it only together
116    /// with the session's own `max_message_bytes`: a frame larger than the codec will
117    /// parse is a frame that is buffered and then refused.
118    #[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    /// The largest WebSocket frame this endpoint will buffer.
125    #[must_use]
126    pub const fn max_message_bytes(&self) -> usize {
127        self.max_message_bytes
128    }
129
130    /// React to a client announcing that its user has started pairing.
131    ///
132    /// Typically: show the pairing code on a display, or light an LED. The handler runs
133    /// inside the request, so it must not block — and it must not be trusted, because the
134    /// signal is unauthenticated and only reaches you at all through the same-subnet
135    /// check in [`lan_router`].
136    #[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    /// Use a different clock — a virtual one, in a test.
146    #[must_use]
147    pub fn with_clock(mut self, clock: fn() -> Timestamp) -> Self {
148        self.clock = clock;
149        self
150    }
151
152    /// The session service, for a host that also terminates the WebSocket.
153    #[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        // Sweep on insert rather than on a timer: the only thing that grows this list is
163        // the operation that also cleans it, so it cannot outrun its own collection.
164        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    /// Which node a bearer's attempt is for, if it is still live.
177    ///
178    /// A list scanned with a constant-time comparison rather than a map keyed by the
179    /// bearer: the attempt id *is* a secret — it authenticates steps 6 to 8 — and how long
180    /// a tree takes to find a key is a function of the key. The list holds at most one
181    /// live entry per node, because the rate limit allows one attempt per node per second
182    /// and each expires after fifteen, so scanning it costs nothing worth saving.
183    ///
184    /// An expired entry is treated as absent, which the caller turns into `401` — and
185    /// `S2C-OAS` says a `401` here lets the client restart the pairing, which is exactly
186    /// the right thing to do with an attempt whose fifteen seconds have gone.
187    fn attempt_node(&self, bearer: &str, now: Timestamp) -> Option<NodeId> {
188        let attempts = self.attempts.lock().ok()?;
189        // Every entry is examined, so how long this takes does not say which matched.
190        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    /// The most long-polling nodes one endpoint will remember.
206    ///
207    /// `waitForPairing` carries no bearer and its body is a list of identifiers the caller
208    /// chose, so the table it fills is bounded. A LAN endpoint talks to tens of devices.
209    pub const MAX_WAITING_NODES: usize = LongPoll::MAX_WAITING;
210
211    /// The most nodes a single `waitForPairing` may ask about.
212    pub const MAX_NODES_PER_POLL: usize = LongPoll::MAX_PER_POLL;
213
214    /// Tell a long-polling node to do something the next time it asks.
215    ///
216    /// This is the other half of [`lan_router`]'s `waitForPairing`: a Resource Manager
217    /// with no listening socket cannot be dialled, so when a person presses the pairing
218    /// button *here* the instruction waits until that node next checks in. A request that
219    /// is already held open is woken at once, so "waits" is usually microseconds.
220    pub fn instruct_waiting_node(&self, client: NodeId, action: crate::connect::proto::WaitAction) {
221        self.long_poll.instruct(client, action);
222    }
223
224    /// Every node that is long-polling this endpoint, and what it has said about itself.
225    ///
226    /// What a user interface lists when somebody asks "what is out there to pair with?" —
227    /// the counterpart of `GET /v1/nodes` for clients that have no server to browse.
228    #[must_use]
229    pub fn waiting_nodes(&self) -> Vec<(NodeId, WaitingNode)> {
230        self.long_poll.waiting()
231    }
232
233    /// This endpoint's clock, which the WebSocket route reads too.
234    pub(super) fn now(&self) -> Timestamp {
235        (self.clock)()
236    }
237
238    /// How many attempts the router is tracking. For a test, and for a health endpoint.
239    #[must_use]
240    pub fn live_attempts(&self) -> usize {
241        self.attempts.lock().map_or(0, |attempts| attempts.len())
242    }
243}
244
245/// The router for an S2 Connect endpoint, mounted at `/v1`.
246///
247/// `S2C §Formal specification and versioning` puts every operation under a version
248/// segment, and the OpenAPI's `servers` entry is `/v1`. Mounting it anywhere else makes
249/// an endpoint no client can talk to.
250pub 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
256/// The largest request body any S2 Connect operation will read.
257///
258/// `requestPairing` needs no bearer, so the number is not a tuning knob — it is the point
259/// at which an unauthenticated caller stops being able to make this process allocate. The
260/// biggest legitimate body is a `requestPairing` carrying two node descriptions, two
261/// endpoint descriptions and a Base64 challenge: a few kilobytes. Sixty-four is generous
262/// enough that no conforming peer will ever meet it and small enough that meeting it
263/// costs nothing.
264pub const MAX_BODY_BYTES: usize = 64 * 1024;
265
266/// The router for a **LAN** endpoint: everything above, plus the operations only LAN
267/// endpoints implement, each behind the same-subnet check they require.
268///
269/// This is a separate function rather than a flag because the unauthenticated operations
270/// need to be impossible to expose by accident. `GET /v1/nodes` tells whoever asks the
271/// brand, model and role of every flexible device in the building, and
272/// `POST /v1/preparePairing` makes a device display its pairing code — neither carries a
273/// bearer, a challenge or a signature. The subnet *is* the access control, so it is not
274/// optional and cannot be forgotten: you cannot mount these routes without supplying
275/// [`LocalSubnets`].
276///
277/// A WAN endpoint uses [`router`] instead. The absent routes then answer `404`, which is
278/// what `S2C §LAN-LAN only interactions` recommends: "WAN endpoints **cannot** implement
279/// these operations. It is **recommended** that WAN endpoints respond with status code
280/// 404."
281///
282/// Requires the server to have been started with
283/// `into_make_service_with_connect_info::<SocketAddr>()`; without a peer address the
284/// subnet check fails closed and every LAN-only request is refused.
285pub 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
303/// The operations every endpoint implements, LAN or WAN.
304///
305/// Each is authenticated: `requestPairing` by the pairing token it proves knowledge of,
306/// the rest by a bearer.
307fn 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
322// ---------------------------------------------------------------------------
323// Pairing
324// ---------------------------------------------------------------------------
325
326async 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            // The mandatory delay, honoured by actually waiting. A server that computes
347            // `send_after` and answers anyway has implemented a comment, not a rule.
348            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    // The attempt is over either way: "Once the pairing process is finished (with or
436    // without success) the identifier can be discarded."
437    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
455// ---------------------------------------------------------------------------
456// LAN-only informational routes
457// ---------------------------------------------------------------------------
458
459async fn get_endpoint(State(endpoint): State<Endpoint>) -> Response {
460    // The schema is `EndpointDescription` itself, with no envelope.
461    (StatusCode::OK, Json(endpoint.pairing.endpoint().clone())).into_response()
462}
463
464async fn get_nodes(State(endpoint): State<Endpoint>) -> Response {
465    // Likewise a bare array of `NodeDescription`. The alias each node is known by is
466    // deliberately not in it (erratum E21).
467    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    // "204: Notification received (also used when provided serverNodeId is not known)" —
482    // so an unknown node is not an error, and telling the caller which node identifiers
483    // exist would be a disclosure the operation does not owe them.
484    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
500/// `POST /v1/waitForPairing` — held open until there is something to say.
501///
502/// Always `200`, with a list that may be empty: "nothing yet, ask again" is the normal
503/// answer and must not look like a failure, or a client that is working perfectly spends
504/// its life backing off.
505async 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
513// ---------------------------------------------------------------------------
514// Session initiation
515// ---------------------------------------------------------------------------
516
517async 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        // A grant that was not confirmed inside `PENDING_TOKEN_LIFETIME` reads the same
550        // way to the client as one that was never issued: start again. The token it
551        // already holds is untouched, so starting again is all it has to do.
552        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
568// ---------------------------------------------------------------------------
569// Plumbing
570// ---------------------------------------------------------------------------
571
572/// The `Authorization: Bearer …` header, which every step after the first carries.
573pub(super) struct Bearer(String);
574
575impl Bearer {
576    /// The token as presented. Compare it in constant time, never with `==`.
577    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    // The trait is async; reading a header is not.
586    #[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            // RFC 9110 §11.4: "the scheme is a case-insensitive token". A client that
596            // writes `bearer` is conforming, and refusing it is our bug, not theirs.
597            .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
607/// The mapping the specification's recovery logic depends on.
608fn pairing_error(error: ConnectError) -> Response {
609    match error {
610        // "The server is temporarily not able to process the pairing request, try again
611        // soon." Not a failure; a client that treats it as one gives up too early.
612        ConnectError::RateLimited => StatusCode::SERVICE_UNAVAILABLE.into_response(),
613        // "Provided pairingAttemptId not accepted. The client may restart the pairing
614        // process by calling /requestPairing again."
615        ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
616        // "The PairingAttempt has failed and cannot proceed." Distinct from 401 on
617        // purpose: restarting is the only option, and the client must not retry the step.
618        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        // "Unauthorized, combination of clientNodeId and accessToken not accepted."
630        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        // Fifteen seconds is the whole budget; after it the state machine would refuse
670        // the attempt anyway, so the router stops routing to it.
671        assert_eq!(endpoint.attempt_node("bearer-one", at(15)), None);
672        assert_eq!(endpoint.attempt_node("bearer-one", at(16)), None);
673        // And something nobody issued never authenticated in the first place.
674        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        // `requestPairing` carries no bearer, so anyone who can reach the endpoint can
680        // add an entry, and a client that walks away never removes it. Unbounded growth
681        // driven by unauthenticated input is not something a device running for years
682        // can afford.
683        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        // Each insert sweeps, so only the ones still inside their budget survive.
694        assert!(
695            endpoint.live_attempts() <= 16,
696            "expected at most one budget's worth, got {}",
697            endpoint.live_attempts()
698        );
699
700        // Long afterwards, one more request clears the lot.
701        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        // "Once the pairing process is finished (with or without success) the identifier
713        // can be discarded" — not fifteen seconds later.
714        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        // These four are the difference between a client that recovers and one that does
726        // not, and they are easy to collapse into a single 400.
727        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        // And session initiation has its own two.
745        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        // No peer address at all means the server was not started with connect info.
808        // Failing closed is the only safe reading: the alternative is serving the
809        // unauthenticated routes to the internet because of a missing builder call.
810        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        // Absent, not refused: "It is recommended that WAN endpoints respond with status
818        // code 404."
819        assert_eq!(get(app, Some(local)).await, StatusCode::NOT_FOUND);
820    }
821}