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 API versions this endpoint serves, newest first: what `GET /` answers.
246pub const API_VERSIONS: &[&str] = &["v1"];
247
248/// The router for an S2 Connect endpoint: the version index at `/`, the operations
249/// under `/v1`.
250///
251/// `S2C §Versioning of OpenAPI files`: "The server **must** always … serve an index (e.g.
252/// `https://hostname.local/pairing/`) which returns a JSON array containing the versions
253/// of the API that it supports (e.g. `["v1", "v2"]`)." A client "**must** always first
254/// determine which version of the API it will use", and URLs exchanged between endpoints
255/// carry no version — so without the index no conforming client gets past its first
256/// request. Mount this router where the base URL you advertise points.
257pub 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
268/// The largest request body any S2 Connect operation will read.
269///
270/// `requestPairing` needs no bearer, so the number is not a tuning knob — it is the point
271/// at which an unauthenticated caller stops being able to make this process allocate. The
272/// biggest legitimate body is a `requestPairing` carrying two node descriptions, two
273/// endpoint descriptions and a Base64 challenge: a few kilobytes. Sixty-four is generous
274/// enough that no conforming peer will ever meet it and small enough that meeting it
275/// costs nothing.
276pub const MAX_BODY_BYTES: usize = 64 * 1024;
277
278/// The router for a **LAN** endpoint: everything above, plus the operations only LAN
279/// endpoints implement, each behind the same-subnet check they require.
280///
281/// This is a separate function rather than a flag because the unauthenticated operations
282/// need to be impossible to expose by accident. `GET /v1/nodes` tells whoever asks the
283/// brand, model and role of every flexible device in the building, and
284/// `POST /v1/preparePairing` makes a device display its pairing code — neither carries a
285/// bearer, a challenge or a signature. The subnet *is* the access control, so it is not
286/// optional and cannot be forgotten: you cannot mount these routes without supplying
287/// [`LocalSubnets`].
288///
289/// A WAN endpoint uses [`router`] instead. The absent routes then answer `404`, which is
290/// what `S2C §LAN-LAN only interactions` recommends: "WAN endpoints **cannot** implement
291/// these operations. It is **recommended** that WAN endpoints respond with status code
292/// 404."
293///
294/// Requires the server to have been started with
295/// `into_make_service_with_connect_info::<SocketAddr>()`; without a peer address the
296/// subnet check fails closed and every LAN-only request is refused.
297pub 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
316/// The operations every endpoint implements, LAN or WAN.
317///
318/// Each is authenticated: `requestPairing` by the pairing token it proves knowledge of,
319/// the rest by a bearer.
320fn 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
335// ---------------------------------------------------------------------------
336// Pairing
337// ---------------------------------------------------------------------------
338
339async 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            // The mandatory delay, honoured by actually waiting. A server that computes
360            // `send_after` and answers anyway has implemented a comment, not a rule.
361            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    // The attempt is over either way: "Once the pairing process is finished (with or
449    // without success) the identifier can be discarded."
450    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
471// ---------------------------------------------------------------------------
472// LAN-only informational routes
473// ---------------------------------------------------------------------------
474
475async fn get_endpoint(State(endpoint): State<Endpoint>) -> Response {
476    // The schema is `EndpointDescription` itself, with no envelope.
477    (StatusCode::OK, Json(endpoint.pairing.endpoint().clone())).into_response()
478}
479
480async fn get_nodes(State(endpoint): State<Endpoint>) -> Response {
481    // Likewise a bare array of `NodeDescription`. The alias each node is known by is
482    // deliberately not in it (erratum E21).
483    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    // "204: Notification received (also used when provided serverNodeId is not known)" —
498    // so an unknown node is not an error, and telling the caller which node identifiers
499    // exist would be a disclosure the operation does not owe them.
500    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
516/// `POST /v1/waitForPairing` — held open until there is something to say.
517///
518/// `200` with at least one instruction, or `204` when the hold ran out with nothing to
519/// say: `S2C-OAS pairing/waitForPairing` gives the `200` list `minItems: 1`, and
520/// `S2C §Long-polling` — "When the server wants the client to immediately do a new
521/// request, it responds with status code 204."
522async 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
533// ---------------------------------------------------------------------------
534// Session initiation
535// ---------------------------------------------------------------------------
536
537async 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        // A grant that was not confirmed inside `PENDING_TOKEN_LIFETIME` reads the same
570        // way to the client as one that was never issued: start again. The token it
571        // already holds is untouched, so starting again is all it has to do.
572        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
588// ---------------------------------------------------------------------------
589// Plumbing
590// ---------------------------------------------------------------------------
591
592/// The `Authorization: Bearer …` header, which every step after the first carries.
593pub(super) struct Bearer(String);
594
595impl Bearer {
596    /// The token as presented. Compare it in constant time, never with `==`.
597    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    // The trait is async; reading a header is not.
606    #[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            // RFC 9110 §11.4: "the scheme is a case-insensitive token". A client that
616            // writes `bearer` is conforming, and refusing it is our bug, not theirs.
617            .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
627/// A JSON body of the pairing API, refused as `400 ParsingError` when it does not parse.
628///
629/// `S2C §1. Request pairing`: "Is the request properly formatted …? | `ParsingError`".
630/// axum's own `Json` answers `415`/`422` with a plain-text body, which no S2 Connect
631/// client is written to read.
632pub(super) struct PairingBody<T>(pub T);
633
634/// The same, for the session-initiation API and its `SessionRefused` body.
635pub(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
695/// The mapping the specification's recovery logic depends on.
696fn pairing_error(error: ConnectError) -> Response {
697    match error {
698        // "The server is temporarily not able to process the pairing request, try again
699        // soon." Not a failure; a client that treats it as one gives up too early.
700        ConnectError::RateLimited => StatusCode::SERVICE_UNAVAILABLE.into_response(),
701        // "Provided pairingAttemptId not accepted. The client may restart the pairing
702        // process by calling /requestPairing again."
703        ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
704        // "The PairingAttempt has failed and cannot proceed." Distinct from 401 on
705        // purpose: restarting is the only option, and the client must not retry the step.
706        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        // "Unauthorized, combination of clientNodeId and accessToken not accepted."
718        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        // Fifteen seconds is the whole budget; after it the state machine would refuse
755        // the attempt anyway, so the router stops routing to it.
756        assert_eq!(endpoint.attempt_node("bearer-one", at(15)), None);
757        assert_eq!(endpoint.attempt_node("bearer-one", at(16)), None);
758        // And something nobody issued never authenticated in the first place.
759        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        // `requestPairing` carries no bearer, so anyone who can reach the endpoint can
765        // add an entry, and a client that walks away never removes it. Unbounded growth
766        // driven by unauthenticated input is not something a device running for years
767        // can afford.
768        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        // Each insert sweeps, so only the ones still inside their budget survive.
779        assert!(
780            endpoint.live_attempts() <= 16,
781            "expected at most one budget's worth, got {}",
782            endpoint.live_attempts()
783        );
784
785        // Long afterwards, one more request clears the lot.
786        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        // "Once the pairing process is finished (with or without success) the identifier
798        // can be discarded" — not fifteen seconds later.
799        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        // These four are the difference between a client that recovers and one that does
811        // not, and they are easy to collapse into a single 400.
812        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        // And session initiation has its own two.
830        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        // No peer address at all means the server was not started with connect info.
893        // Failing closed is the only safe reading: the alternative is serving the
894        // unauthenticated routes to the internet because of a missing builder call.
895        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        // `S2C-OAS pairing/waitForPairing`: `200` carries at least one item; a hold that
908        // ran out is `204`, "No action for the client, try again."
909        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        // Not axum's `422` with a plain-text body: `S2C §1` names this outcome.
943        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        // Absent, not refused: "It is recommended that WAN endpoints respond with status
969        // code 404."
970        assert_eq!(get(app, Some(local)).await, StatusCode::NOT_FOUND);
971    }
972}