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    /// What to do when a client says the user has started pairing on their side.
51    on_prepare: Option<Arc<dyn Fn(PrepareSignal) + Send + Sync>>,
52}
53
54/// The "a user is about to pair with you" signal, and its cancellation.
55///
56/// `S2C §preparePairing`: "It is up to the server implementation to decide what to do with
57/// this signal, but it can be used to display a pop-up with the pairing token in its UI to
58/// improve the user experience." A device with a screen shows the code at the moment
59/// somebody is looking for it, rather than making them go and find it.
60///
61/// Best effort by design: "When a preparePairing is called, it is not guaranteed that a
62/// call to pairingRequest or cancelPreparePairing will follow." Anything a handler starts
63/// needs its own timeout.
64#[derive(Debug, Clone)]
65#[non_exhaustive]
66pub enum PrepareSignal {
67    /// The user has started pairing on the client and wants this node's code.
68    Prepare(crate::connect::proto::PreparePairing),
69    /// They changed their mind.
70    Cancel(crate::connect::proto::CancelPreparePairing),
71}
72
73/// A pairing attempt in flight, from the router's point of view.
74#[derive(Debug, Clone, Copy)]
75struct Attempt {
76    node: NodeId,
77    /// After this, the state machine would refuse the attempt anyway.
78    expires: Timestamp,
79}
80
81impl core::fmt::Debug for Endpoint {
82    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
83        f.debug_struct("Endpoint")
84            .field("pairing", &self.pairing)
85            .field("session", &self.session)
86            .finish_non_exhaustive()
87    }
88}
89
90impl Endpoint {
91    /// An endpoint serving both APIs.
92    #[must_use]
93    pub fn new(pairing: Arc<PairingService>, session: Arc<SessionService>) -> Self {
94        Self {
95            pairing,
96            session,
97            attempts: Arc::new(std::sync::Mutex::new(Vec::new())),
98            long_poll: Arc::new(LongPoll::default()),
99            clock: Timestamp::now,
100            on_prepare: None,
101        }
102    }
103
104    /// React to a client announcing that its user has started pairing.
105    ///
106    /// Typically: show the pairing code on a display, or light an LED. The handler runs
107    /// inside the request, so it must not block — and it must not be trusted, because the
108    /// signal is unauthenticated and only reaches you at all through the same-subnet
109    /// check in [`lan_router`].
110    #[must_use]
111    pub fn on_prepare_pairing(
112        mut self,
113        handler: impl Fn(PrepareSignal) + Send + Sync + 'static,
114    ) -> Self {
115        self.on_prepare = Some(Arc::new(handler));
116        self
117    }
118
119    /// Use a different clock — a virtual one, in a test.
120    #[must_use]
121    pub fn with_clock(mut self, clock: fn() -> Timestamp) -> Self {
122        self.clock = clock;
123        self
124    }
125
126    /// The session service, for a host that also terminates the WebSocket.
127    #[must_use]
128    pub fn session(&self) -> &Arc<SessionService> {
129        &self.session
130    }
131
132    fn remember(&self, id: PairingAttemptId, node: NodeId, now: Timestamp) {
133        let Ok(mut attempts) = self.attempts.lock() else {
134            return;
135        };
136        // Sweep on insert rather than on a timer: the only thing that grows this list is
137        // the operation that also cleans it, so it cannot outrun its own collection.
138        attempts.retain(|(_, attempt)| attempt.expires > now);
139        attempts.push((
140            id,
141            Attempt {
142                node,
143                expires: now
144                    .checked_add(crate::connect::proto::PAIRING_BUDGET)
145                    .unwrap_or(now),
146            },
147        ));
148    }
149
150    /// Which node a bearer's attempt is for, if it is still live.
151    ///
152    /// A list scanned with a constant-time comparison rather than a map keyed by the
153    /// bearer: the attempt id *is* a secret — it authenticates steps 6 to 8 — and how long
154    /// a tree takes to find a key is a function of the key. The list holds at most one
155    /// live entry per node, because the rate limit allows one attempt per node per second
156    /// and each expires after fifteen, so scanning it costs nothing worth saving.
157    ///
158    /// An expired entry is treated as absent, which the caller turns into `401` — and
159    /// `S2C-OAS` says a `401` here lets the client restart the pairing, which is exactly
160    /// the right thing to do with an attempt whose fifteen seconds have gone.
161    fn attempt_node(&self, bearer: &str, now: Timestamp) -> Option<NodeId> {
162        let attempts = self.attempts.lock().ok()?;
163        // Every entry is examined, so how long this takes does not say which matched.
164        let mut found = None;
165        for (id, attempt) in attempts.iter() {
166            if id.verify(bearer) && attempt.expires > now {
167                found = Some(attempt.node);
168            }
169        }
170        found
171    }
172
173    fn forget(&self, bearer: &str) {
174        if let Ok(mut attempts) = self.attempts.lock() {
175            attempts.retain(|(id, _)| !id.verify(bearer));
176        }
177    }
178
179    /// The most long-polling nodes one endpoint will remember.
180    ///
181    /// `waitForPairing` carries no bearer and its body is a list of identifiers the caller
182    /// chose, so the table it fills is bounded. A LAN endpoint talks to tens of devices.
183    pub const MAX_WAITING_NODES: usize = LongPoll::MAX_WAITING;
184
185    /// The most nodes a single `waitForPairing` may ask about.
186    pub const MAX_NODES_PER_POLL: usize = LongPoll::MAX_PER_POLL;
187
188    /// Tell a long-polling node to do something the next time it asks.
189    ///
190    /// This is the other half of [`lan_router`]'s `waitForPairing`: a Resource Manager
191    /// with no listening socket cannot be dialled, so when a person presses the pairing
192    /// button *here* the instruction waits until that node next checks in. A request that
193    /// is already held open is woken at once, so "waits" is usually microseconds.
194    pub fn instruct_waiting_node(&self, client: NodeId, action: crate::connect::proto::WaitAction) {
195        self.long_poll.instruct(client, action);
196    }
197
198    /// Every node that is long-polling this endpoint, and what it has said about itself.
199    ///
200    /// What a user interface lists when somebody asks "what is out there to pair with?" —
201    /// the counterpart of `GET /v1/nodes` for clients that have no server to browse.
202    #[must_use]
203    pub fn waiting_nodes(&self) -> Vec<(NodeId, WaitingNode)> {
204        self.long_poll.waiting()
205    }
206
207    /// This endpoint's clock, which the WebSocket route reads too.
208    pub(super) fn now(&self) -> Timestamp {
209        (self.clock)()
210    }
211
212    /// How many attempts the router is tracking. For a test, and for a health endpoint.
213    #[must_use]
214    pub fn live_attempts(&self) -> usize {
215        self.attempts.lock().map_or(0, |attempts| attempts.len())
216    }
217}
218
219/// The router for an S2 Connect endpoint, mounted at `/v1`.
220///
221/// `S2C §Formal specification and versioning` puts every operation under a version
222/// segment, and the OpenAPI's `servers` entry is `/v1`. Mounting it anywhere else makes
223/// an endpoint no client can talk to.
224pub fn router(endpoint: Endpoint) -> axum::Router {
225    axum::Router::new()
226        .nest("/v1", authenticated_routes(endpoint))
227        .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
228}
229
230/// The largest request body any S2 Connect operation will read.
231///
232/// `requestPairing` needs no bearer, so the number is not a tuning knob — it is the point
233/// at which an unauthenticated caller stops being able to make this process allocate. The
234/// biggest legitimate body is a `requestPairing` carrying two node descriptions, two
235/// endpoint descriptions and a Base64 challenge: a few kilobytes. Sixty-four is generous
236/// enough that no conforming peer will ever meet it and small enough that meeting it
237/// costs nothing.
238pub const MAX_BODY_BYTES: usize = 64 * 1024;
239
240/// The router for a **LAN** endpoint: everything above, plus the operations only LAN
241/// endpoints implement, each behind the same-subnet check they require.
242///
243/// This is a separate function rather than a flag because the unauthenticated operations
244/// need to be impossible to expose by accident. `GET /v1/nodes` tells whoever asks the
245/// brand, model and role of every flexible device in the building, and
246/// `POST /v1/preparePairing` makes a device display its pairing code — neither carries a
247/// bearer, a challenge or a signature. The subnet *is* the access control, so it is not
248/// optional and cannot be forgotten: you cannot mount these routes without supplying
249/// [`LocalSubnets`].
250///
251/// A WAN endpoint uses [`router`] instead. The absent routes then answer `404`, which is
252/// what `S2C §LAN-LAN only interactions` recommends: "WAN endpoints **cannot** implement
253/// these operations. It is **recommended** that WAN endpoints respond with status code
254/// 404."
255///
256/// Requires the server to have been started with
257/// `into_make_service_with_connect_info::<SocketAddr>()`; without a peer address the
258/// subnet check fails closed and every LAN-only request is refused.
259pub fn lan_router(endpoint: Endpoint, subnets: LocalSubnets) -> axum::Router {
260    let lan_only = axum::Router::new()
261        .route("/endpoint", get(get_endpoint))
262        .route("/nodes", get(get_nodes))
263        .route("/preparePairing", post(prepare_pairing))
264        .route("/cancelPreparePairing", post(cancel_prepare_pairing))
265        .route("/waitForPairing", post(wait_for_pairing))
266        .with_state(endpoint.clone())
267        .layer(axum::middleware::from_fn_with_state(
268            subnets,
269            super::subnet::same_subnet,
270        ));
271
272    axum::Router::new()
273        .nest("/v1", authenticated_routes(endpoint).merge(lan_only))
274        .layer(axum::extract::DefaultBodyLimit::max(MAX_BODY_BYTES))
275}
276
277/// The operations every endpoint implements, LAN or WAN.
278///
279/// Each is authenticated: `requestPairing` by the pairing token it proves knowledge of,
280/// the rest by a bearer.
281fn authenticated_routes(endpoint: Endpoint) -> axum::Router {
282    axum::Router::new()
283        .route("/requestPairing", post(request_pairing))
284        .route(
285            "/requestConnectionDetails",
286            post(request_connection_details),
287        )
288        .route("/postConnectionDetails", post(post_connection_details))
289        .route("/finalizePairing", post(finalize_pairing))
290        .route("/initiateSession", post(initiate_session))
291        .route("/confirmAccessToken", post(confirm_access_token))
292        .route("/unpair", post(unpair))
293        .with_state(endpoint)
294}
295
296// ---------------------------------------------------------------------------
297// Pairing
298// ---------------------------------------------------------------------------
299
300async fn request_pairing(
301    State(endpoint): State<Endpoint>,
302    Json(request): Json<PairingRequest>,
303) -> Response {
304    let mut nonce = [0u8; 32];
305    let mut attempt = [0u8; 24];
306    if fill_random(&mut nonce).is_err() || fill_random(&mut attempt).is_err() {
307        return StatusCode::INTERNAL_SERVER_ERROR.into_response();
308    }
309    let Ok(attempt_id) = PairingAttemptId::from_entropy(&attempt) else {
310        return StatusCode::INTERNAL_SERVER_ERROR.into_response();
311    };
312    let bearer = attempt_id.clone();
313    let now = (endpoint.clock)();
314
315    match endpoint
316        .pairing
317        .request_pairing(&request, &nonce, attempt_id, now)
318    {
319        Ok((node, send_after, accepted)) => {
320            // The mandatory delay, honoured by actually waiting. A server that computes
321            // `send_after` and answers anyway has implemented a comment, not a rule.
322            let wait = send_after.saturating_duration_since((endpoint.clock)());
323            if !wait.is_zero() {
324                tokio::time::sleep(core::time::Duration::from(wait)).await;
325            }
326            endpoint.remember(bearer, node, now);
327            crate::trace::event!(info, node = %node, "answered a pairing request");
328            (StatusCode::OK, Json(accepted)).into_response()
329        }
330        Err(e) => {
331            crate::trace::event!(warn, error = %e, "refused a pairing request");
332            pairing_error(e)
333        }
334    }
335}
336
337async fn request_connection_details(
338    State(endpoint): State<Endpoint>,
339    bearer: Bearer,
340    Json(request): Json<ConnectionDetailsRequest>,
341) -> Response {
342    let now = (endpoint.clock)();
343    let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
344        return StatusCode::UNAUTHORIZED.into_response();
345    };
346    match endpoint
347        .pairing
348        .request_connection_details(
349            node,
350            &bearer.0,
351            &request.server_hmac_challenge_response,
352            now,
353        )
354        .await
355    {
356        Ok(details) => (StatusCode::OK, Json(details)).into_response(),
357        Err(e) => {
358            if matches!(e, ConnectError::ChallengeFailed) {
359                endpoint.forget(&bearer.0);
360            }
361            pairing_error(e)
362        }
363    }
364}
365
366async fn post_connection_details(
367    State(endpoint): State<Endpoint>,
368    bearer: Bearer,
369    Json(request): Json<ConnectionDetailsPost>,
370) -> Response {
371    let now = (endpoint.clock)();
372    let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
373        return StatusCode::UNAUTHORIZED.into_response();
374    };
375    match endpoint
376        .pairing
377        .post_connection_details(
378            node,
379            &bearer.0,
380            &request.server_hmac_challenge_response,
381            request.connection_details,
382            now,
383        )
384        .await
385    {
386        Ok(()) => StatusCode::NO_CONTENT.into_response(),
387        Err(e) => {
388            if matches!(e, ConnectError::ChallengeFailed) {
389                endpoint.forget(&bearer.0);
390            }
391            pairing_error(e)
392        }
393    }
394}
395
396async fn finalize_pairing(
397    State(endpoint): State<Endpoint>,
398    bearer: Bearer,
399    Json(body): Json<FinalizePairing>,
400) -> Response {
401    let now = (endpoint.clock)();
402    let Some(node) = endpoint.attempt_node(&bearer.0, now) else {
403        return StatusCode::UNAUTHORIZED.into_response();
404    };
405    let result = endpoint
406        .pairing
407        .finalize(node, &bearer.0, body.success, now)
408        .await;
409    // The attempt is over either way: "Once the pairing process is finished (with or
410    // without success) the identifier can be discarded."
411    endpoint.forget(&bearer.0);
412    match result {
413        Ok(()) => {
414            crate::trace::event!(
415                info,
416                node = %node,
417                success = body.success,
418                "pairing finalized"
419            );
420            StatusCode::NO_CONTENT.into_response()
421        }
422        Err(e) => {
423            crate::trace::event!(warn, error = %e, "finalization refused");
424            pairing_error(e)
425        }
426    }
427}
428
429// ---------------------------------------------------------------------------
430// LAN-only informational routes
431// ---------------------------------------------------------------------------
432
433async fn get_endpoint(State(endpoint): State<Endpoint>) -> Response {
434    // The schema is `EndpointDescription` itself, with no envelope.
435    (StatusCode::OK, Json(endpoint.pairing.endpoint().clone())).into_response()
436}
437
438async fn get_nodes(State(endpoint): State<Endpoint>) -> Response {
439    // Likewise a bare array of `NodeDescription`. The alias each node is known by is
440    // deliberately not in it (erratum E21).
441    let nodes: Vec<crate::connect::proto::NodeDescription> = endpoint
442        .pairing
443        .store()
444        .nodes()
445        .into_iter()
446        .map(|(node, _alias)| node)
447        .collect();
448    (StatusCode::OK, Json(nodes)).into_response()
449}
450
451async fn prepare_pairing(
452    State(endpoint): State<Endpoint>,
453    Json(body): Json<crate::connect::proto::PreparePairing>,
454) -> Response {
455    // "204: Notification received (also used when provided serverNodeId is not known)" —
456    // so an unknown node is not an error, and telling the caller which node identifiers
457    // exist would be a disclosure the operation does not owe them.
458    if let Some(handler) = &endpoint.on_prepare {
459        handler(PrepareSignal::Prepare(body));
460    }
461    StatusCode::NO_CONTENT.into_response()
462}
463
464async fn cancel_prepare_pairing(
465    State(endpoint): State<Endpoint>,
466    Json(body): Json<crate::connect::proto::CancelPreparePairing>,
467) -> Response {
468    if let Some(handler) = &endpoint.on_prepare {
469        handler(PrepareSignal::Cancel(body));
470    }
471    StatusCode::NO_CONTENT.into_response()
472}
473
474/// `POST /v1/waitForPairing` — held open until there is something to say.
475///
476/// Always `200`, with a list that may be empty: "nothing yet, ask again" is the normal
477/// answer and must not look like a failure, or a client that is working perfectly spends
478/// its life backing off.
479async fn wait_for_pairing(
480    State(endpoint): State<Endpoint>,
481    Json(nodes): Json<Vec<crate::connect::proto::WaitForPairing>>,
482) -> Response {
483    let instructions = endpoint.long_poll.poll(&nodes).await;
484    (StatusCode::OK, Json(instructions)).into_response()
485}
486
487// ---------------------------------------------------------------------------
488// Session initiation
489// ---------------------------------------------------------------------------
490
491async fn initiate_session(
492    State(endpoint): State<Endpoint>,
493    bearer: Bearer,
494    Json(request): Json<crate::connect::proto::SessionRequest>,
495) -> Response {
496    let mut entropy = [0u8; 32];
497    if fill_random(&mut entropy).is_err() {
498        return StatusCode::INTERNAL_SERVER_ERROR.into_response();
499    }
500    let token = AccessToken::new(bearer.0);
501    let now = (endpoint.clock)();
502    match endpoint
503        .session
504        .initiate_session(&token, &request, &entropy, now)
505    {
506        Ok(grant) => (StatusCode::OK, Json(grant)).into_response(),
507        Err(e) => session_error(e),
508    }
509}
510
511async fn confirm_access_token(State(endpoint): State<Endpoint>, bearer: Bearer) -> Response {
512    let mut entropy = [0u8; 32];
513    if fill_random(&mut entropy).is_err() {
514        return StatusCode::INTERNAL_SERVER_ERROR.into_response();
515    }
516    let token = AccessToken::new(bearer.0);
517    let now = (endpoint.clock)();
518    match endpoint.session.confirm_access_token(&token, &entropy, now) {
519        Ok((remote, details)) => {
520            crate::trace::event!(info, node = %remote, "issued a communication token");
521            (StatusCode::OK, Json(details)).into_response()
522        }
523        // A grant that was not confirmed inside `PENDING_TOKEN_LIFETIME` reads the same
524        // way to the client as one that was never issued: start again. The token it
525        // already holds is untouched, so starting again is all it has to do.
526        Err(_) => StatusCode::UNAUTHORIZED.into_response(),
527    }
528}
529
530async fn unpair(
531    State(endpoint): State<Endpoint>,
532    bearer: Bearer,
533    Json(request): Json<crate::connect::proto::UnpairRequest>,
534) -> Response {
535    let token = AccessToken::new(bearer.0);
536    match endpoint.session.unpair(&token, &request) {
537        Ok(()) => StatusCode::NO_CONTENT.into_response(),
538        Err(_) => StatusCode::UNAUTHORIZED.into_response(),
539    }
540}
541
542// ---------------------------------------------------------------------------
543// Plumbing
544// ---------------------------------------------------------------------------
545
546/// The `Authorization: Bearer …` header, which every step after the first carries.
547pub(super) struct Bearer(String);
548
549impl Bearer {
550    /// The token as presented. Compare it in constant time, never with `==`.
551    pub(super) fn as_str(&self) -> &str {
552        &self.0
553    }
554}
555
556impl<S: Send + Sync> axum::extract::FromRequestParts<S> for Bearer {
557    type Rejection = StatusCode;
558
559    // The trait is async; reading a header is not.
560    #[allow(clippy::unused_async_trait_impl)]
561    async fn from_request_parts(
562        parts: &mut axum::http::request::Parts,
563        _state: &S,
564    ) -> Result<Self, Self::Rejection> {
565        parts
566            .headers
567            .get(axum::http::header::AUTHORIZATION)
568            .and_then(|value| value.to_str().ok())
569            // RFC 9110 §11.4: "the scheme is a case-insensitive token". A client that
570            // writes `bearer` is conforming, and refusing it is our bug, not theirs.
571            .and_then(|value| {
572                let (scheme, token) = value.split_once(' ')?;
573                scheme.eq_ignore_ascii_case("Bearer").then_some(token)
574            })
575            .map(|token| Self(token.trim().to_string()))
576            .filter(|bearer| !bearer.0.is_empty())
577            .ok_or(StatusCode::UNAUTHORIZED)
578    }
579}
580
581/// The mapping the specification's recovery logic depends on.
582fn pairing_error(error: ConnectError) -> Response {
583    match error {
584        // "The server is temporarily not able to process the pairing request, try again
585        // soon." Not a failure; a client that treats it as one gives up too early.
586        ConnectError::RateLimited => StatusCode::SERVICE_UNAVAILABLE.into_response(),
587        // "Provided pairingAttemptId not accepted. The client may restart the pairing
588        // process by calling /requestPairing again."
589        ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
590        // "The PairingAttempt has failed and cannot proceed." Distinct from 401 on
591        // purpose: restarting is the only option, and the client must not retry the step.
592        ConnectError::ChallengeFailed => StatusCode::FORBIDDEN.into_response(),
593        ConnectError::Refused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
594        ConnectError::Expired { .. } | ConnectError::OutOfOrder { .. } => {
595            StatusCode::BAD_REQUEST.into_response()
596        }
597        _ => StatusCode::BAD_REQUEST.into_response(),
598    }
599}
600
601fn session_error(error: ConnectError) -> Response {
602    match error {
603        // "Unauthorized, combination of clientNodeId and accessToken not accepted."
604        ConnectError::NotPaired => StatusCode::UNAUTHORIZED.into_response(),
605        ConnectError::SessionRefused(body) => (StatusCode::BAD_REQUEST, Json(body)).into_response(),
606        _ => StatusCode::BAD_REQUEST.into_response(),
607    }
608}
609
610fn fill_random(buffer: &mut [u8]) -> Result<(), rand::rngs::SysError> {
611    use rand::TryRng as _;
612    rand::rngs::SysRng.try_fill_bytes(buffer)
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618
619    fn at(secs: i64) -> Timestamp {
620        Timestamp::from_unix(1_700_000_000 + secs, 0)
621    }
622
623    fn endpoint() -> Endpoint {
624        let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
625        Endpoint::new(
626            Arc::new(PairingService::wan(
627                store.clone(),
628                crate::connect::proto::EndpointDescription::default(),
629                "pairing.example.com",
630            )),
631            Arc::new(SessionService::new(store, "wss://example.com/s2")),
632        )
633    }
634
635    #[test]
636    fn an_attempt_stops_authenticating_when_its_budget_runs_out() {
637        let endpoint = endpoint();
638        let node = NodeId::parse("cem-1").expect("a legal id");
639        endpoint.remember(PairingAttemptId::new("bearer-one"), node, at(0));
640
641        assert_eq!(endpoint.attempt_node("bearer-one", at(0)), Some(node));
642        assert_eq!(endpoint.attempt_node("bearer-one", at(14)), Some(node));
643        // Fifteen seconds is the whole budget; after it the state machine would refuse
644        // the attempt anyway, so the router stops routing to it.
645        assert_eq!(endpoint.attempt_node("bearer-one", at(15)), None);
646        assert_eq!(endpoint.attempt_node("bearer-one", at(16)), None);
647        // And something nobody issued never authenticated in the first place.
648        assert_eq!(endpoint.attempt_node("not-a-bearer", at(0)), None);
649    }
650
651    #[test]
652    fn abandoned_attempts_are_swept_rather_than_accumulated() {
653        // `requestPairing` carries no bearer, so anyone who can reach the endpoint can
654        // add an entry, and a client that walks away never removes it. Unbounded growth
655        // driven by unauthenticated input is not something a device running for years
656        // can afford.
657        let endpoint = endpoint();
658        let node = NodeId::parse("cem-1").expect("a legal id");
659
660        for i in 0..100 {
661            endpoint.remember(
662                PairingAttemptId::new(alloc::format!("abandoned-{i}")),
663                node,
664                at(i),
665            );
666        }
667        // Each insert sweeps, so only the ones still inside their budget survive.
668        assert!(
669            endpoint.live_attempts() <= 16,
670            "expected at most one budget's worth, got {}",
671            endpoint.live_attempts()
672        );
673
674        // Long afterwards, one more request clears the lot.
675        endpoint.remember(PairingAttemptId::new("fresh"), node, at(1_000));
676        assert_eq!(endpoint.live_attempts(), 1);
677        assert_eq!(
678            endpoint.attempt_node("fresh", at(1_000)),
679            Some(node),
680            "and the new one is the survivor"
681        );
682    }
683
684    #[test]
685    fn finalizing_forgets_the_attempt_immediately() {
686        // "Once the pairing process is finished (with or without success) the identifier
687        // can be discarded" — not fifteen seconds later.
688        let endpoint = endpoint();
689        let node = NodeId::parse("cem-1").expect("a legal id");
690        endpoint.remember(PairingAttemptId::new("bearer"), node, at(0));
691        assert_eq!(endpoint.live_attempts(), 1);
692        endpoint.forget("bearer");
693        assert_eq!(endpoint.live_attempts(), 0);
694        assert_eq!(endpoint.attempt_node("bearer", at(0)), None);
695    }
696
697    #[test]
698    fn the_status_codes_are_the_ones_the_specification_distinguishes() {
699        // These four are the difference between a client that recovers and one that does
700        // not, and they are easy to collapse into a single 400.
701        let code = |e: ConnectError| pairing_error(e).status();
702        assert_eq!(
703            code(ConnectError::RateLimited),
704            StatusCode::SERVICE_UNAVAILABLE
705        );
706        assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
707        assert_eq!(code(ConnectError::ChallengeFailed), StatusCode::FORBIDDEN);
708        assert_eq!(
709            code(ConnectError::Refused(
710                crate::connect::proto::PairingRefused {
711                    error_message: crate::connect::proto::PairingErrorMessage::NodeNotFound,
712                    additional_info: None,
713                }
714            )),
715            StatusCode::BAD_REQUEST
716        );
717
718        // And session initiation has its own two.
719        let code = |e: ConnectError| session_error(e).status();
720        assert_eq!(code(ConnectError::NotPaired), StatusCode::UNAUTHORIZED);
721        assert_eq!(
722            code(ConnectError::SessionRefused(
723                crate::connect::proto::SessionRefused {
724                    error_message: crate::connect::proto::SessionErrorMessage::NoLongerPaired,
725                    additional_info: None,
726                }
727            )),
728            StatusCode::BAD_REQUEST
729        );
730    }
731}
732
733#[cfg(test)]
734mod subnet_wiring {
735    use super::*;
736    use tower::ServiceExt as _;
737
738    fn endpoint() -> Endpoint {
739        let store: Arc<dyn super::super::store::Store> = super::super::store::Memory::new();
740        Endpoint::new(
741            Arc::new(PairingService::lan(
742                store.clone(),
743                crate::connect::proto::EndpointDescription::default(),
744                crate::connect::tls::Fingerprint::parse(&"AA".repeat(32)).expect("a fingerprint"),
745            )),
746            Arc::new(SessionService::new(store, "wss://example.com/s2")),
747        )
748    }
749
750    async fn get(app: axum::Router, peer: Option<std::net::SocketAddr>) -> StatusCode {
751        let mut request = axum::http::Request::builder()
752            .uri("/v1/endpoint")
753            .body(axum::body::Body::empty())
754            .expect("a request");
755        if let Some(peer) = peer {
756            request
757                .extensions_mut()
758                .insert(axum::extract::ConnectInfo(peer));
759        }
760        app.oneshot(request)
761            .await
762            .expect("the router answers")
763            .status()
764    }
765
766    #[tokio::test]
767    async fn the_lan_routes_admit_a_local_peer_and_refuse_a_remote_one() {
768        let subnets =
769            LocalSubnets::from_prefixes([("192.168.1.10".parse().expect("an address"), 24)]);
770        let app = lan_router(endpoint(), subnets);
771
772        let local: std::net::SocketAddr = "192.168.1.50:9000".parse().expect("an address");
773        assert_eq!(get(app.clone(), Some(local)).await, StatusCode::OK);
774
775        let remote: std::net::SocketAddr = "8.8.8.8:9000".parse().expect("an address");
776        assert_eq!(
777            get(app.clone(), Some(remote)).await,
778            StatusCode::UNAUTHORIZED
779        );
780
781        // No peer address at all means the server was not started with connect info.
782        // Failing closed is the only safe reading: the alternative is serving the
783        // unauthenticated routes to the internet because of a missing builder call.
784        assert_eq!(get(app, None).await, StatusCode::UNAUTHORIZED);
785    }
786
787    #[tokio::test]
788    async fn the_wan_router_has_no_lan_routes_to_admit_anyone_to() {
789        let app = router(endpoint());
790        let local: std::net::SocketAddr = "127.0.0.1:9000".parse().expect("an address");
791        // Absent, not refused: "It is recommended that WAN endpoints respond with status
792        // code 404."
793        assert_eq!(get(app, Some(local)).await, StatusCode::NOT_FOUND);
794    }
795}