Skip to main content

s2_kit/connect/server/
pairing.rs

1//! The pairing endpoints, and the per-node serialisation the specification demands.
2
3use alloc::collections::BTreeMap;
4use alloc::string::String;
5use alloc::sync::Arc;
6
7use alloc::vec::Vec;
8
9use crate::connect::proto::{
10    AccessToken, ConnectError, ConnectionDetails, Deployment, EndpointDescription, HmacBinding,
11    NodeId, PairingAccepted, PairingAttemptId, PairingErrorMessage, PairingRefused, PairingRequest,
12    PairingServer,
13};
14use crate::connect::tls::Fingerprint;
15use crate::types::Timestamp;
16
17use super::store::{PairedNode, PairingKey, Store};
18
19/// What this endpoint tells a client it should connect to, when this endpoint is the
20/// communication server (7A).
21///
22/// A template rather than a [`ConnectionDetails`]: the access token in the details is a
23/// secret **per pairing** — `S2C §8A`, "The server **must** generate an access token for
24/// the HTTPS client … by a cryptographically secure pseudorandom number generator" — so
25/// [`PairingService`] mints a fresh one for every client and only the URL and the CA are
26/// the host's to supply. Handing every client the same token lets any one of them open a
27/// session as any other.
28#[derive(Debug, Clone)]
29pub struct CommunicationServer {
30    /// The base URL of this endpoint's session-initiation API, **without** a version:
31    /// `S2C §8A`, `initiateSessionUrl` "does not include the version number".
32    pub initiate_session_url: String,
33    /// The CA this endpoint's communication certificate is issued by, sent as
34    /// `certificateFingerprint.SHA256` so a client can cross-check what it pins.
35    pub ca: Fingerprint,
36}
37
38/// What a completed `finalizePairing` changed.
39#[derive(Debug, Clone, Default)]
40pub struct Finalized {
41    /// The pairing stored, if the client reported success.
42    pub paired: Option<PairingKey>,
43    /// Pairings this one replaced, whose live sessions must end: the same two nodes
44    /// paired before (`S2C §Pairing process`, "the current communication session should
45    /// be terminated"), or — for a Resource Manager — the CEM it was paired with before,
46    /// since "A RM can only be paired with one CEM at a time".
47    pub displaced: Vec<PairingKey>,
48}
49
50/// Runs the pairing half of an endpoint.
51///
52/// One [`PairingServer`] per node, because the rate limit is per node: "Pairing attempts
53/// targeting different nodes **may** be processed in parallel… a server representing
54/// multiple nodes is not globally limited to one pairing attempt per second."
55///
56/// Serialisation is a per-node lock rather than a check-and-set, so two requests that
57/// arrive in the same millisecond cannot both see an idle slot.
58pub struct PairingService {
59    store: Arc<dyn Store>,
60    /// One state machine per node, each behind its own lock.
61    attempts: std::sync::Mutex<BTreeMap<NodeId, Arc<tokio::sync::Mutex<PairingServer>>>>,
62    endpoint: EndpointDescription,
63    /// What the challenge response is bound to: this endpoint's leaf fingerprint in a
64    /// LAN, its domain name in a WAN. Decided once, at construction, because it cannot
65    /// change while the endpoint is serving.
66    binding: HmacBinding,
67    /// What to hand a client that will be the communication client.
68    communication: Option<CommunicationServer>,
69}
70
71impl core::fmt::Debug for PairingService {
72    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
73        f.debug_struct("PairingService")
74            .field("endpoint", &self.endpoint)
75            .field("binding", &self.binding)
76            .finish_non_exhaustive()
77    }
78}
79
80impl PairingService {
81    /// A service for a LAN endpoint, bound to the leaf certificate it serves.
82    #[must_use]
83    ///
84    /// The endpoint description's `deployment` is set to LAN when it says nothing: which
85    /// side becomes the communication server is decided from it, and a peer reading an
86    /// absent deployment cannot know.
87    pub fn lan(
88        store: Arc<dyn Store>,
89        mut endpoint: EndpointDescription,
90        leaf: Fingerprint,
91    ) -> Self {
92        endpoint.deployment.get_or_insert(Deployment::Lan);
93        Self {
94            store,
95            attempts: std::sync::Mutex::new(BTreeMap::new()),
96            endpoint,
97            binding: leaf.binding(),
98            communication: None,
99        }
100    }
101
102    /// A service for a WAN endpoint, bound to its domain name.
103    #[must_use]
104    ///
105    /// The endpoint description's `deployment` is set to WAN when it says nothing.
106    pub fn wan(
107        store: Arc<dyn Store>,
108        mut endpoint: EndpointDescription,
109        domain: impl Into<String>,
110    ) -> Self {
111        endpoint.deployment.get_or_insert(Deployment::Wan);
112        Self {
113            store,
114            attempts: std::sync::Mutex::new(BTreeMap::new()),
115            endpoint,
116            binding: HmacBinding::DomainName(domain.into()),
117            communication: None,
118        }
119    }
120
121    /// Be the communication server for clients that pair with this endpoint (7A).
122    ///
123    /// Without this, a client that should be the communication client is refused with
124    /// `IncompatibleCommunicationProtocols`.
125    #[must_use]
126    pub fn as_communication_server(mut self, communication: CommunicationServer) -> Self {
127        self.communication = Some(communication);
128        self
129    }
130
131    /// The store, for a route that needs it.
132    #[must_use]
133    pub fn store(&self) -> &Arc<dyn Store> {
134        &self.store
135    }
136
137    /// The endpoint's own description.
138    #[must_use]
139    pub fn endpoint(&self) -> &EndpointDescription {
140        &self.endpoint
141    }
142
143    /// Which node a request is for.
144    ///
145    /// `S2C-OAS`: `nodeId` when the client knows it, `nodeIdAlias` when it only has the
146    /// code, neither when the endpoint hosts exactly one node — and never both.
147    fn target(&self, request: &PairingRequest) -> Result<NodeId, ConnectError> {
148        match (&request.node_id, &request.node_id_alias) {
149            (Some(_), Some(_)) => Err(refused(PairingErrorMessage::ParsingError)),
150            (Some(id), None) => self
151                .store
152                .node(*id)
153                .map(|n| n.id)
154                .ok_or_else(|| refused(PairingErrorMessage::NodeNotFound)),
155            (None, Some(alias)) => self
156                .store
157                .resolve_alias(alias)
158                .ok_or_else(|| refused(PairingErrorMessage::NodeNotFound)),
159            (None, None) => self
160                .store
161                .sole_node()
162                .ok_or_else(|| refused(PairingErrorMessage::NoNodeIdProvided)),
163        }
164    }
165
166    fn machine(
167        &self,
168        node: NodeId,
169    ) -> Result<Arc<tokio::sync::Mutex<PairingServer>>, ConnectError> {
170        let description = self
171            .store
172            .node(node)
173            .ok_or_else(|| refused(PairingErrorMessage::NodeNotFound))?;
174        let mut attempts = self
175            .attempts
176            .lock()
177            .map_err(|_| refused(PairingErrorMessage::Other))?;
178        Ok(attempts
179            .entry(node)
180            .or_insert_with(|| {
181                Arc::new(tokio::sync::Mutex::new(PairingServer::new(
182                    description,
183                    self.endpoint.clone(),
184                    self.binding.clone(),
185                )))
186            })
187            .clone())
188    }
189
190    /// `POST /v1/requestPairing`.
191    ///
192    /// Returns the body to send and the instant before which it must not be sent — the
193    /// caller sleeps until then, because the delay is the specification's brute-force
194    /// mitigation and a server that computes it and answers anyway has implemented a
195    /// comment.
196    ///
197    /// "One attempt per second per node" is enforced by the state machine rather than by
198    /// holding a lock across the wait: [`PairingServer`] remembers the attempt in flight
199    /// and when the last one finished, so a second request is
200    /// [`ConnectError::RateLimited`] whether or not the first has finished sleeping. The
201    /// `try_lock` here is only about two requests reaching the *same* machine in the same
202    /// instant.
203    pub fn request_pairing(
204        &self,
205        request: &PairingRequest,
206        server_nonce: &[u8],
207        attempt_id: PairingAttemptId,
208        now: Timestamp,
209    ) -> Result<(NodeId, Timestamp, PairingAccepted), ConnectError> {
210        let node = self.target(request)?;
211        let token = self
212            .store
213            .pairing_token(node, now)
214            .ok_or_else(|| refused(PairingErrorMessage::NoValidPairingTokenOnPairingServer))?;
215
216        let machine = self.machine(node)?;
217        // `try_lock`, not `lock`: a second attempt for this node must be told to come back
218        // rather than queued behind a fifteen-second budget.
219        let Ok(mut guard) = machine.try_lock() else {
220            return Err(ConnectError::RateLimited);
221        };
222        let (send_after, accepted) =
223            guard.request_pairing(request, &token, server_nonce, attempt_id, now)?;
224        Ok((node, send_after, accepted))
225    }
226
227    /// `POST /v1/requestConnectionDetails` (6A) — this endpoint is the communication
228    /// server.
229    pub async fn request_connection_details(
230        &self,
231        node: NodeId,
232        bearer: &str,
233        response: &str,
234        now: Timestamp,
235    ) -> Result<ConnectionDetails, ConnectError> {
236        let machine = self.machine(node)?;
237        let mut guard = machine.lock().await;
238        if !guard.authenticates(bearer) {
239            return Err(ConnectError::NotPaired);
240        }
241        guard.verify_client(response, now)?;
242        let communication = self
243            .communication
244            .as_ref()
245            .ok_or_else(|| refused(PairingErrorMessage::IncompatibleCommunicationProtocols))?;
246        let mut entropy = [0u8; 32];
247        super::fill_random(&mut entropy).map_err(|_| refused(PairingErrorMessage::Other))?;
248        let details = ConnectionDetails::new(
249            communication.initiate_session_url.clone(),
250            AccessToken::from_entropy(&entropy)?,
251        )
252        .with_ca_fingerprint(communication.ca.as_bytes());
253        guard.connection_details(details, now)
254    }
255
256    /// `POST /v1/postConnectionDetails` (6B) — the *client* is the communication server.
257    pub async fn post_connection_details(
258        &self,
259        node: NodeId,
260        bearer: &str,
261        response: &str,
262        details: ConnectionDetails,
263        now: Timestamp,
264    ) -> Result<(), ConnectError> {
265        let machine = self.machine(node)?;
266        let mut guard = machine.lock().await;
267        if !guard.authenticates(bearer) {
268            return Err(ConnectError::NotPaired);
269        }
270        guard.verify_client(response, now)?;
271        guard.accept_connection_details(details, now)
272    }
273
274    /// `POST /v1/finalizePairing`.
275    pub async fn finalize(
276        &self,
277        node: NodeId,
278        bearer: &str,
279        success: bool,
280        now: Timestamp,
281    ) -> Result<Finalized, ConnectError> {
282        let machine = self.machine(node)?;
283        let mut guard = machine.lock().await;
284        if !guard.authenticates(bearer) {
285            return Err(ConnectError::NotPaired);
286        }
287        let pairing = guard.finalize(crate::connect::proto::FinalizePairing { success }, now)?;
288        drop(guard);
289
290        let mut finalized = Finalized::default();
291        let Some(pairing) = pairing else {
292            return Ok(finalized);
293        };
294        let key = PairingKey {
295            local: pairing.local,
296            remote: pairing.remote.id,
297        };
298        // Re-pairing the same two nodes replaces the old pairing, and its session with it.
299        if self.store.paired(key).is_some() {
300            finalized.displaced.push(key);
301        }
302        let local_role = self.store.node(pairing.local).map(|n| n.role);
303        self.store.pair(PairedNode {
304            local: pairing.local,
305            remote: pairing.remote.clone(),
306            tokens: crate::connect::proto::TokenStore::new(pairing.details.access_token.clone()),
307            details: Some(pairing.details),
308            revoked: false,
309        });
310        finalized.paired = Some(key);
311        // `S2C §Pairing process`: "A CEM can be paired with multiple RMs at the same
312        // time. A RM can only be paired with one CEM at a time." So when the node that was
313        // just paired is a Resource Manager, whatever CEM it was paired with before is
314        // dropped — *after* the new pairing is stored, so a failure in between leaves the
315        // device reachable rather than orphaned.
316        if local_role == Some(crate::connect::proto::Role::Rm) {
317            for previous in self.store.pairings_of(pairing.local) {
318                if previous != key {
319                    crate::trace::event!(
320                        info,
321                        node = %pairing.local,
322                        unpaired = %previous.remote,
323                        "a Resource Manager pairs with one CEM at a time"
324                    );
325                    self.store.unpair(previous);
326                    finalized.displaced.push(previous);
327                }
328            }
329        }
330        Ok(finalized)
331    }
332}
333
334fn refused(message: PairingErrorMessage) -> ConnectError {
335    ConnectError::Refused(PairingRefused {
336        error_message: message,
337        additional_info: None,
338    })
339}