Skip to main content

s2_kit/connect/proto/
pairing.rs

1//! Pairing as a state machine that refuses to advance when a rule is broken.
2//!
3//! The exchange is a **two-way** challenge–response, and the two directions are not
4//! symmetrical in time: the client challenges first and the server answers in the same
5//! round trip, then the server's challenge is answered one request later. Getting that
6//! order wrong produces something that looks like authentication and proves nothing.
7//!
8//! ```text
9//!   HTTPS client                                      HTTPS server
10//!   ────────────                                      ────────────
11//!   1. generate C_c
12//!      POST /v1/requestPairing ───────────────────▶   2. R_c = HMAC(C_c, T ‖ binding)
13//!         clientNodeDescription, C_c,                    (rate-limited, ≥ 1 s delay)
14//!         versions, protocols, algorithms                generate C_s, attempt id
15//!   4. check R_c                ◀───────────────────3. pairingAttemptId, R_c, C_s,
16//!   5. R_s = HMAC(C_s, T ‖ binding)                     serverNodeDescription
17//!   6A. POST /v1/requestConnectionDetails ───────▶   7A. check R_s
18//!          R_s                  ◀───────────────────    ConnectionDetails
19//!    or
20//!   6B. POST /v1/postConnectionDetails ──────────▶   7B. check R_s
21//!          R_s, ConnectionDetails
22//!   8. POST /v1/finalizePairing {success} ───────▶   both sides store the pairing
23//! ```
24//!
25//! Which of 6A and 6B applies is decided by [`Deployment::communication_server`], not by
26//! preference: the side that will be the *communication* server is the side that has
27//! connection details to give.
28//!
29//! `R_c` proves the server holds the pairing token **and** that the TLS identity answering
30//! is the one the token was meant for — its leaf-certificate fingerprint in a LAN, its
31//! domain name otherwise. `R_s` proves the client holds the token. Steps 2 through 8 are
32//! authenticated by the `pairingAttemptId` the server issues, which is a bearer token.
33
34use alloc::collections::BTreeMap;
35use alloc::string::String;
36use alloc::vec::Vec;
37
38use serde::{Deserialize, Serialize};
39use zeroize::{Zeroize, ZeroizeOnDrop};
40
41use crate::types::{Duration, ProtocolVersion, Timestamp};
42
43use super::{
44    AccessToken, ChallengeResponse, CommunicationProtocol, ConnectError, Deployment,
45    EndpointDescription, HmacBinding, HmacHashingAlgorithm, NodeDescription, NodeId, NodeIdAlias,
46    PairingToken, Role,
47};
48
49/// How long a whole pairing attempt may take.
50///
51/// `S2C §Pairing`: "the pairing attempt must be finished within 15 seconds". Each side
52/// keeps its own budget, because each side can only see its own clock.
53pub const PAIRING_BUDGET: Duration = Duration::from_secs(15);
54
55/// The delay the server must insert before answering `requestPairing`.
56///
57/// `S2C §2. Calculate clientHmacChallengeResponse`: "To mitigate brute-force attacks, the
58/// server **must** enforce a mandatory delay of one second before sending its response to
59/// the client. For any given node at the server, pairing attempts **must** be handled
60/// sequentially, such that each second only one pairing attempt can be processed for a
61/// node."
62pub const MINIMUM_SERVER_DELAY: Duration = Duration::from_secs(1);
63
64// ---------------------------------------------------------------------------
65// Wire types — `s2-connect-pairing.yml`
66// ---------------------------------------------------------------------------
67
68/// The bearer token that authenticates steps 6 through 8 of one pairing attempt.
69///
70/// `S2C-OAS pairing/PairingAttemptId`: "a random string with a minimal length of 32
71/// characters… generated by a cryptographically secure pseudorandom number generator. The
72/// recommended method is to generate 24 random bytes and Base64 encode them."
73#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
74#[serde(transparent)]
75pub struct PairingAttemptId(String);
76
77impl PairingAttemptId {
78    /// The fewest characters the specification allows.
79    pub const MIN_LEN: usize = 32;
80
81    /// Wrap an identifier received from a peer.
82    #[must_use]
83    pub fn new(value: impl Into<String>) -> Self {
84        Self(value.into())
85    }
86
87    /// Generate one from the recommended 24 bytes of entropy.
88    pub fn from_entropy(bytes: &[u8]) -> Result<Self, ConnectError> {
89        // 24 bytes Base64-encode to exactly the 32 characters the minimum requires.
90        if bytes.len() < 24 {
91            return Err(ConnectError::WeakSecret {
92                got: bytes.len(),
93                need: 24,
94            });
95        }
96        Ok(Self(super::base64_encode(bytes)))
97    }
98
99    /// The string, which is what travels in `Authorization: Bearer …`.
100    #[must_use]
101    pub fn as_str(&self) -> &str {
102        &self.0
103    }
104
105    /// Whether a presented identifier is this one, compared in constant time.
106    #[must_use]
107    pub fn verify(&self, presented: &str) -> bool {
108        use subtle::ConstantTimeEq as _;
109        self.0.len() == presented.len() && bool::from(self.0.as_bytes().ct_eq(presented.as_bytes()))
110    }
111}
112
113impl core::fmt::Debug for PairingAttemptId {
114    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115        f.write_str("PairingAttemptId(<redacted>)")
116    }
117}
118
119/// The body of `POST /v1/requestPairing`.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "camelCase")]
122pub struct PairingRequest {
123    /// Who the client is.
124    pub client_node_description: NodeDescription,
125    /// Where the client's endpoint runs.
126    pub client_endpoint_description: EndpointDescription,
127    /// Which node at the endpoint, when the client knows its identifier.
128    ///
129    /// `S2C-OAS pairing/requestPairing`: "The (optional) properties nodeId and nodeIdAlias
130    /// may never be used at the same time." [`PairingClient`] cannot set both.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub node_id: Option<NodeId>,
133    /// Which node at the endpoint, when the client only has the alias from the code.
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub node_id_alias: Option<NodeIdAlias>,
136    /// How the client can carry S2 messages afterwards.
137    pub supported_communication_protocols: Vec<CommunicationProtocol>,
138    /// **S2 JSON** message versions — the same versions the `Handshake` negotiates,
139    /// spelled the way `S2C` spells them (E25).
140    pub supported_s2_message_versions: Vec<ProtocolVersion>,
141    /// The hash functions the client accepts; SHA-256 "**must** be present".
142    pub supported_hmac_hashing_algorithms: Vec<HmacHashingAlgorithm>,
143    /// `C_c`: a nonce of at least 32 bytes, Base64.
144    pub client_hmac_challenge: String,
145    /// Pair anyway, even with no S2 message version in common.
146    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
147    pub force_pairing: bool,
148}
149
150/// The `200` body of `requestPairing`.
151#[derive(Debug, Clone, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase")]
153pub struct PairingAccepted {
154    /// The bearer for the rest of the attempt.
155    pub pairing_attempt_id: PairingAttemptId,
156    /// Who the server is.
157    pub server_node_description: NodeDescription,
158    /// Where the server's endpoint runs.
159    pub server_endpoint_description: EndpointDescription,
160    /// The hash function the server chose from the client's list.
161    pub selected_hmac_hashing_algorithm: HmacHashingAlgorithm,
162    /// `R_c`: the server's answer to the client's challenge.
163    pub client_hmac_challenge_response: String,
164    /// `C_s`: the server's own nonce.
165    pub server_hmac_challenge: String,
166}
167
168/// Why a pairing was refused. `S2C-OAS pairing/PairingResponseErrorMessage`.
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
170#[non_exhaustive]
171pub enum PairingErrorMessage {
172    /// Two CEMs, or two RMs.
173    InvalidCombinationOfRoles,
174    /// No S2 JSON message version in common.
175    IncompatibleS2MessageVersions,
176    /// No hash function in common.
177    IncompatibleHmacHashingAlgorithms,
178    /// No transport in common.
179    IncompatibleCommunicationProtocols,
180    /// The alias or identifier names no node here.
181    NodeNotFound,
182    /// The endpoint hosts more than one node and the client named none.
183    NoNodeIdProvided,
184    /// No pairing token is active for that node.
185    NoValidPairingTokenOnPairingServer,
186    /// The body was not understood.
187    ParsingError,
188    /// Anything else.
189    Other,
190}
191
192/// The `400` body of `requestPairing`.
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194#[serde(rename_all = "camelCase")]
195pub struct PairingRefused {
196    /// Which of the enumerated reasons.
197    pub error_message: PairingErrorMessage,
198    /// Free text, for a log.
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub additional_info: Option<String>,
201}
202
203/// Where a communication client should connect, and with what.
204///
205/// `S2C-OAS pairing/ConnectionDetails`.
206#[derive(Debug, Clone, Serialize, Deserialize)]
207#[serde(rename_all = "camelCase")]
208pub struct ConnectionDetails {
209    /// The base URL of the session-initiation API.
210    pub initiate_session_url: String,
211    /// The first access token, which session initiation will rotate.
212    pub access_token: AccessToken,
213    /// Fingerprints of the **CA** certificate the communication server uses, by hashing
214    /// algorithm; `SHA256` is always present.
215    ///
216    /// Note that this is the *CA*, whereas the HMAC binding uses the **leaf**
217    /// (`S2C §Challenge response process`). They are different certificates and the
218    /// specification names them differently in the two places; conflating them produces a
219    /// pairing that verifies and a connection that does not.
220    ///
221    /// "Mandatory when the pairing client will become the communication server."
222    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
223    pub certificate_fingerprint: BTreeMap<String, String>,
224}
225
226impl ConnectionDetails {
227    /// The key `S2C` requires in [`certificate_fingerprint`](Self::certificate_fingerprint).
228    ///
229    /// (The OpenAPI's description spells it `"SHA265"`; the prose and every
230    /// implementation spell it `SHA256` — erratum E31.)
231    pub const SHA256: &'static str = "SHA256";
232
233    /// Details with no fingerprint: what a communication server hands out in 7A, where the
234    /// client pins the CA it saw during pairing instead.
235    #[must_use]
236    pub fn new(initiate_session_url: impl Into<String>, access_token: AccessToken) -> Self {
237        Self {
238            initiate_session_url: initiate_session_url.into(),
239            access_token,
240            certificate_fingerprint: BTreeMap::new(),
241        }
242    }
243
244    /// Add the SHA-256 fingerprint of the CA, written the way `S2C` encodes it: plain
245    /// lowercase hexadecimal.
246    ///
247    /// Mandatory in 6B ("when the pairing client will become the communication server"),
248    /// harmless in 7A.
249    #[must_use]
250    pub fn with_ca_fingerprint(mut self, sha256: &[u8; 32]) -> Self {
251        use core::fmt::Write as _;
252        let mut hex = String::with_capacity(64);
253        for b in sha256 {
254            let _ = write!(hex, "{b:02x}");
255        }
256        self.certificate_fingerprint
257            .insert(String::from(Self::SHA256), hex);
258        self
259    }
260
261    /// The SHA-256 fingerprint of the CA, if one was given and it is 32 bytes of hex —
262    /// either case, with or without colons.
263    #[must_use]
264    pub fn ca_fingerprint(&self) -> Option<[u8; 32]> {
265        let hex = self.certificate_fingerprint.get(Self::SHA256)?;
266        match super::HmacBinding::from_hex_fingerprint(hex).ok()? {
267            super::HmacBinding::LeafFingerprint(bytes) => bytes.try_into().ok(),
268            super::HmacBinding::DomainName(_) => None,
269        }
270    }
271}
272
273/// The body of `requestConnectionDetails` (6A).
274#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276pub struct ConnectionDetailsRequest {
277    /// `R_s`: the client's answer to the server's challenge.
278    pub server_hmac_challenge_response: String,
279}
280
281/// The body of `postConnectionDetails` (6B).
282#[derive(Debug, Clone, Serialize, Deserialize)]
283#[serde(rename_all = "camelCase")]
284pub struct ConnectionDetailsPost {
285    /// `R_s`: the client's answer to the server's challenge.
286    pub server_hmac_challenge_response: String,
287    /// What the client, as the future communication server, is offering.
288    pub connection_details: ConnectionDetails,
289}
290
291/// The body of `finalizePairing` (8).
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
293pub struct FinalizePairing {
294    /// Whether the client is satisfied and has stored the pairing.
295    pub success: bool,
296}
297
298/// A completed pairing, ready to be stored.
299#[derive(Debug, Clone)]
300pub struct Pairing {
301    /// This node.
302    pub local: NodeId,
303    /// The node paired with.
304    pub remote: NodeDescription,
305    /// The remote endpoint.
306    pub remote_endpoint: EndpointDescription,
307    /// Where to initiate sessions, and with what.
308    pub details: ConnectionDetails,
309    /// Which side will be the communication server.
310    pub communication_server: Role,
311    /// The S2 JSON message versions both sides offered, newest first — what a later
312    /// `Handshake` or `initiateSession` negotiates from.
313    pub s2_message_versions: Vec<ProtocolVersion>,
314}
315
316// ---------------------------------------------------------------------------
317// The client
318// ---------------------------------------------------------------------------
319
320/// How far a pairing attempt has got.
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322pub enum PairingStep {
323    /// Nothing has been sent.
324    Start,
325    /// `requestPairing` has been sent; the server's answer has not arrived.
326    AwaitingAcceptance,
327    /// `R_c` is verified; connection details have not been exchanged.
328    Authenticated,
329    /// Connection details are known; `finalizePairing` has not been sent.
330    DetailsExchanged,
331    /// The pairing is complete and may be stored.
332    Paired,
333    /// The attempt failed and may not be resumed.
334    Failed,
335}
336
337impl PairingStep {
338    const fn name(self) -> &'static str {
339        match self {
340            PairingStep::Start => "the start of pairing",
341            PairingStep::AwaitingAcceptance => "the server's acceptance",
342            PairingStep::Authenticated => "connection details",
343            PairingStep::DetailsExchanged => "finalization",
344            PairingStep::Paired => "a completed pairing",
345            PairingStep::Failed => "a failed pairing",
346        }
347    }
348}
349
350/// Which of steps 6A and 6B the client must take next.
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352pub enum NextStep {
353    /// 6A — the pairing server will be the communication server, so ask it for details.
354    RequestConnectionDetails,
355    /// 6B — the pairing *client* will be the communication server, so send details.
356    PostConnectionDetails,
357}
358
359/// The pairing client: the side that types in the code and makes the HTTPS requests.
360///
361/// ```
362/// # use s2_kit::connect::proto::*;
363/// # use s2_kit::types::Timestamp;
364/// # fn me() -> NodeDescription { NodeDescription {
365/// #   id: NodeId::parse("cem-1").unwrap(), brand: "Acme".into(), logo_url: None,
366/// #   kind: "CEM".into(), model_name: "Hub".into(), user_defined_name: None,
367/// #   role: Role::Cem } }
368/// let code = PairingCode::parse("evse7-A1b2C3", TokenKind::Static)?;
369/// let now = Timestamp::from_unix(1_700_000_000, 0);
370///
371/// let mut client = PairingClient::start(me(), EndpointDescription::default(), code, now);
372/// let body = client.request_pairing(&[0xA5; 32])?;
373/// assert_eq!(client.step(), PairingStep::AwaitingAcceptance);
374/// // The alias from the code names the node; `nodeId` stays unset, as the spec requires.
375/// assert!(body.node_id.is_none());
376/// assert_eq!(body.node_id_alias.as_ref().unwrap().0, "evse7");
377/// # Ok::<(), Box<dyn core::error::Error>>(())
378/// ```
379#[derive(Debug)]
380pub struct PairingClient {
381    local: NodeDescription,
382    local_endpoint: EndpointDescription,
383    code: super::PairingCode,
384    /// Known only once the server has presented a certificate, which is why it arrives
385    /// with [`PairingClient::accept`] rather than at the start.
386    binding: Option<HmacBinding>,
387    started: Timestamp,
388    step: PairingStep,
389    /// `C_c`, kept so the server's `R_c` can be checked against it in step 4.
390    challenge: Option<Vec<u8>>,
391    s2_message_versions: Vec<ProtocolVersion>,
392    protocols: Vec<CommunicationProtocol>,
393    force: bool,
394    accepted: Option<PairingAccepted>,
395    /// The server's handle on the attempt, remembered **before** anything about the
396    /// server's answer is judged.
397    ///
398    /// It is not ours: it names a slot the server is holding open for us, and the server's
399    /// rate limit is one attempt per node per second, so an attempt left in flight refuses
400    /// every retry with `503` for the whole fifteen-second budget. A client that decides
401    /// the server failed its challenge still has to give the slot back, and cannot if it
402    /// only kept the id on the success path.
403    attempt_id: Option<PairingAttemptId>,
404    details: Option<ConnectionDetails>,
405    communication_server: Option<Role>,
406}
407
408impl PairingClient {
409    /// Begin an attempt. The fifteen-second clock starts here.
410    #[must_use]
411    pub fn start(
412        local: NodeDescription,
413        local_endpoint: EndpointDescription,
414        code: super::PairingCode,
415        now: Timestamp,
416    ) -> Self {
417        Self {
418            local,
419            local_endpoint,
420            code,
421            binding: None,
422            started: now,
423            step: PairingStep::Start,
424            challenge: None,
425            // Both, newest first — the deployed ecosystem still negotiates the beta.
426            s2_message_versions: alloc::vec![
427                crate::types::WireProfile::V1_0_0.connect_version(),
428                crate::types::WireProfile::V0_0_2Beta.connect_version(),
429            ],
430            protocols: alloc::vec![CommunicationProtocol::WebSocket],
431            force: false,
432            accepted: None,
433            attempt_id: None,
434            details: None,
435            communication_server: None,
436        }
437    }
438
439    /// Offer a different set of S2 JSON message versions, newest first.
440    #[must_use]
441    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
442        self.s2_message_versions = versions;
443        self
444    }
445
446    /// Pair even with no S2 message version in common.
447    ///
448    /// The two nodes will not be able to talk until one of them is updated, which is
449    /// exactly what the flag is for: `S2C-OAS pairing` calls it out as something "could
450    /// later be solved through a software update".
451    #[must_use]
452    pub fn forcing(mut self) -> Self {
453        self.force = true;
454        self
455    }
456
457    /// How far the attempt has got.
458    #[must_use]
459    pub const fn step(&self) -> PairingStep {
460        self.step
461    }
462
463    /// The bearer for steps 6 through 8, once the server has issued one.
464    #[must_use]
465    pub fn attempt_id(&self) -> Option<&PairingAttemptId> {
466        self.attempt_id.as_ref()
467    }
468
469    /// Step 1: build `requestPairing` from 32 bytes of cryptographically secure
470    /// randomness.
471    ///
472    /// The randomness is a parameter because this layer has no business drawing it: a
473    /// test needs it pinned, and a driver knows where the system's entropy lives.
474    pub fn request_pairing(&mut self, challenge: &[u8]) -> Result<PairingRequest, ConnectError> {
475        self.expect(PairingStep::Start)?;
476        if challenge.len() < 32 {
477            self.step = PairingStep::Failed;
478            return Err(ConnectError::WeakSecret {
479                got: challenge.len(),
480                need: 32,
481            });
482        }
483        self.challenge = Some(challenge.to_vec());
484        self.step = PairingStep::AwaitingAcceptance;
485        Ok(PairingRequest {
486            client_node_description: self.local.clone(),
487            client_endpoint_description: self.local_endpoint.clone(),
488            // "may never be used at the same time" — the alias wins, because it is what
489            // the user typed.
490            node_id: None,
491            node_id_alias: self.code.alias.clone(),
492            supported_communication_protocols: self.protocols.clone(),
493            supported_s2_message_versions: self.s2_message_versions.clone(),
494            supported_hmac_hashing_algorithms: alloc::vec![HmacHashingAlgorithm::Sha256],
495            client_hmac_challenge: super::base64_encode(challenge),
496            force_pairing: self.force,
497        })
498    }
499
500    /// Step 4: check `clientHmacChallengeResponse`, and decide which of 6A and 6B follows.
501    ///
502    /// This is the moment the client learns it is talking to something that holds the same
503    /// pairing token *and* is the TLS identity the token was meant for. A man in the
504    /// middle who terminates TLS with his own certificate computes a different `R_c` and
505    /// is refused here.
506    ///
507    /// `S2C §4`: "in case of a local server, the TLS certificate fingerprint is part of
508    /// the challenge. So if the challenge succeeds, the certificate fingerprint is
509    /// correct, and the certificate can be trusted. The client **must** pin the
510    /// self-signed CA (root) certificate."
511    ///
512    /// `server_deployment` is how the server was reached — [`Deployment::Lan`] for a
513    /// `.local` endpoint, [`Deployment::Wan`] for one verified against the public PKI —
514    /// and is used only when the server's endpoint description omits its own. This
515    /// node's deployment is the one its own [`EndpointDescription`] states, LAN when it
516    /// states none.
517    pub fn accept(
518        &mut self,
519        accepted: PairingAccepted,
520        binding: HmacBinding,
521        server_deployment: Deployment,
522        now: Timestamp,
523    ) -> Result<NextStep, ConnectError> {
524        self.expect(PairingStep::AwaitingAcceptance)?;
525        // Before anything can refuse: whatever the verdict below, the server is holding an
526        // attempt for us and this is the only way to hand it back.
527        self.attempt_id = Some(accepted.pairing_attempt_id.clone());
528        self.within_budget(now)?;
529        self.binding = Some(binding);
530
531        if !self
532            .local
533            .role
534            .can_pair_with(accepted.server_node_description.role)
535        {
536            self.step = PairingStep::Failed;
537            return Err(ConnectError::SameRole(self.local.role));
538        }
539
540        let challenge = self.challenge.as_ref().ok_or(ConnectError::OutOfOrder {
541            got: "the server's acceptance",
542            expected: "the start of pairing",
543        })?;
544        let binding = self.binding.as_ref().ok_or(ConnectError::ChallengeFailed)?;
545        let expected = ChallengeResponse::compute(challenge, &self.code.token, binding)?;
546        if !expected.verify(&accepted.client_hmac_challenge_response) {
547            self.step = PairingStep::Failed;
548            return Err(ConnectError::ChallengeFailed);
549        }
550
551        // Which side is the communication server is decided by the two deployments and
552        // the two roles, never by preference.
553        let server_deployment = accepted
554            .server_endpoint_description
555            .deployment
556            .unwrap_or(server_deployment);
557        let local_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
558        let (cem, rm) = if self.local.role == Role::Cem {
559            (local_deployment, server_deployment)
560        } else {
561            (server_deployment, local_deployment)
562        };
563        let communication_server = Deployment::communication_server(cem, rm);
564        self.communication_server = Some(communication_server);
565
566        self.accepted = Some(accepted);
567        self.step = PairingStep::Authenticated;
568        Ok(if communication_server == self.local.role {
569            NextStep::PostConnectionDetails
570        } else {
571            NextStep::RequestConnectionDetails
572        })
573    }
574
575    /// Step 5: `R_s`, the answer to the server's challenge, Base64.
576    ///
577    /// Goes in the body of whichever of 6A and 6B [`Self::accept`] selected.
578    pub fn server_challenge_response(&self) -> Result<String, ConnectError> {
579        let accepted = self.accepted.as_ref().ok_or(ConnectError::OutOfOrder {
580            got: "a challenge response",
581            expected: "the server's acceptance",
582        })?;
583        let binding = self.binding.as_ref().ok_or(ConnectError::OutOfOrder {
584            got: "a challenge response",
585            expected: "the server's acceptance",
586        })?;
587        let challenge = super::base64_decode(&accepted.server_hmac_challenge)
588            .ok_or(ConnectError::ChallengeFailed)?;
589        Ok(ChallengeResponse::compute(&challenge, &self.code.token, binding)?.as_base64())
590    }
591
592    /// Step 6A: the body to send when the pairing server is the communication server.
593    pub fn request_connection_details(&self) -> Result<ConnectionDetailsRequest, ConnectError> {
594        Ok(ConnectionDetailsRequest {
595            server_hmac_challenge_response: self.server_challenge_response()?,
596        })
597    }
598
599    /// Step 6B: the body to send when *this* node is the communication server.
600    pub fn post_connection_details(
601        &mut self,
602        details: ConnectionDetails,
603        now: Timestamp,
604    ) -> Result<ConnectionDetailsPost, ConnectError> {
605        // "The key `SHA256` must always be provided": without it the pairing server, which
606        // is about to become our communication client, has nothing to pin.
607        if details.ca_fingerprint().is_none() {
608            return Err(ConnectError::OutOfOrder {
609                got: "connection details without a SHA256 CA fingerprint",
610                expected: "certificateFingerprint.SHA256",
611            });
612        }
613        let response = self.server_challenge_response()?;
614        self.connection_details(details.clone(), now)?;
615        Ok(ConnectionDetailsPost {
616            server_hmac_challenge_response: response,
617            connection_details: details,
618        })
619    }
620
621    /// Record the connection details, however they arrived.
622    pub fn connection_details(
623        &mut self,
624        details: ConnectionDetails,
625        now: Timestamp,
626    ) -> Result<(), ConnectError> {
627        self.expect(PairingStep::Authenticated)?;
628        self.within_budget(now)?;
629        self.details = Some(details);
630        self.step = PairingStep::DetailsExchanged;
631        Ok(())
632    }
633
634    /// Step 8: the body of `finalizePairing`, and the pairing to store.
635    pub fn finalize(&mut self, now: Timestamp) -> Result<(FinalizePairing, Pairing), ConnectError> {
636        self.expect(PairingStep::DetailsExchanged)?;
637        self.within_budget(now)?;
638        let accepted = self.accepted.take().ok_or(ConnectError::OutOfOrder {
639            got: "finalization",
640            expected: "the server's acceptance",
641        })?;
642        let details = self.details.take().ok_or(ConnectError::OutOfOrder {
643            got: "finalization",
644            expected: "connection details",
645        })?;
646        self.step = PairingStep::Paired;
647        Ok((
648            FinalizePairing { success: true },
649            Pairing {
650                local: self.local.id,
651                remote: accepted.server_node_description,
652                remote_endpoint: accepted.server_endpoint_description,
653                details,
654                communication_server: self.communication_server.unwrap_or(Role::Cem),
655                s2_message_versions: self.s2_message_versions.clone(),
656            },
657        ))
658    }
659
660    /// Give up, telling the server so. `S2C §8`: the client may finalize with
661    /// `success: false` "to let the server know it was not satisfied".
662    pub fn abandon(&mut self) -> FinalizePairing {
663        self.step = PairingStep::Failed;
664        FinalizePairing { success: false }
665    }
666
667    fn expect(&mut self, step: PairingStep) -> Result<(), ConnectError> {
668        if self.step == step {
669            return Ok(());
670        }
671        let got = self.step.name();
672        self.step = PairingStep::Failed;
673        Err(ConnectError::OutOfOrder {
674            got,
675            expected: step.name(),
676        })
677    }
678
679    fn within_budget(&mut self, now: Timestamp) -> Result<(), ConnectError> {
680        if now.saturating_duration_since(self.started) > PAIRING_BUDGET {
681            self.step = PairingStep::Failed;
682            return Err(ConnectError::Expired {
683                what: "pairing",
684                limit: PAIRING_BUDGET,
685            });
686        }
687        Ok(())
688    }
689}
690
691// ---------------------------------------------------------------------------
692// The server
693// ---------------------------------------------------------------------------
694
695/// The pairing server: the side that holds the token and answers.
696///
697/// It carries the two rules a request handler tends to lose — one attempt per node per
698/// second, and a response delayed by at least a second — as state rather than as
699/// discipline. `s2energy`'s S2 Connect layer has exactly these as an open issue.
700#[derive(Debug)]
701pub struct PairingServer {
702    local: NodeDescription,
703    local_endpoint: EndpointDescription,
704    binding: HmacBinding,
705    s2_message_versions: Vec<ProtocolVersion>,
706    protocols: Vec<CommunicationProtocol>,
707    /// The attempt currently in flight, if any.
708    attempt: Option<Attempt>,
709    /// When the last attempt for this node finished, for the rate limit.
710    last_finished: Option<Timestamp>,
711    /// The answer we owe the client, held until the mandatory second has elapsed.
712    pending: Option<(Timestamp, PairingAccepted)>,
713}
714
715#[derive(Debug)]
716struct Attempt {
717    id: PairingAttemptId,
718    started: Timestamp,
719    /// `C_s`, kept so the client's `R_s` can be checked against it.
720    expected_response: ChallengeResponse,
721    client: NodeDescription,
722    client_endpoint: EndpointDescription,
723    s2_message_versions: Vec<ProtocolVersion>,
724    details: Option<ConnectionDetails>,
725    verified: bool,
726    /// Whether the *client* will be the communication server — 6B — rather than this
727    /// node — 6A. Decided from the two deployments when the attempt starts, so a client
728    /// that takes the other branch is refused rather than obeyed.
729    client_is_communication_server: bool,
730}
731
732impl PairingServer {
733    /// A server for one node, bound to the identity clients will verify against.
734    #[must_use]
735    pub fn new(
736        local: NodeDescription,
737        local_endpoint: EndpointDescription,
738        binding: HmacBinding,
739    ) -> Self {
740        Self {
741            local,
742            local_endpoint,
743            binding,
744            s2_message_versions: alloc::vec![
745                crate::types::WireProfile::V1_0_0.connect_version(),
746                crate::types::WireProfile::V0_0_2Beta.connect_version(),
747            ],
748            protocols: alloc::vec![CommunicationProtocol::WebSocket],
749            attempt: None,
750            last_finished: None,
751            pending: None,
752        }
753    }
754
755    /// Offer a different set of S2 JSON message versions, newest first.
756    #[must_use]
757    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
758        self.s2_message_versions = versions;
759        self
760    }
761
762    /// Steps 2 and 3: handle `requestPairing`.
763    ///
764    /// Returns the `200` body **and the instant before which it may not be sent**. The
765    /// delay is not advisory: with a four-character token there are 14.7 million
766    /// possibilities, and one guess per second is the difference between a brute force
767    /// taking months and taking an afternoon.
768    ///
769    /// A refusal consumes the rate-limit slot just as a success does, which is what makes
770    /// the limit worth anything.
771    ///
772    /// # Errors
773    ///
774    /// [`ConnectError::RateLimited`] should become `503`; a [`PairingRefused`] carried in
775    /// [`ConnectError::Refused`] should become `400` with that body.
776    pub fn request_pairing(
777        &mut self,
778        request: &PairingRequest,
779        token: &PairingToken,
780        server_challenge: &[u8],
781        attempt_id: PairingAttemptId,
782        now: Timestamp,
783    ) -> Result<(Timestamp, PairingAccepted), ConnectError> {
784        if let Some(attempt) = &self.attempt
785            && now.saturating_duration_since(attempt.started) <= PAIRING_BUDGET
786        {
787            return Err(ConnectError::RateLimited);
788        }
789        if let Some(finished) = self.last_finished
790            && now.saturating_duration_since(finished) < MINIMUM_SERVER_DELAY
791        {
792            return Err(ConnectError::RateLimited);
793        }
794
795        let result = self.answer(request, token, server_challenge, attempt_id, now);
796        if result.is_err() {
797            self.last_finished = Some(now);
798            self.attempt = None;
799        }
800        result
801    }
802
803    fn answer(
804        &mut self,
805        request: &PairingRequest,
806        token: &PairingToken,
807        server_challenge: &[u8],
808        attempt_id: PairingAttemptId,
809        now: Timestamp,
810    ) -> Result<(Timestamp, PairingAccepted), ConnectError> {
811        use PairingErrorMessage as E;
812
813        // The checks in the order `S2C §1. Request pairing` tabulates them.
814        if !self
815            .local
816            .role
817            .can_pair_with(request.client_node_description.role)
818        {
819            return Err(refused(E::InvalidCombinationOfRoles));
820        }
821        if !request
822            .supported_hmac_hashing_algorithms
823            .contains(&HmacHashingAlgorithm::Sha256)
824        {
825            return Err(refused(E::IncompatibleHmacHashingAlgorithms));
826        }
827        if !request
828            .supported_communication_protocols
829            .iter()
830            .any(|p| self.protocols.contains(p))
831        {
832            return Err(refused(E::IncompatibleCommunicationProtocols));
833        }
834        // A version mismatch is refusable, but `forcePairing` overrides it: the nodes
835        // pair now and talk after a software update.
836        let common = request
837            .supported_s2_message_versions
838            .iter()
839            .filter(|v| self.s2_message_versions.iter().any(|ours| ours.matches(v)))
840            .cloned()
841            .collect::<Vec<_>>();
842        if common.is_empty() && !request.force_pairing {
843            return Err(refused(E::IncompatibleS2MessageVersions));
844        }
845        if request.node_id.is_some() && request.node_id_alias.is_some() {
846            return Err(refused(E::ParsingError));
847        }
848
849        let client_challenge = super::base64_decode(&request.client_hmac_challenge)
850            .ok_or_else(|| refused(E::ParsingError))?;
851        // `R_c`: prove to the client that we hold the token and are the identity it
852        // reached.
853        let client_response = ChallengeResponse::compute(&client_challenge, token, &self.binding)?;
854        // `C_s` / the response we will expect back in step 6.
855        let expected_response = ChallengeResponse::compute(server_challenge, token, &self.binding)?;
856
857        let accepted = PairingAccepted {
858            pairing_attempt_id: attempt_id.clone(),
859            server_node_description: self.local.clone(),
860            server_endpoint_description: self.local_endpoint.clone(),
861            selected_hmac_hashing_algorithm: HmacHashingAlgorithm::Sha256,
862            client_hmac_challenge_response: client_response.as_base64(),
863            server_hmac_challenge: super::base64_encode(server_challenge),
864        };
865
866        let client_deployment = request
867            .client_endpoint_description
868            .deployment
869            .unwrap_or(Deployment::Lan);
870        let own_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
871        let (cem, rm) = if self.local.role == Role::Cem {
872            (own_deployment, client_deployment)
873        } else {
874            (client_deployment, own_deployment)
875        };
876        let client_is_communication_server =
877            Deployment::communication_server(cem, rm) == request.client_node_description.role;
878
879        self.attempt = Some(Attempt {
880            id: attempt_id,
881            started: now,
882            expected_response,
883            client: request.client_node_description.clone(),
884            client_endpoint: request.client_endpoint_description.clone(),
885            s2_message_versions: common,
886            details: None,
887            verified: false,
888            client_is_communication_server,
889        });
890        let send_after = now.checked_add(MINIMUM_SERVER_DELAY).unwrap_or(now);
891        self.pending = Some((send_after, accepted.clone()));
892        Ok((send_after, accepted))
893    }
894
895    /// When the driver should next do something: the moment the delayed answer becomes
896    /// sendable, or the moment the attempt's budget runs out.
897    #[must_use]
898    pub fn poll_timeout(&self) -> Option<Timestamp> {
899        self.pending.as_ref().map(|(at, _)| *at).or_else(|| {
900            self.attempt
901                .as_ref()
902                .map(|a| a.started.checked_add(PAIRING_BUDGET).unwrap_or(a.started))
903        })
904    }
905
906    /// Take the delayed answer, if the mandatory second has elapsed.
907    ///
908    /// Returning `None` early is the point: a driver that loops on this cannot answer
909    /// sooner than the specification allows, however tempting it is to.
910    pub fn poll_response(&mut self, now: Timestamp) -> Option<PairingAccepted> {
911        let (at, _) = self.pending.as_ref()?;
912        if now < *at {
913            return None;
914        }
915        self.pending.take().map(|(_, accepted)| accepted)
916    }
917
918    /// Authenticate a step-6-or-later request by its bearer.
919    ///
920    /// A `false` here is a `401`, and `S2C-OAS` says the client "may restart the pairing
921    /// process by calling /requestPairing again" — so it must not fail the attempt.
922    #[must_use]
923    pub fn authenticates(&self, bearer: &str) -> bool {
924        self.attempt.as_ref().is_some_and(|a| a.id.verify(bearer))
925    }
926
927    /// Steps 7A and 7B: check `serverHmacChallengeResponse`.
928    ///
929    /// A `false` here is a `403`: `S2C-OAS` — "The PairingAttempt has failed and cannot
930    /// proceed", so the attempt is dropped rather than merely refused.
931    pub fn verify_client(&mut self, response: &str, now: Timestamp) -> Result<(), ConnectError> {
932        let Some(attempt) = self.attempt.as_mut() else {
933            return Err(ConnectError::OutOfOrder {
934                got: "a challenge response",
935                expected: "the start of pairing",
936            });
937        };
938        if now.saturating_duration_since(attempt.started) > PAIRING_BUDGET {
939            self.fail(now);
940            return Err(ConnectError::Expired {
941                what: "pairing",
942                limit: PAIRING_BUDGET,
943            });
944        }
945        if !attempt.expected_response.verify(response) {
946            self.fail(now);
947            return Err(ConnectError::ChallengeFailed);
948        }
949        attempt.verified = true;
950        Ok(())
951    }
952
953    /// Whether this attempt's client is to be the communication server (6B), if an
954    /// attempt is in flight.
955    #[must_use]
956    pub fn client_is_communication_server(&self) -> Option<bool> {
957        self.attempt
958            .as_ref()
959            .map(|a| a.client_is_communication_server)
960    }
961
962    /// Step 7A: what to answer `requestConnectionDetails` with, once verified.
963    ///
964    /// Refused — and the attempt failed — when the client is the one that should be the
965    /// communication server: `S2C §Invalid interactions`, "If the server receives a wrong
966    /// HTTPS request (e.g. `/postConnectionDetails` while it was expecting
967    /// `/requestConnectionDetails`) … it **must** respond with a status 400 and consider
968    /// the pairing attempt as failed."
969    pub fn connection_details(
970        &mut self,
971        details: ConnectionDetails,
972        now: Timestamp,
973    ) -> Result<ConnectionDetails, ConnectError> {
974        self.record_details(details, false, now)
975    }
976
977    /// Step 7B: record the details the client posted, once verified.
978    ///
979    /// Refused — and the attempt failed — when this node should be the communication
980    /// server, or when the details carry no `SHA256` CA fingerprint to pin.
981    pub fn accept_connection_details(
982        &mut self,
983        details: ConnectionDetails,
984        now: Timestamp,
985    ) -> Result<(), ConnectError> {
986        if details.ca_fingerprint().is_none() {
987            self.fail(now);
988            return Err(refused(PairingErrorMessage::ParsingError));
989        }
990        self.record_details(details, true, now).map(|_| ())
991    }
992
993    fn record_details(
994        &mut self,
995        details: ConnectionDetails,
996        posted_by_client: bool,
997        now: Timestamp,
998    ) -> Result<ConnectionDetails, ConnectError> {
999        let (verified, client_is_server) = self
1000            .attempt
1001            .as_ref()
1002            .map(|a| (a.verified, a.client_is_communication_server))
1003            .ok_or(ConnectError::OutOfOrder {
1004                got: "connection details",
1005                expected: "the start of pairing",
1006            })?;
1007        if !verified {
1008            return Err(ConnectError::ChallengeFailed);
1009        }
1010        if client_is_server != posted_by_client {
1011            let (got, expected) = if posted_by_client {
1012                ("postConnectionDetails", "requestConnectionDetails")
1013            } else {
1014                ("requestConnectionDetails", "postConnectionDetails")
1015            };
1016            self.fail(now);
1017            return Err(ConnectError::OutOfOrder { got, expected });
1018        }
1019        if let Some(attempt) = self.attempt.as_mut() {
1020            attempt.details = Some(details.clone());
1021        }
1022        Ok(details)
1023    }
1024
1025    /// Step 8: handle `finalizePairing`, yielding the pairing to store.
1026    ///
1027    /// A `success: false` is not an error — it is the client saying it could not proceed —
1028    /// but it yields no pairing.
1029    pub fn finalize(
1030        &mut self,
1031        body: FinalizePairing,
1032        now: Timestamp,
1033    ) -> Result<Option<Pairing>, ConnectError> {
1034        let Some(attempt) = self.attempt.take() else {
1035            return Err(ConnectError::OutOfOrder {
1036                got: "finalization",
1037                expected: "the start of pairing",
1038            });
1039        };
1040        self.last_finished = Some(now);
1041        self.pending = None;
1042
1043        if now.saturating_duration_since(attempt.started) > PAIRING_BUDGET {
1044            return Err(ConnectError::Expired {
1045                what: "pairing",
1046                limit: PAIRING_BUDGET,
1047            });
1048        }
1049        if !body.success {
1050            return Ok(None);
1051        }
1052        if !attempt.verified {
1053            return Err(ConnectError::ChallengeFailed);
1054        }
1055        let details = attempt.details.ok_or(ConnectError::OutOfOrder {
1056            got: "finalization",
1057            expected: "connection details",
1058        })?;
1059        let client_deployment = attempt
1060            .client_endpoint
1061            .deployment
1062            .unwrap_or(Deployment::Lan);
1063        let own_deployment = self.local_endpoint.deployment.unwrap_or(Deployment::Lan);
1064        let (cem, rm) = if self.local.role == Role::Cem {
1065            (own_deployment, client_deployment)
1066        } else {
1067            (client_deployment, own_deployment)
1068        };
1069        Ok(Some(Pairing {
1070            local: self.local.id,
1071            remote: attempt.client,
1072            remote_endpoint: attempt.client_endpoint,
1073            details,
1074            communication_server: Deployment::communication_server(cem, rm),
1075            s2_message_versions: attempt.s2_message_versions,
1076        }))
1077    }
1078
1079    fn fail(&mut self, now: Timestamp) {
1080        self.attempt = None;
1081        self.pending = None;
1082        self.last_finished = Some(now);
1083    }
1084}
1085
1086fn refused(message: PairingErrorMessage) -> ConnectError {
1087    ConnectError::Refused(PairingRefused {
1088        error_message: message,
1089        additional_info: None,
1090    })
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095    use super::*;
1096    use crate::connect::proto::{PairingCode, TokenKind};
1097    // Explicit because the crate is `no_std`: without `std` there is no prelude to take
1098    // `.to_string()` from, and `cargo test --lib --no-default-features` is a CI job.
1099    use alloc::string::ToString;
1100
1101    const CLIENT_CHALLENGE: [u8; 32] = [0xA5; 32];
1102    const SERVER_CHALLENGE: [u8; 32] = [0x5A; 32];
1103    const ATTEMPT: [u8; 24] = [0x33; 24];
1104
1105    fn binding() -> HmacBinding {
1106        HmacBinding::DomainName("pairing.example.com".to_string())
1107    }
1108
1109    fn code() -> PairingCode {
1110        PairingCode::parse("evse7-A1b2C3", TokenKind::Static).expect("a legal code")
1111    }
1112
1113    fn node(id: &str, role: Role) -> NodeDescription {
1114        NodeDescription {
1115            id: NodeId::parse(id).expect("a legal id"),
1116            brand: "Acme".to_string(),
1117            logo_url: None,
1118            kind: if role == Role::Cem { "CEM" } else { "EVSE" }.to_string(),
1119            model_name: "Charger 9000".to_string(),
1120            user_defined_name: None,
1121            role,
1122        }
1123    }
1124
1125    fn endpoint(deployment: Deployment) -> EndpointDescription {
1126        EndpointDescription {
1127            name: Some("Test endpoint".to_string()),
1128            logo_url: None,
1129            deployment: Some(deployment),
1130        }
1131    }
1132
1133    fn details() -> ConnectionDetails {
1134        ConnectionDetails::new(
1135            "https://pairing.example.com/",
1136            AccessToken::from_entropy(&[1u8; 32]).expect("32 bytes"),
1137        )
1138        .with_ca_fingerprint(&[0xCA; 32])
1139    }
1140
1141    fn t(secs: i64) -> Timestamp {
1142        Timestamp::from_unix(1_700_000_000 + secs, 0)
1143    }
1144
1145    fn attempt_id() -> PairingAttemptId {
1146        PairingAttemptId::from_entropy(&ATTEMPT).expect("24 bytes")
1147    }
1148
1149    /// Both sides, driven end to end the way a real pairing runs: a WAN CEM as the
1150    /// pairing client, a LAN RM as the pairing server, so the RM is the pairing server
1151    /// and the CEM the communication server (6B).
1152    struct Run {
1153        client: PairingClient,
1154        server: PairingServer,
1155    }
1156
1157    fn setup(
1158        client_role: Role,
1159        client_deployment: Deployment,
1160        server_deployment: Deployment,
1161    ) -> Run {
1162        Run {
1163            client: PairingClient::start(
1164                node("cem-1", client_role),
1165                endpoint(client_deployment),
1166                code(),
1167                t(0),
1168            ),
1169            server: PairingServer::new(
1170                node("rm-1", client_role.other()),
1171                endpoint(server_deployment),
1172                binding(),
1173            ),
1174        }
1175    }
1176
1177    #[test]
1178    fn a_pairing_runs_to_completion_and_both_sides_agree() {
1179        let Run {
1180            mut client,
1181            mut server,
1182        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1183
1184        // 1–3.
1185        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1186        let (send_after, accepted) = server
1187            .request_pairing(
1188                &request,
1189                &code().token,
1190                &SERVER_CHALLENGE,
1191                attempt_id(),
1192                t(0),
1193            )
1194            .unwrap();
1195        assert_eq!(send_after, t(1));
1196        let accepted = {
1197            assert!(server.poll_response(t(0)).is_none());
1198            server.poll_response(t(1)).unwrap_or(accepted)
1199        };
1200
1201        // 4–5. Both LAN, so the CEM is the communication server: the client posts.
1202        let next = client
1203            .accept(accepted, binding(), Deployment::Lan, t(1))
1204            .unwrap();
1205        assert_eq!(next, NextStep::PostConnectionDetails);
1206
1207        // 6B–7B.
1208        let post = client.post_connection_details(details(), t(1)).unwrap();
1209        assert!(server.authenticates(client.attempt_id().unwrap().as_str()));
1210        server
1211            .verify_client(&post.server_hmac_challenge_response, t(1))
1212            .unwrap();
1213        server
1214            .accept_connection_details(post.connection_details, t(1))
1215            .unwrap();
1216
1217        // 8.
1218        let (body, mine) = client.finalize(t(2)).unwrap();
1219        assert!(body.success);
1220        let theirs = server.finalize(body, t(2)).unwrap().expect("a pairing");
1221
1222        assert_eq!(client.step(), PairingStep::Paired);
1223        assert_eq!(mine.remote.id, theirs.local);
1224        assert_eq!(theirs.remote.id, mine.local);
1225        assert_eq!(mine.communication_server, Role::Cem);
1226        assert_eq!(theirs.communication_server, Role::Cem);
1227    }
1228
1229    #[test]
1230    fn a_wan_pairing_server_supplies_the_details_instead() {
1231        // The RM is in the WAN, so it is the communication server and the client asks.
1232        let Run {
1233            mut client,
1234            mut server,
1235        } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);
1236
1237        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1238        let (_, accepted) = server
1239            .request_pairing(
1240                &request,
1241                &code().token,
1242                &SERVER_CHALLENGE,
1243                attempt_id(),
1244                t(0),
1245            )
1246            .unwrap();
1247        let next = client
1248            .accept(accepted, binding(), Deployment::Lan, t(1))
1249            .unwrap();
1250        assert_eq!(next, NextStep::RequestConnectionDetails);
1251
1252        let ask = client.request_connection_details().unwrap();
1253        server
1254            .verify_client(&ask.server_hmac_challenge_response, t(1))
1255            .unwrap();
1256        let given = server.connection_details(details(), t(1)).unwrap();
1257        client.connection_details(given, t(1)).unwrap();
1258        let (body, pairing) = client.finalize(t(2)).unwrap();
1259        assert_eq!(pairing.communication_server, Role::Rm);
1260        assert!(server.finalize(body, t(2)).unwrap().is_some());
1261    }
1262
1263    #[test]
1264    fn a_server_that_omits_its_deployment_is_taken_to_be_where_it_was_reached() {
1265        // A LAN CEM pairing with a WAN RM that leaves `deployment` out. Defaulting the
1266        // absent value to LAN made the CEM the communication server and the client posted
1267        // details the server never asked for — the WAN node is the server
1268        // (`S2C §Mapping`), and the client reached it as one.
1269        let outcome = |reached: Deployment| {
1270            let Run {
1271                mut client,
1272                mut server,
1273            } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);
1274            let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1275            let (_, mut accepted) = server
1276                .request_pairing(
1277                    &request,
1278                    &code().token,
1279                    &SERVER_CHALLENGE,
1280                    attempt_id(),
1281                    t(0),
1282                )
1283                .unwrap();
1284            accepted.server_endpoint_description.deployment = None;
1285            client.accept(accepted, binding(), reached, t(1)).unwrap()
1286        };
1287        assert_eq!(outcome(Deployment::Wan), NextStep::RequestConnectionDetails);
1288        assert_eq!(outcome(Deployment::Lan), NextStep::PostConnectionDetails);
1289    }
1290
1291    #[test]
1292    fn the_wrong_branch_of_step_six_fails_the_attempt() {
1293        // `S2C §Invalid interactions`: "/postConnectionDetails while it was expecting
1294        // /requestConnectionDetails … must respond with a status 400 and consider the
1295        // pairing attempt as failed." Here the server is the WAN RM, so 6A is expected and
1296        // a client that posts its own details instead is refused, and the attempt is over.
1297        let Run {
1298            mut client,
1299            mut server,
1300        } = setup(Role::Cem, Deployment::Lan, Deployment::Wan);
1301        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1302        let (_, accepted) = server
1303            .request_pairing(
1304                &request,
1305                &code().token,
1306                &SERVER_CHALLENGE,
1307                attempt_id(),
1308                t(0),
1309            )
1310            .unwrap();
1311        client
1312            .accept(accepted, binding(), Deployment::Lan, t(1))
1313            .unwrap();
1314        let ask = client.request_connection_details().unwrap();
1315        server
1316            .verify_client(&ask.server_hmac_challenge_response, t(1))
1317            .unwrap();
1318        assert_eq!(server.client_is_communication_server(), Some(false));
1319        assert!(matches!(
1320            server.accept_connection_details(details(), t(1)),
1321            Err(ConnectError::OutOfOrder { .. })
1322        ));
1323        assert!(
1324            server.client_is_communication_server().is_none(),
1325            "the attempt is failed, not merely refused"
1326        );
1327    }
1328
1329    #[test]
1330    fn posted_details_without_a_ca_fingerprint_are_refused() {
1331        // "The key `SHA256` must always be provided": without it the pairing server has
1332        // nothing to pin when it becomes the communication client.
1333        let bare = ConnectionDetails::new("https://cem.local/", AccessToken::new("x".repeat(43)));
1334        assert!(bare.ca_fingerprint().is_none());
1335        let pinned = bare.clone().with_ca_fingerprint(&[0xAB; 32]);
1336        assert_eq!(pinned.ca_fingerprint(), Some([0xAB; 32]));
1337        assert_eq!(
1338            pinned
1339                .certificate_fingerprint
1340                .get("SHA256")
1341                .map(String::as_str),
1342            Some("ab".repeat(32).as_str()),
1343            "plain lowercase hexadecimal on the wire"
1344        );
1345        // Colons and capitals are still read.
1346        let mut colons = bare;
1347        colons
1348            .certificate_fingerprint
1349            .insert("SHA256".to_string(), alloc::vec!["AB"; 32].join(":"));
1350        assert_eq!(colons.ca_fingerprint(), Some([0xAB; 32]));
1351    }
1352
1353    #[test]
1354    fn the_response_may_not_be_sent_before_the_mandatory_second() {
1355        let Run {
1356            mut client,
1357            mut server,
1358        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1359        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1360        server
1361            .request_pairing(
1362                &request,
1363                &code().token,
1364                &SERVER_CHALLENGE,
1365                attempt_id(),
1366                t(0),
1367            )
1368            .unwrap();
1369
1370        assert_eq!(server.poll_timeout(), Some(t(1)));
1371        assert!(server.poll_response(t(0)).is_none());
1372        assert!(
1373            server
1374                .poll_response(Timestamp::from_unix(1_700_000_000, 999_000_000))
1375                .is_none()
1376        );
1377        assert!(server.poll_response(t(1)).is_some());
1378        // And it is delivered once.
1379        assert!(server.poll_response(t(2)).is_none());
1380    }
1381
1382    #[test]
1383    fn a_second_attempt_for_the_same_node_is_refused() {
1384        let Run {
1385            mut client,
1386            mut server,
1387        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1388        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1389        server
1390            .request_pairing(
1391                &request,
1392                &code().token,
1393                &SERVER_CHALLENGE,
1394                attempt_id(),
1395                t(0),
1396            )
1397            .unwrap();
1398
1399        assert!(matches!(
1400            server.request_pairing(
1401                &request,
1402                &code().token,
1403                &SERVER_CHALLENGE,
1404                attempt_id(),
1405                t(1)
1406            ),
1407            Err(ConnectError::RateLimited)
1408        ));
1409        // Once its budget has run out, the slot frees.
1410        assert!(
1411            server
1412                .request_pairing(
1413                    &request,
1414                    &code().token,
1415                    &SERVER_CHALLENGE,
1416                    attempt_id(),
1417                    t(16)
1418                )
1419                .is_ok()
1420        );
1421    }
1422
1423    #[test]
1424    fn a_wrong_token_costs_the_attacker_a_second_too() {
1425        let Run {
1426            mut client,
1427            mut server,
1428        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1429        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1430
1431        // The server answers with *its* token; a client holding the wrong one fails in
1432        // step 4, not here — so the interesting failure is the reverse direction.
1433        let wrong = PairingToken::parse("Z9y8X7", TokenKind::Static).unwrap();
1434        let (_, accepted) = server
1435            .request_pairing(&request, &wrong, &SERVER_CHALLENGE, attempt_id(), t(0))
1436            .unwrap();
1437        assert!(matches!(
1438            client.accept(accepted, binding(), Deployment::Lan, t(1)),
1439            Err(ConnectError::ChallengeFailed)
1440        ));
1441
1442        // And a client that guesses wrong at step 6 kills the attempt outright.
1443        let Run {
1444            mut client,
1445            mut server,
1446        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1447        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1448        let (_, accepted) = server
1449            .request_pairing(
1450                &request,
1451                &code().token,
1452                &SERVER_CHALLENGE,
1453                attempt_id(),
1454                t(0),
1455            )
1456            .unwrap();
1457        client
1458            .accept(accepted, binding(), Deployment::Lan, t(1))
1459            .unwrap();
1460        let forged = ChallengeResponse::compute(&SERVER_CHALLENGE, &wrong, &binding())
1461            .unwrap()
1462            .as_base64();
1463        assert!(matches!(
1464            server.verify_client(&forged, t(1)),
1465            Err(ConnectError::ChallengeFailed)
1466        ));
1467        // "The PairingAttempt has failed and cannot proceed."
1468        assert!(!server.authenticates(attempt_id().as_str()));
1469    }
1470
1471    #[test]
1472    fn a_man_in_the_middle_cannot_relay_the_exchange() {
1473        // The attacker terminates TLS with his own certificate, so his binding differs.
1474        let attacker = HmacBinding::DomainName("pairing.example.com.evil.test".to_string());
1475        let mut client = PairingClient::start(
1476            node("cem-1", Role::Cem),
1477            endpoint(Deployment::Lan),
1478            code(),
1479            t(0),
1480        );
1481        let mut server =
1482            PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), attacker);
1483
1484        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1485        // He can relay the request and compute a response — but under his own name.
1486        let (_, accepted) = server
1487            .request_pairing(
1488                &request,
1489                &code().token,
1490                &SERVER_CHALLENGE,
1491                attempt_id(),
1492                t(0),
1493            )
1494            .unwrap();
1495        // The client, which binds to the name it *believes* it reached, refuses it.
1496        assert!(matches!(
1497            client.accept(accepted, binding(), Deployment::Lan, t(1)),
1498            Err(ConnectError::ChallengeFailed)
1499        ));
1500        assert_eq!(client.step(), PairingStep::Failed);
1501    }
1502
1503    #[test]
1504    fn the_fifteen_second_budget_is_enforced_on_both_sides() {
1505        let Run {
1506            mut client,
1507            mut server,
1508        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1509        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1510        let (_, accepted) = server
1511            .request_pairing(
1512                &request,
1513                &code().token,
1514                &SERVER_CHALLENGE,
1515                attempt_id(),
1516                t(0),
1517            )
1518            .unwrap();
1519
1520        assert!(matches!(
1521            client.accept(accepted, binding(), Deployment::Lan, t(16)),
1522            Err(ConnectError::Expired { .. })
1523        ));
1524        assert!(matches!(
1525            server.verify_client("anything", t(16)),
1526            Err(ConnectError::Expired { .. })
1527        ));
1528    }
1529
1530    #[test]
1531    fn the_steps_cannot_be_taken_out_of_order() {
1532        let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1533        assert!(matches!(
1534            client.finalize(t(0)),
1535            Err(ConnectError::OutOfOrder { .. })
1536        ));
1537        // And the attempt is now dead, not merely unhappy.
1538        assert_eq!(client.step(), PairingStep::Failed);
1539        assert!(client.request_pairing(&CLIENT_CHALLENGE).is_err());
1540    }
1541
1542    #[test]
1543    fn two_nodes_of_the_same_role_are_refused_by_both_sides() {
1544        // The server refuses in step 1, with the enumerated reason.
1545        let mut client = PairingClient::start(
1546            node("cem-1", Role::Cem),
1547            endpoint(Deployment::Lan),
1548            code(),
1549            t(0),
1550        );
1551        let mut server = PairingServer::new(
1552            node("cem-2", Role::Cem),
1553            endpoint(Deployment::Lan),
1554            binding(),
1555        );
1556        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1557        let err = server
1558            .request_pairing(
1559                &request,
1560                &code().token,
1561                &SERVER_CHALLENGE,
1562                attempt_id(),
1563                t(0),
1564            )
1565            .unwrap_err();
1566        assert!(matches!(
1567            err,
1568            ConnectError::Refused(PairingRefused {
1569                error_message: PairingErrorMessage::InvalidCombinationOfRoles,
1570                ..
1571            })
1572        ));
1573    }
1574
1575    #[test]
1576    fn incompatible_versions_are_refused_unless_forced() {
1577        let mut client = PairingClient::start(
1578            node("cem-1", Role::Cem),
1579            endpoint(Deployment::Lan),
1580            code(),
1581            t(0),
1582        )
1583        .with_s2_message_versions(alloc::vec![crate::types::ProtocolVersion::new("9.9.9")]);
1584        let mut server =
1585            PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), binding());
1586        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1587        assert!(matches!(
1588            server.request_pairing(
1589                &request,
1590                &code().token,
1591                &SERVER_CHALLENGE,
1592                attempt_id(),
1593                t(0)
1594            ),
1595            Err(ConnectError::Refused(PairingRefused {
1596                error_message: PairingErrorMessage::IncompatibleS2MessageVersions,
1597                ..
1598            }))
1599        ));
1600
1601        // Forced, it pairs anyway — the nodes cannot talk until one is updated, which is
1602        // what the flag is for.
1603        let mut client = PairingClient::start(
1604            node("cem-1", Role::Cem),
1605            endpoint(Deployment::Lan),
1606            code(),
1607            t(0),
1608        )
1609        .with_s2_message_versions(alloc::vec![crate::types::ProtocolVersion::new("9.9.9")])
1610        .forcing();
1611        let mut server =
1612            PairingServer::new(node("rm-1", Role::Rm), endpoint(Deployment::Lan), binding());
1613        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1614        assert!(
1615            server
1616                .request_pairing(
1617                    &request,
1618                    &code().token,
1619                    &SERVER_CHALLENGE,
1620                    attempt_id(),
1621                    t(16)
1622                )
1623                .is_ok()
1624        );
1625    }
1626
1627    #[test]
1628    fn a_client_without_sha256_is_refused() {
1629        let Run {
1630            mut client,
1631            mut server,
1632        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1633        let mut request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1634        request.supported_hmac_hashing_algorithms.clear();
1635        assert!(matches!(
1636            server.request_pairing(
1637                &request,
1638                &code().token,
1639                &SERVER_CHALLENGE,
1640                attempt_id(),
1641                t(0)
1642            ),
1643            Err(ConnectError::Refused(PairingRefused {
1644                error_message: PairingErrorMessage::IncompatibleHmacHashingAlgorithms,
1645                ..
1646            }))
1647        ));
1648    }
1649
1650    #[test]
1651    fn a_short_challenge_never_reaches_the_wire() {
1652        let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1653        assert!(matches!(
1654            client.request_pairing(&[0u8; 16]),
1655            Err(ConnectError::WeakSecret { need: 32, .. })
1656        ));
1657    }
1658
1659    #[test]
1660    fn the_attempt_id_is_a_bearer_and_is_compared_in_constant_time() {
1661        let Run {
1662            mut client,
1663            mut server,
1664        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1665        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1666        server
1667            .request_pairing(
1668                &request,
1669                &code().token,
1670                &SERVER_CHALLENGE,
1671                attempt_id(),
1672                t(0),
1673            )
1674            .unwrap();
1675
1676        assert!(server.authenticates(attempt_id().as_str()));
1677        assert!(!server.authenticates("something else entirely"));
1678        assert!(!server.authenticates(""));
1679        // 24 bytes Base64-encode to the 32 characters the specification requires.
1680        assert_eq!(attempt_id().as_str().len(), PairingAttemptId::MIN_LEN);
1681        assert!(PairingAttemptId::from_entropy(&[0u8; 23]).is_err());
1682        // And it never prints itself.
1683        assert_eq!(
1684            alloc::format!("{:?}", attempt_id()),
1685            "PairingAttemptId(<redacted>)"
1686        );
1687    }
1688
1689    #[test]
1690    fn a_client_that_gives_up_says_so_and_no_pairing_is_stored() {
1691        let Run {
1692            mut client,
1693            mut server,
1694        } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1695        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1696        let (_, accepted) = server
1697            .request_pairing(
1698                &request,
1699                &code().token,
1700                &SERVER_CHALLENGE,
1701                attempt_id(),
1702                t(0),
1703            )
1704            .unwrap();
1705        client
1706            .accept(accepted, binding(), Deployment::Lan, t(1))
1707            .unwrap();
1708
1709        let body = client.abandon();
1710        assert!(!body.success);
1711        assert!(server.finalize(body, t(2)).unwrap().is_none());
1712    }
1713
1714    #[test]
1715    fn the_request_body_is_the_shape_the_openapi_defines() {
1716        let Run { mut client, .. } = setup(Role::Cem, Deployment::Lan, Deployment::Lan);
1717        let request = client.request_pairing(&CLIENT_CHALLENGE).unwrap();
1718        let json = serde_json::to_value(&request).expect("serializable");
1719        for key in [
1720            "clientNodeDescription",
1721            "clientEndpointDescription",
1722            "supportedCommunicationProtocols",
1723            "supportedS2MessageVersions",
1724            "supportedHmacHashingAlgorithms",
1725            "clientHmacChallenge",
1726        ] {
1727            assert!(json.get(key).is_some(), "missing required property {key}");
1728        }
1729        // "may never be used at the same time" — and `forcePairing` defaults to absent.
1730        assert!(json.get("nodeId").is_none());
1731        assert!(json.get("nodeIdAlias").is_some());
1732        assert!(json.get("forcePairing").is_none());
1733        assert_eq!(
1734            json["clientNodeDescription"]["role"].as_str(),
1735            Some("CEM"),
1736            "the role enum is spelled as the schema spells it"
1737        );
1738    }
1739}