Skip to main content

s2_kit/connect/client/
pairing.rs

1//! Driving the pairing state machine over HTTPS.
2
3use alloc::string::{String, ToString};
4use alloc::vec::Vec;
5
6use crate::connect::proto::{
7    ConnectionDetails, Deployment, EndpointDescription, HmacBinding, NextStep, NodeDescription,
8    Pairing as ProtoPairing, PairingClient, PairingCode,
9};
10use crate::connect::tls::{CapturedIdentity, Fingerprint, TlsPolicy};
11use crate::types::{ProtocolVersion, Timestamp};
12
13use super::http::{Error, Http};
14
15/// The paths, relative to the endpoint's versioned base URL.
16const REQUEST_PAIRING: &str = "requestPairing";
17const REQUEST_CONNECTION_DETAILS: &str = "requestConnectionDetails";
18const POST_CONNECTION_DETAILS: &str = "postConnectionDetails";
19// The path, which is what goes on the wire. `S2C-OAS pairing` gives this operation the
20// `operationId` `confirmPairing`, which every other operation in the file does not do —
21// so a generated client calls it `confirm_pairing` and nobody searching for
22// `finalizePairing` finds it (erratum E28).
23const FINALIZE_PAIRING: &str = "finalizePairing";
24
25/// What a completed pairing leaves you holding.
26#[derive(Debug)]
27pub struct Paired {
28    /// Everything the protocol agreed: who, where, and with which first access token.
29    pub pairing: ProtoPairing,
30    /// The certificate chain the server presented during a **LAN** pairing.
31    ///
32    /// For a LAN endpoint this is what the specification tells you to pin:
33    /// `S2C §4` — "The client **must** pin the self-signed CA (root) certificate, and
34    /// trust this certificate for the remainder of the pairing relation."
35    pub identity: Option<CapturedIdentity>,
36}
37
38impl Paired {
39    /// The certificate every later connection to this peer is pinned to, if any.
40    ///
41    /// The CA captured during a LAN pairing, whose leaf the challenge response verified.
42    /// `None` for a WAN peer, which the public PKI vouches for. Persist it beside the
43    /// access token: 32 bytes, and without it every later connection to this device is
44    /// unauthenticated.
45    #[must_use]
46    pub fn pin(&self) -> Option<Fingerprint> {
47        self.identity.as_ref().map(|identity| identity.root)
48    }
49
50    /// The TLS policy every later connection to this peer should use.
51    #[must_use]
52    pub fn policy(&self) -> TlsPolicy {
53        self.pin().map_or(TlsPolicy::Web, TlsPolicy::Pinned)
54    }
55}
56
57/// Runs one pairing attempt against one endpoint.
58///
59/// ```no_run
60/// use s2_kit::connect::client::Pairing;
61/// use s2_kit::connect::proto::*;
62/// use s2_kit::types::Timestamp;
63///
64/// # async fn run(me: NodeDescription) -> Result<(), Box<dyn std::error::Error>> {
65/// // Whatever the end user typed, and wherever they typed the URL from.
66/// let code = PairingCode::parse("evse7-A1b2C3", TokenKind::Static)?;
67///
68/// let paired = Pairing::lan("https://EVSE1038.local/", me, EndpointDescription::default())?
69///     .run(code, Timestamp::now())
70///     .await?;
71///
72/// // Persist both: the token is useless without the certificate to trust.
73/// let policy = paired.policy();
74/// # let _ = policy;
75/// # Ok(())
76/// # }
77/// ```
78#[derive(Debug)]
79pub struct Pairing {
80    http: Http,
81    local: NodeDescription,
82    local_endpoint: EndpointDescription,
83    deployment: Deployment,
84    /// `None` in a LAN, where the binding is the certificate we have not seen yet.
85    domain: Option<String>,
86    s2_message_versions: Option<Vec<ProtocolVersion>>,
87    force: bool,
88    /// Read before every step, so the fifteen-second budget is measured, not assumed.
89    clock: fn() -> Timestamp,
90}
91
92impl Pairing {
93    /// How long any single pairing request may take.
94    ///
95    /// Shorter than the fifteen-second budget for the whole attempt, so that one slow
96    /// request fails as a request rather than as an expired pairing — a far clearer thing
97    /// to see in a log.
98    pub const REQUEST_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(10);
99
100    /// Pair with an endpoint in the same LAN.
101    ///
102    /// The certificate is self-signed and unverifiable, so the first request runs under
103    /// [`TlsPolicy::LanPairingOnly`] and the challenge response is what decides whether
104    /// the server was genuine. See [`crate::connect::tls`].
105    pub fn lan(
106        base_url: &str,
107        local: NodeDescription,
108        local_endpoint: EndpointDescription,
109    ) -> Result<Self, Error> {
110        Ok(Self {
111            http: Http::new(base_url, &TlsPolicy::LanPairingOnly, Self::REQUEST_TIMEOUT)?,
112            local,
113            local_endpoint,
114            deployment: Deployment::Lan,
115            domain: None,
116            s2_message_versions: None,
117            force: false,
118            clock: Timestamp::now,
119        })
120    }
121
122    /// Pair with an endpoint on the public internet.
123    ///
124    /// Here the certificate *is* verifiable, so it is verified, and the binding is the
125    /// domain name rather than a fingerprint.
126    pub fn wan(
127        base_url: &str,
128        local: NodeDescription,
129        local_endpoint: EndpointDescription,
130    ) -> Result<Self, Error> {
131        let http = Http::new(base_url, &TlsPolicy::Web, Self::REQUEST_TIMEOUT)?;
132        // "The domain name of the HTTPS server, including subdomains, without protocol or
133        // trailing slashes."
134        let domain = http
135            .base()
136            .host_str()
137            .ok_or_else(|| Error::Url(base_url.to_string()))?
138            .to_string();
139        Ok(Self {
140            http,
141            local,
142            local_endpoint,
143            deployment: Deployment::Wan,
144            domain: Some(domain),
145            s2_message_versions: None,
146            force: false,
147            clock: Timestamp::now,
148        })
149    }
150
151    /// Offer a different set of S2 JSON message versions, newest first.
152    #[must_use]
153    pub fn with_s2_message_versions(mut self, versions: Vec<ProtocolVersion>) -> Self {
154        self.s2_message_versions = Some(versions);
155        self
156    }
157
158    /// Pair even with no S2 message version in common.
159    #[must_use]
160    pub fn forcing(mut self) -> Self {
161        self.force = true;
162        self
163    }
164
165    /// Use a different clock for the budget checks between steps — a virtual one, in a
166    /// test.
167    #[must_use]
168    pub fn with_clock(mut self, clock: fn() -> Timestamp) -> Self {
169        self.clock = clock;
170        self
171    }
172
173    /// Run the whole attempt: four requests, or three plus a push.
174    ///
175    /// `now` starts the fifteen-second budget; every later step reads the clock again, so
176    /// an attempt that runs past the budget on this side fails here as it already has on
177    /// the server (`S2C §Interruption`). Entropy is drawn from the operating system;
178    /// [`Self::run_with_entropy`] takes it as a parameter for a test that needs it pinned.
179    pub async fn run(&self, code: PairingCode, now: Timestamp) -> Result<Paired, Error> {
180        let mut nonce = [0u8; 32];
181        fill_random(&mut nonce)?;
182        self.run_with_entropy(code, now, &nonce, None).await
183    }
184
185    /// As [`Self::run`], with the client nonce supplied and, when this node will be the
186    /// communication server, the details to offer.
187    ///
188    /// A LAN Resource Manager never needs the second argument: it is never the
189    /// communication server. A CEM usually does.
190    pub async fn run_with_entropy(
191        &self,
192        code: PairingCode,
193        now: Timestamp,
194        client_nonce: &[u8],
195        own_details: Option<ConnectionDetails>,
196    ) -> Result<Paired, Error> {
197        // Step 1 carries a challenge and no response, which is exactly why it can be
198        // sent before the binding is known: in a LAN, the handshake this request performs
199        // is what reveals it.
200        let mut machine = self.machine(code, now);
201        let body = machine.request_pairing(client_nonce)?;
202        crate::trace::event!(
203            info,
204            deployment = ?self.deployment,
205            alias = ?body.node_id_alias,
206            "requesting pairing"
207        );
208        let accepted: crate::connect::proto::PairingAccepted = self
209            .http
210            .post("requestPairing", REQUEST_PAIRING, None, &body)
211            .await?;
212
213        // From here on the server is holding an attempt for us, and every failure below is
214        // one it would otherwise sit on for the whole fifteen-second budget — refusing
215        // every retry with `503`, because the rate limit is one attempt per node per
216        // second and an attempt in flight occupies the slot. `finalizePairing { success:
217        // false }` is what releases it, and `S2C` calls that a legitimate outcome rather
218        // than an error path. So the rest of the attempt runs in a closure whose failure
219        // is reported *and* cleaned up.
220        let bearer_of = |machine: &PairingClient| {
221            machine
222                .attempt_id()
223                .map(|id| id.as_str().to_string())
224                .unwrap_or_default()
225        };
226        match self.finish(&mut machine, accepted, own_details).await {
227            Ok(paired) => Ok(paired),
228            Err(e) => {
229                let bearer = bearer_of(&machine);
230                if !bearer.is_empty() {
231                    crate::trace::event!(
232                        info,
233                        error = %e,
234                        "releasing the pairing attempt after a failure"
235                    );
236                    self.abandon(&bearer).await;
237                }
238                Err(e)
239            }
240        }
241    }
242
243    /// Steps 4 to 8, once `requestPairing` has been answered.
244    async fn finish(
245        &self,
246        machine: &mut PairingClient,
247        accepted: crate::connect::proto::PairingAccepted,
248        own_details: Option<ConnectionDetails>,
249    ) -> Result<Paired, Error> {
250        // The handshake has happened, so in a LAN we now know `F`. Supplying it here —
251        // rather than at the start — is the whole reason this driver exists.
252        let identity = self.http.tls().captured();
253        if !self.http.tls().identity_is_stable() {
254            return Err(Error::IdentityChanged);
255        }
256        let binding = match &self.domain {
257            Some(domain) => HmacBinding::DomainName(domain.clone()),
258            None => identity
259                .as_ref()
260                .map(|i| i.leaf.binding())
261                .ok_or(Error::IdentityChanged)?,
262        };
263
264        crate::trace::event!(debug, binding = ?binding, "checking the server's response");
265
266        // Steps 4 and 5. How the server was reached is the fallback for a server that
267        // does not state its own deployment.
268        let next = machine.accept(accepted, binding, self.deployment, (self.clock)())?;
269        crate::trace::event!(info, next = ?next, "the server authenticated");
270        let bearer = machine
271            .attempt_id()
272            .map(|id| id.as_str().to_string())
273            .unwrap_or_default();
274
275        // Steps 6 and 7.
276        match next {
277            NextStep::RequestConnectionDetails => {
278                let ask = machine.request_connection_details()?;
279                let details: ConnectionDetails = self
280                    .http
281                    .post(
282                        "requestConnectionDetails",
283                        REQUEST_CONNECTION_DETAILS,
284                        Some(&bearer),
285                        &ask,
286                    )
287                    .await?;
288                machine.connection_details(details, (self.clock)())?;
289            }
290            NextStep::PostConnectionDetails => {
291                let details = own_details.ok_or(Error::Protocol(
292                    crate::connect::proto::ConnectError::OutOfOrder {
293                        got: "a pairing in which this node is the communication server",
294                        expected: "connection details to offer",
295                    },
296                ))?;
297                let post = machine.post_connection_details(details, (self.clock)())?;
298                self.http
299                    .post_empty(
300                        "postConnectionDetails",
301                        POST_CONNECTION_DETAILS,
302                        Some(&bearer),
303                        Some(&post),
304                    )
305                    .await?;
306            }
307        }
308
309        // Step 8. The certificate must still be the one we bound to.
310        if !self.http.tls().identity_is_stable() {
311            return Err(Error::IdentityChanged);
312        }
313        let (body, pairing) = machine.finalize((self.clock)())?;
314        crate::trace::event!(
315            info,
316            remote = %pairing.remote.id,
317            communication_server = ?pairing.communication_server,
318            "pairing complete"
319        );
320        self.http
321            .post_empty(
322                "finalizePairing",
323                FINALIZE_PAIRING,
324                Some(&bearer),
325                Some(&body),
326            )
327            .await?;
328
329        Ok(Paired {
330            pairing,
331            identity: (self.deployment == Deployment::Lan)
332                .then_some(identity)
333                .flatten(),
334        })
335    }
336
337    /// Tell the server we are giving up, so it does not hold the attempt open.
338    ///
339    /// Best effort: if this fails there is nothing useful to do about it, and the server's
340    /// own fifteen-second budget will clean up.
341    pub async fn abandon(&self, bearer: &str) {
342        let body = crate::connect::proto::FinalizePairing { success: false };
343        let _ = self
344            .http
345            .post_empty(
346                "finalizePairing",
347                FINALIZE_PAIRING,
348                Some(bearer),
349                Some(&body),
350            )
351            .await;
352    }
353
354    fn machine(&self, code: PairingCode, now: Timestamp) -> PairingClient {
355        let mut machine =
356            PairingClient::start(self.local.clone(), self.local_endpoint.clone(), code, now);
357        if let Some(versions) = &self.s2_message_versions {
358            machine = machine.with_s2_message_versions(versions.clone());
359        }
360        if self.force {
361            machine = machine.forcing();
362        }
363        machine
364    }
365}
366
367/// Fill a buffer with cryptographically secure randomness.
368pub(crate) fn fill_random(buffer: &mut [u8]) -> Result<(), Error> {
369    use rand::TryRng as _;
370    // The operating system's CSPRNG. A failure here means the system has no entropy
371    // source — not something a retry fixes, and not something to paper over with a
372    // weaker generator when the value is about to authenticate a device.
373    rand::rngs::SysRng
374        .try_fill_bytes(buffer)
375        .map_err(|e| Error::Transport {
376            operation: "drawing randomness",
377            source: Box::new(e),
378        })
379}