Skip to main content

s2_kit/connect/proto/
mod.rs

1//! S2 Connect as pure state machines: no sockets, no clock, no hidden randomness.
2//!
3//! Everything a driver could forget lives here instead — the HMAC binding that defeats a
4//! man in the middle, the fifteen-second pairing budget, the one-attempt-per-node-per-
5//! second rate limit, the pending-token exchange that must not strand a pairing if the
6//! network drops between two requests.
7
8pub mod lan;
9pub mod pairing;
10pub mod session_init;
11
12use alloc::string::{String, ToString};
13use alloc::vec::Vec;
14
15use base64::Engine as _;
16use serde::{Deserialize, Serialize};
17use zeroize::{Zeroize, ZeroizeOnDrop};
18
19use crate::types::Duration;
20
21pub use lan::{
22    CancelPreparePairing, LONG_POLL_HOLD, LONG_POLL_TIMEOUT, NodeListing, PreparePairing,
23    PrepareRefused, WaitAction, WaitErrorMessage, WaitForPairing, WaitInstruction,
24};
25pub use pairing::{
26    ConnectionDetails, ConnectionDetailsPost, ConnectionDetailsRequest, FinalizePairing,
27    MINIMUM_SERVER_DELAY, NextStep, PAIRING_BUDGET, Pairing, PairingAccepted, PairingAttemptId,
28    PairingClient, PairingErrorMessage, PairingRefused, PairingRequest, PairingServer, PairingStep,
29};
30pub use session_init::{
31    COMMUNICATION_TOKEN_LIFETIME, CommunicationDetails, SessionCredentials, SessionErrorMessage,
32    SessionGrant, SessionInitClient, SessionInitServer, SessionRefused, SessionRequest, TokenStore,
33    UnpairRequest,
34};
35
36/// Which side of an S2 conversation a node hosts.
37///
38/// The same two values as [`EnergyManagementRole`](crate::types::common::EnergyManagementRole),
39/// spelled as `s2-connect-common.yml` spells them.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
41#[serde(rename_all = "UPPERCASE")]
42pub enum Role {
43    /// A Customer Energy Manager.
44    Cem,
45    /// A Resource Manager.
46    Rm,
47}
48
49impl Role {
50    /// The DNS-SD subtype a node of this role advertises.
51    #[must_use]
52    pub const fn service_subtype(self) -> &'static str {
53        match self {
54            Role::Cem => "_cem",
55            Role::Rm => "_rm",
56        }
57    }
58
59    /// Whether these two roles may pair. "S2 communication between two nodes can only be
60    /// established if one of the nodes is a CEM and the other a RM."
61    #[must_use]
62    pub const fn can_pair_with(self, other: Self) -> bool {
63        !matches!((self, other), (Role::Cem, Role::Cem) | (Role::Rm, Role::Rm))
64    }
65
66    /// The only role this one can pair with.
67    #[must_use]
68    pub const fn other(self) -> Self {
69        match self {
70            Role::Cem => Role::Rm,
71            Role::Rm => Role::Cem,
72        }
73    }
74}
75
76/// Where a node runs.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
78#[serde(rename_all = "UPPERCASE")]
79pub enum Deployment {
80    /// On the public internet.
81    Wan,
82    /// On the building's own network.
83    Lan,
84}
85
86impl Deployment {
87    /// Which side is the **communication** server, given both deployments and which is
88    /// the CEM.
89    ///
90    /// `S2C §Mapping the CEM and RM to communication server or client`: a WAN node is
91    /// always the server; otherwise the CEM is.
92    #[must_use]
93    pub const fn communication_server(cem: Self, rm: Self) -> Role {
94        match (cem, rm) {
95            (Deployment::Lan, Deployment::Wan) => Role::Rm,
96            _ => Role::Cem,
97        }
98    }
99}
100
101/// A node's globally unique identifier.
102///
103/// `s2-connect-common.yml/NodeId` gives `format: uuid`, and [`NodeId::generate`] produces
104/// one. The underlying [`Id`](crate::types::Id) is the S2 JSON identifier type, which
105/// accepts more than a UUID — so a peer that sends `"evse-1"` is understood rather than
106/// refused, on the same reasoning as erratum E1.
107///
108/// Ordered so that an endpoint can key a map by it, which every endpoint hosting more
109/// than one node needs to do.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
111#[serde(transparent)]
112pub struct NodeId(pub crate::types::Id);
113
114impl NodeId {
115    /// A fresh identifier.
116    #[cfg(feature = "uuid")]
117    #[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
118    #[must_use]
119    pub fn generate() -> Self {
120        Self(crate::types::Id::generate())
121    }
122
123    /// Parse one.
124    pub fn parse(s: &str) -> Result<Self, ConnectError> {
125        crate::types::Id::parse(s)
126            .map(Self)
127            .map_err(|_| ConnectError::MalformedNodeId)
128    }
129}
130
131impl core::fmt::Display for NodeId {
132    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
133        self.0.fmt(f)
134    }
135}
136
137/// A short identifier for a node within one endpoint.
138///
139/// An endpoint may host thousands of nodes; a node id is a UUID and nobody is going to
140/// type one. The alias is what makes the pairing code short enough to read off a screen.
141///
142/// The invariant is enforced on the way **in as well as out**: `nodeIdAlias` is a field of
143/// `requestPairing`, which needs no bearer, so it is a string an unauthenticated peer
144/// chooses. A `#[serde(transparent)]` newtype whose `parse` validates and whose
145/// `Deserialize` does not is a validated type in name only.
146#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
147#[serde(transparent)]
148pub struct NodeIdAlias(pub String);
149
150impl NodeIdAlias {
151    /// The longest alias this crate accepts.
152    ///
153    /// The specification's pattern, `^[0-9a-zA-Z]+$`, has no upper bound — but the alias
154    /// exists so that a person can read a pairing code off a screen and type it, and
155    /// nothing about that is improved past sixty-four characters. A bound is what turns
156    /// "an unauthenticated peer picks this string" from a question into a fact.
157    pub const MAX_LEN: usize = 64;
158
159    /// Parse an alias: `^[0-9a-zA-Z]+$`, at most [`MAX_LEN`](Self::MAX_LEN) characters.
160    pub fn parse(s: &str) -> Result<Self, ConnectError> {
161        if s.is_empty() || s.len() > Self::MAX_LEN || !s.bytes().all(|b| b.is_ascii_alphanumeric())
162        {
163            return Err(ConnectError::MalformedPairingCode);
164        }
165        Ok(Self(s.to_string()))
166    }
167}
168
169impl<'de> Deserialize<'de> for NodeIdAlias {
170    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
171        let raw = <&str as Deserialize>::deserialize(deserializer)?;
172        Self::parse(raw).map_err(serde::de::Error::custom)
173    }
174}
175
176/// The secret half of a pairing code.
177///
178/// Zeroized on drop and never compared with `==`: [`ChallengeResponse`] is the only thing
179/// that ever looks at it, and it does so in constant time.
180#[derive(Clone, Zeroize, ZeroizeOnDrop)]
181pub struct PairingToken(Vec<u8>);
182
183/// Compared in constant time, so that a `==` on a secret cannot leak its prefix through
184/// timing. `PairingCode` derives `PartialEq`, and this is what that derive calls.
185impl PartialEq for PairingToken {
186    fn eq(&self, other: &Self) -> bool {
187        use subtle::ConstantTimeEq as _;
188        self.0.ct_eq(&other.0).into()
189    }
190}
191
192impl Eq for PairingToken {}
193
194impl PairingToken {
195    /// The fewest characters a token that expires may have.
196    pub const MIN_DYNAMIC: usize = 4;
197    /// The fewest characters a token printed on a device may have.
198    pub const MIN_STATIC: usize = 6;
199    /// The most characters any pairing token may have.
200    ///
201    /// The specification gives minimums and no maximum. A token is typed by a person or
202    /// read off a label, so 256 characters is already absurd — and the value goes into an
203    /// HMAC, so an unbounded one is unbounded work for whoever holds the other end.
204    pub const MAX_LEN: usize = 256;
205
206    /// Parse a token, checking the length its kind requires.
207    pub fn parse(s: &str, kind: TokenKind) -> Result<Self, ConnectError> {
208        let minimum = match kind {
209            TokenKind::Dynamic => Self::MIN_DYNAMIC,
210            TokenKind::Static => Self::MIN_STATIC,
211        };
212        if s.len() < minimum
213            || s.len() > Self::MAX_LEN
214            || !s.bytes().all(|b| b.is_ascii_alphanumeric())
215        {
216            return Err(ConnectError::MalformedPairingCode);
217        }
218        Ok(Self(s.as_bytes().to_vec()))
219    }
220
221    /// The bytes, for the HMAC. `S2C §Challenge response process`: "The pairing token and
222    /// domain name are strings, which need to be converted into binary data using the
223    /// ASCII table."
224    #[must_use]
225    pub fn as_bytes(&self) -> &[u8] {
226        &self.0
227    }
228}
229
230impl core::fmt::Debug for PairingToken {
231    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
232        // Never print a secret, not even in a panic message.
233        write!(f, "PairingToken(<{} characters>)", self.0.len())
234    }
235}
236
237/// Whether a pairing token expires.
238///
239/// # A four-character token is weaker than it looks
240///
241/// The specification's stated mitigation for brute force is the server's one-second delay
242/// and its per-node serialisation ([`pairing::MINIMUM_SERVER_DELAY`]), and this crate
243/// implements both. They bound *online* guessing.
244///
245/// They do not bound offline guessing, because `requestPairing` answers with
246/// `R_c = HMAC(C_c, T ‖ F)` for a challenge the caller chose, and `F` — the server's
247/// leaf-certificate fingerprint — is public. One reachable request is therefore enough to
248/// recover the token at leisure: a [`Dynamic`](Self::Dynamic) token's four alphanumeric
249/// characters are 14.7 million candidates, which is seconds of GPU time, and its five
250/// minutes of validity do not help against an attacker who already has the answer.
251///
252/// So: prefer longer tokens than the minimum, and treat the minimum as what it is — a
253/// floor the specification permits, recorded as erratum E18.
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255pub enum TokenKind {
256    /// Generated on demand and expiring; five minutes is recommended. At least
257    /// [`PairingToken::MIN_DYNAMIC`] characters — see the warning above about that floor.
258    Dynamic,
259    /// Printed on the device, valid indefinitely. At least
260    /// [`PairingToken::MIN_STATIC`] characters.
261    Static,
262}
263
264/// What the end user copies from one node to the other.
265///
266/// `[nodeIdAlias-]pairingToken`, matching `^([0-9a-zA-Z]+-)?[0-9a-zA-Z]{4,}$`. The alias
267/// is not secret and is sent; the token is secret and never is.
268#[derive(Debug, Clone, PartialEq, Eq)]
269pub struct PairingCode {
270    /// Which node at the endpoint, when the endpoint hosts more than one.
271    pub alias: Option<NodeIdAlias>,
272    /// The secret.
273    pub token: PairingToken,
274}
275
276impl PairingCode {
277    /// Parse a pairing code as the end user typed it.
278    ///
279    /// ```
280    /// use s2_kit::connect::proto::{PairingCode, TokenKind};
281    ///
282    /// // An endpoint with one node: the code is just the token.
283    /// let code = PairingCode::parse("A1b2C3", TokenKind::Static)?;
284    /// assert!(code.alias.is_none());
285    ///
286    /// // An endpoint with many: the alias comes first.
287    /// let code = PairingCode::parse("evse7-A1b2C3", TokenKind::Static)?;
288    /// assert_eq!(code.alias.unwrap().0, "evse7");
289    ///
290    /// // The token is checked for length, so a typo is caught before the network is.
291    /// assert!(PairingCode::parse("abc", TokenKind::Dynamic).is_err());
292    /// # Ok::<(), s2_kit::connect::proto::ConnectError>(())
293    /// ```
294    pub fn parse(code: &str, kind: TokenKind) -> Result<Self, ConnectError> {
295        match code.split_once('-') {
296            // A dash means an alias precedes the token — but a token may not contain one,
297            // so the *first* dash is the separator.
298            Some((alias, token)) => Ok(Self {
299                alias: Some(NodeIdAlias::parse(alias)?),
300                token: PairingToken::parse(token, kind)?,
301            }),
302            None => Ok(Self {
303                alias: None,
304                token: PairingToken::parse(code, kind)?,
305            }),
306        }
307    }
308}
309
310/// A one-time secret that lets a communication client start a session.
311///
312/// `S2C-OAS common`: "valid for one time login, with a maximum 5 years", Base64, at least
313/// 32 bytes.
314#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
315#[serde(transparent)]
316pub struct AccessToken(String);
317
318/// A secret that authorises exactly one WebSocket connection.
319///
320/// `S2C-OAS common`: "valid for maximum 30 seconds". The prose calls it `commToken`; the
321/// schema calls it `websocketToken` (erratum E9).
322#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
323#[serde(transparent)]
324pub struct CommunicationToken(String);
325
326macro_rules! opaque_token {
327    ($ty:ident, $name:literal, $lifetime:expr) => {
328        impl $ty {
329            /// The fewest bytes of entropy the specification requires.
330            pub const MIN_BYTES: usize = 32;
331
332            /// Wrap a token received from a peer.
333            #[must_use]
334            pub fn new(value: impl Into<String>) -> Self {
335                Self(value.into())
336            }
337
338            /// Generate one from 32 bytes of cryptographically secure randomness.
339            ///
340            /// The bytes are a parameter rather than drawn here, so the protocol layer
341            /// stays pure and a test can pin them.
342            pub fn from_entropy(bytes: &[u8]) -> Result<Self, ConnectError> {
343                if bytes.len() < Self::MIN_BYTES {
344                    return Err(ConnectError::WeakSecret {
345                        got: bytes.len(),
346                        need: Self::MIN_BYTES,
347                    });
348                }
349                Ok(Self(
350                    base64::engine::general_purpose::STANDARD.encode(bytes),
351                ))
352            }
353
354            /// The Base64 form, which is what travels.
355            #[must_use]
356            pub fn as_str(&self) -> &str {
357                &self.0
358            }
359
360            /// How long the specification says it stays usable.
361            #[must_use]
362            pub const fn lifetime() -> Duration {
363                $lifetime
364            }
365
366            /// Whether another token is this one, compared in constant time.
367            #[must_use]
368            pub fn verify(&self, other: &Self) -> bool {
369                self.verify_str(&other.0)
370            }
371
372            /// Whether a token as it arrived on the wire is this one, compared in
373            /// constant time.
374            ///
375            /// A short-circuiting `==` on a bearer token leaks its prefix to anyone who
376            /// can time the answer, which is why these types have no `PartialEq` at all:
377            /// there is no way to compare them carelessly.
378            #[must_use]
379            pub fn verify_str(&self, presented: &str) -> bool {
380                use subtle::ConstantTimeEq as _;
381                // Length is not a secret — the encoding fixes it — so an early return on
382                // a mismatch reveals nothing a listener could not already count.
383                self.0.len() == presented.len()
384                    && bool::from(self.0.as_bytes().ct_eq(presented.as_bytes()))
385            }
386        }
387
388        impl core::fmt::Debug for $ty {
389            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
390                write!(f, concat!($name, "(<redacted>)"))
391            }
392        }
393    };
394}
395
396// 5 years and 30 seconds, as `s2-connect-common.yml` gives them.
397opaque_token!(AccessToken, "AccessToken", Duration::from_secs(157_680_000));
398opaque_token!(
399    CommunicationToken,
400    "CommunicationToken",
401    Duration::from_secs(30)
402);
403
404/// Information about a node, as `s2-connect-common.yml` defines it.
405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
406pub struct NodeDescription {
407    /// The node's identifier.
408    pub id: NodeId,
409    /// The brand a user would recognise.
410    pub brand: String,
411    /// A logo.
412    #[serde(rename = "logoUrl", skip_serializing_if = "Option::is_none")]
413    pub logo_url: Option<String>,
414    /// What kind of thing it is.
415    #[serde(rename = "type")]
416    pub kind: String,
417    /// The model name.
418    #[serde(rename = "modelName")]
419    pub model_name: String,
420    /// A name the user gave it.
421    #[serde(rename = "userDefinedName", skip_serializing_if = "Option::is_none")]
422    pub user_defined_name: Option<String>,
423    /// Whether it is a CEM or an RM.
424    pub role: Role,
425}
426
427/// Information about the endpoint that hosts nodes. Every field is optional.
428#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
429pub struct EndpointDescription {
430    /// A user-facing name.
431    #[serde(skip_serializing_if = "Option::is_none")]
432    pub name: Option<String>,
433    /// A logo.
434    #[serde(rename = "logoUrl", skip_serializing_if = "Option::is_none")]
435    pub logo_url: Option<String>,
436    /// Where it runs.
437    #[serde(skip_serializing_if = "Option::is_none")]
438    pub deployment: Option<Deployment>,
439}
440
441/// Anything that can go wrong in the pure protocol.
442#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
443#[non_exhaustive]
444pub enum ConnectError {
445    /// The pairing code does not match `^([0-9a-zA-Z]+-)?[0-9a-zA-Z]{4,}$`, or the token
446    /// is shorter than its kind allows.
447    #[error("the pairing code is malformed")]
448    MalformedPairingCode,
449    /// A node identifier is not a legal identifier.
450    #[error("the node identifier is malformed")]
451    MalformedNodeId,
452    /// A challenge or token carries less entropy than the specification requires.
453    #[error("a secret of {got} bytes is weaker than the {need} the specification requires")]
454    WeakSecret {
455        /// What was supplied.
456        got: usize,
457        /// What is required.
458        need: usize,
459    },
460    /// The challenge response did not match. Someone is in the middle, or the user
461    /// mistyped.
462    #[error("the challenge response does not match")]
463    ChallengeFailed,
464    /// The two nodes cannot pair: two CEMs, or two RMs.
465    #[error("a {0:?} cannot pair with another {0:?}")]
466    SameRole(Role),
467    /// The step arrived out of order.
468    #[error("{got} arrived while waiting for {expected}")]
469    OutOfOrder {
470        /// What arrived.
471        got: &'static str,
472        /// What was expected.
473        expected: &'static str,
474    },
475    /// The fifteen-second budget ran out.
476    #[error("the {what} budget of {} seconds ran out", limit.as_secs_f64())]
477    Expired {
478        /// Which budget.
479        what: &'static str,
480        /// How long it was.
481        limit: Duration,
482    },
483    /// The server is already handling an attempt for this node.
484    ///
485    /// `S2C §2. Calculate clientHmacChallengeResponse`: "pairing attempts **must** be
486    /// handled sequentially, such that each second only one pairing attempt can be
487    /// processed for a node."
488    #[error("another pairing attempt for this node is in progress")]
489    RateLimited,
490    /// The peer offered no version, protocol or algorithm in common.
491    #[error("no common {0}")]
492    NoOverlap(&'static str),
493    /// No pairing exists for this pair of node identifiers, or the token is wrong.
494    #[error("not paired")]
495    NotPaired,
496    /// The pairing server refused, with one of the reasons the specification enumerates.
497    ///
498    /// A driver turns this into `400` with the body verbatim.
499    #[error("pairing refused: {:?}", .0.error_message)]
500    Refused(pairing::PairingRefused),
501    /// The communication server refused a session, likewise.
502    #[error("session refused: {:?}", .0.error_message)]
503    SessionRefused(session_init::SessionRefused),
504}
505
506/// What the challenge–response is bound to, which is what defeats a man in the middle.
507///
508/// `S2C §Challenge response process`:
509/// `R = HMAC(C, T ‖ F)` when the pairing server is in the LAN, where `F` is the SHA-256
510/// fingerprint of the **leaf** TLS certificate; `R = HMAC(C, T ‖ D)` in the WAN, where
511/// `D` is the domain name.
512#[derive(Debug, Clone, PartialEq, Eq)]
513pub enum HmacBinding {
514    /// A LAN server: the fingerprint of its leaf certificate, already hex-decoded.
515    ///
516    /// "SHA256 certificate fingerprints are encoded into a hexadecimal string, and must
517    /// be decoded as hexadecimal string before it can be used as input (note that
518    /// fingerprint strings usually contain colons to separate bytes)."
519    LeafFingerprint(Vec<u8>),
520    /// A WAN server: its domain name, "including subdomains, without protocol or trailing
521    /// slashes".
522    DomainName(String),
523}
524
525impl HmacBinding {
526    /// A binding from a fingerprint written as hexadecimal, with or without colons.
527    pub fn from_hex_fingerprint(hex: &str) -> Result<Self, ConnectError> {
528        let digits: Vec<u8> = hex.bytes().filter(|b| *b != b':' && *b != b' ').collect();
529        if !digits.len().is_multiple_of(2) || digits.is_empty() {
530            return Err(ConnectError::WeakSecret {
531                got: digits.len() / 2,
532                need: 32,
533            });
534        }
535        let mut bytes = Vec::with_capacity(digits.len() / 2);
536        for pair in digits.chunks(2) {
537            let hi = hex_value(*pair.first().unwrap_or(&0))?;
538            let lo = hex_value(*pair.get(1).unwrap_or(&0))?;
539            bytes.push(hi << 4 | lo);
540        }
541        if bytes.len() < 32 {
542            return Err(ConnectError::WeakSecret {
543                got: bytes.len(),
544                need: 32,
545            });
546        }
547        Ok(Self::LeafFingerprint(bytes))
548    }
549
550    fn as_bytes(&self) -> &[u8] {
551        match self {
552            HmacBinding::LeafFingerprint(bytes) => bytes,
553            HmacBinding::DomainName(name) => name.as_bytes(),
554        }
555    }
556}
557
558fn hex_value(b: u8) -> Result<u8, ConnectError> {
559    match b {
560        b'0'..=b'9' => Ok(b - b'0'),
561        b'a'..=b'f' => Ok(b - b'a' + 10),
562        b'A'..=b'F' => Ok(b - b'A' + 10),
563        _ => Err(ConnectError::MalformedPairingCode),
564    }
565}
566
567/// How S2 messages travel once a session is initiated.
568///
569/// `s2-connect-common.yml/CommunicationProtocol`. One value today; the enumeration exists
570/// because the specification expects more.
571#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
572#[non_exhaustive]
573pub enum CommunicationProtocol {
574    /// A WebSocket, which is the only transport S2 Connect 1.0.0 defines.
575    WebSocket,
576}
577
578/// The only hash the specification currently allows.
579#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
580#[non_exhaustive]
581pub enum HmacHashingAlgorithm {
582    /// SHA-256, which "**must** be present" in every client's list.
583    #[serde(rename = "SHA256")]
584    Sha256,
585}
586
587/// A challenge and its answer.
588///
589/// The challenge is a nonce of at least 32 random bytes; the answer is
590/// `HMAC(key = challenge, message = token ‖ binding)`. Both sides compute it, and the one
591/// that issued the challenge compares — in constant time.
592#[derive(Debug, Clone, PartialEq, Eq)]
593pub struct ChallengeResponse {
594    bytes: [u8; 32],
595}
596
597impl ChallengeResponse {
598    /// Compute the response to a challenge.
599    ///
600    /// ```
601    /// use s2_kit::connect::proto::{ChallengeResponse, HmacBinding, PairingCode, TokenKind};
602    ///
603    /// let code = PairingCode::parse("A1b2C3", TokenKind::Static)?;
604    /// let challenge = [7u8; 32];
605    /// let binding = HmacBinding::DomainName("pairing.example.com".into());
606    ///
607    /// // Both sides compute the same answer from the same three inputs.
608    /// let theirs = ChallengeResponse::compute(&challenge, &code.token, &binding)?;
609    /// let ours = ChallengeResponse::compute(&challenge, &code.token, &binding)?;
610    /// assert!(ours.verify(theirs.as_base64().as_str()));
611    ///
612    /// // A different binding — a man in the middle with his own certificate — does not.
613    /// let elsewhere = HmacBinding::DomainName("attacker.example.com".into());
614    /// let forged = ChallengeResponse::compute(&challenge, &code.token, &elsewhere)?;
615    /// assert!(!ours.verify(forged.as_base64().as_str()));
616    /// # Ok::<(), s2_kit::connect::proto::ConnectError>(())
617    /// ```
618    pub fn compute(
619        challenge: &[u8],
620        token: &PairingToken,
621        binding: &HmacBinding,
622    ) -> Result<Self, ConnectError> {
623        use hmac::Mac as _;
624        if challenge.len() < 32 {
625            return Err(ConnectError::WeakSecret {
626                got: challenge.len(),
627                need: 32,
628            });
629        }
630        let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::KeyInit>::new_from_slice(challenge)
631            .map_err(|_| ConnectError::ChallengeFailed)?;
632        mac.update(token.as_bytes());
633        mac.update(binding.as_bytes());
634        let out = mac.finalize().into_bytes();
635        let mut bytes = [0u8; 32];
636        bytes.copy_from_slice(&out);
637        Ok(Self { bytes })
638    }
639
640    /// Parse a response received from a peer.
641    pub fn from_base64(encoded: &str) -> Result<Self, ConnectError> {
642        let decoded = base64::engine::general_purpose::STANDARD
643            .decode(encoded)
644            .map_err(|_| ConnectError::ChallengeFailed)?;
645        if decoded.len() != 32 {
646            return Err(ConnectError::ChallengeFailed);
647        }
648        let mut bytes = [0u8; 32];
649        bytes.copy_from_slice(&decoded);
650        Ok(Self { bytes })
651    }
652
653    /// The Base64 form, which is what travels.
654    #[must_use]
655    pub fn as_base64(&self) -> String {
656        base64::engine::general_purpose::STANDARD.encode(self.bytes)
657    }
658
659    /// Whether a peer's answer matches ours, compared in constant time.
660    #[must_use]
661    pub fn verify(&self, theirs: &str) -> bool {
662        use subtle::ConstantTimeEq as _;
663        let Ok(other) = Self::from_base64(theirs) else {
664            return false;
665        };
666        self.bytes.ct_eq(&other.bytes).into()
667    }
668}
669
670pub(crate) fn base64_encode(bytes: &[u8]) -> String {
671    base64::engine::general_purpose::STANDARD.encode(bytes)
672}
673
674pub(crate) fn base64_decode(encoded: &str) -> Option<Vec<u8>> {
675    base64::engine::general_purpose::STANDARD
676        .decode(encoded)
677        .ok()
678}
679
680/// The reconnection delay S2 Connect prescribes.
681///
682/// `S2C §Reconnection strategy`: `delay_n = random(0, min(max_delay, base_delay × 2^n))`,
683/// with a base of two seconds and a maximum of six hundred.
684pub type Backoff = crate::session::Backoff;
685
686/// The DNS-SD service S2 Connect uses.
687pub mod dnssd {
688    use super::{Deployment, Role};
689    use alloc::string::{String, ToString};
690    use alloc::vec::Vec;
691
692    /// `_s2connect`, always over TCP because the protocol is HTTPS.
693    pub const SERVICE_TYPE: &str = "_s2connect";
694    /// The transport the service type is registered under.
695    pub const PROTOCOL: &str = "_tcp";
696    /// The value `txtver` must carry for this version of the specification.
697    pub const TXT_VERSION: &str = "1";
698
699    /// What an endpoint advertises.
700    #[derive(Debug, Clone, Default, PartialEq, Eq)]
701    pub struct ServiceRecord {
702        /// A user-facing name for the endpoint.
703        pub endpoint_name: Option<String>,
704        /// A logo.
705        pub endpoint_logo_url: Option<String>,
706        /// The base URL of the pairing API, including the trailing slash.
707        pub pairing_url: Option<String>,
708        /// The base URL of the long-polling API, for endpoints that host only Resource
709        /// Managers and implement no HTTPS server.
710        pub longpolling_url: Option<String>,
711        /// Which roles this endpoint hosts, as DNS-SD subtypes.
712        pub roles: Vec<Role>,
713    }
714
715    impl ServiceRecord {
716        /// The TXT record, as key–value pairs in the order the specification lists them.
717        ///
718        /// The key is `txtver`, which is what the normative table says and what the only
719        /// other implementation emits — although the avahi example on the same page of
720        /// the specification writes `txtvers` (erratum E7).
721        #[must_use]
722        pub fn txt_pairs(&self) -> Vec<(&'static str, String)> {
723            let mut out = alloc::vec![("txtver", TXT_VERSION.to_string())];
724            if let Some(name) = &self.endpoint_name {
725                out.push(("e_name", name.clone()));
726            }
727            if let Some(logo) = &self.endpoint_logo_url {
728                out.push(("e_logoUrl", logo.clone()));
729            }
730            if let Some(url) = &self.pairing_url {
731                out.push(("pairingUrl", url.clone()));
732            }
733            if let Some(url) = &self.longpolling_url {
734                out.push(("longpollingUrl", url.clone()));
735            }
736            out
737        }
738
739        /// Read a record from a browsed TXT record.
740        ///
741        /// Both spellings of the version key are accepted, because both appear in the
742        /// specification.
743        #[must_use]
744        pub fn from_txt<'a, I>(pairs: I) -> Option<Self>
745        where
746            I: IntoIterator<Item = (&'a str, &'a str)>,
747        {
748            let mut record = Self::default();
749            let mut version_seen = false;
750            for (key, value) in pairs {
751                match key {
752                    "txtver" | "txtvers" => {
753                        if value != TXT_VERSION {
754                            return None;
755                        }
756                        version_seen = true;
757                    }
758                    "e_name" => record.endpoint_name = Some(value.to_string()),
759                    "e_logoUrl" => record.endpoint_logo_url = Some(value.to_string()),
760                    "pairingUrl" => record.pairing_url = Some(value.to_string()),
761                    "longpollingUrl" => record.longpolling_url = Some(value.to_string()),
762                    _ => {}
763                }
764            }
765            // "It is mandatory to provide a value for at least one of the properties
766            // pairingUrl and longpollingUrl."
767            if !version_seen || (record.pairing_url.is_none() && record.longpolling_url.is_none()) {
768                return None;
769            }
770            Some(record)
771        }
772
773        /// Whether this endpoint can be paired with directly, as opposed to only through
774        /// long-polling.
775        #[must_use]
776        pub fn has_pairing_server(&self) -> bool {
777            self.pairing_url.is_some()
778        }
779
780        /// The subtypes to register under.
781        #[must_use]
782        pub fn subtypes(&self) -> Vec<&'static str> {
783            self.roles.iter().map(|r| r.service_subtype()).collect()
784        }
785
786        /// Long-polling is only ever offered by a LAN endpoint.
787        #[must_use]
788        pub fn is_consistent_with(&self, deployment: Deployment) -> bool {
789            self.longpolling_url.is_none() || deployment == Deployment::Lan
790        }
791    }
792}
793
794#[cfg(test)]
795mod tests {
796    use super::*;
797
798    fn token() -> PairingToken {
799        PairingToken::parse("A1b2C3", TokenKind::Static).expect("a legal token")
800    }
801
802    #[test]
803    fn a_pairing_code_splits_at_the_first_dash() {
804        let code = PairingCode::parse("evse7-A1b2C3", TokenKind::Static).unwrap();
805        assert_eq!(code.alias.unwrap().0, "evse7");
806        assert_eq!(code.token.as_bytes(), b"A1b2C3");
807
808        let code = PairingCode::parse("A1b2C3", TokenKind::Static).unwrap();
809        assert!(code.alias.is_none());
810    }
811
812    #[test]
813    fn a_pairing_code_is_checked_before_the_network_is() {
814        // Too short for its kind.
815        assert!(PairingCode::parse("abc", TokenKind::Dynamic).is_err());
816        assert!(PairingCode::parse("abcd", TokenKind::Dynamic).is_ok());
817        assert!(PairingCode::parse("abcde", TokenKind::Static).is_err());
818        assert!(PairingCode::parse("abcdef", TokenKind::Static).is_ok());
819        // Illegal characters.
820        assert!(PairingCode::parse("ab cd", TokenKind::Dynamic).is_err());
821        assert!(PairingCode::parse("ab.cd", TokenKind::Dynamic).is_err());
822        assert!(PairingCode::parse("", TokenKind::Dynamic).is_err());
823        // An empty alias.
824        assert!(PairingCode::parse("-abcd", TokenKind::Dynamic).is_err());
825    }
826
827    #[test]
828    fn everything_an_unauthenticated_peer_chooses_is_bounded() {
829        use alloc::string::ToString;
830
831        // The alias is a field of `requestPairing`, which carries no bearer.
832        assert!(NodeIdAlias::parse(&"a".repeat(NodeIdAlias::MAX_LEN)).is_ok());
833        assert!(NodeIdAlias::parse(&"a".repeat(NodeIdAlias::MAX_LEN + 1)).is_err());
834
835        // And the bound holds on the way *in*, which is the only direction that matters:
836        // a newtype whose `parse` validates and whose `Deserialize` does not is validated
837        // in name only.
838        let long = alloc::format!("\"{}\"", "a".repeat(NodeIdAlias::MAX_LEN + 1));
839        assert!(serde_json::from_str::<NodeIdAlias>(&long).is_err());
840        assert!(serde_json::from_str::<NodeIdAlias>("\"has space\"").is_err());
841        assert!(serde_json::from_str::<NodeIdAlias>("\"\"").is_err());
842        assert_eq!(
843            serde_json::from_str::<NodeIdAlias>("\"hub7\"").unwrap().0,
844            "hub7".to_string()
845        );
846
847        // The token goes into an HMAC, so an unbounded one is unbounded work.
848        let longest = "a".repeat(PairingToken::MAX_LEN);
849        assert!(PairingToken::parse(&longest, TokenKind::Static).is_ok());
850        assert!(PairingToken::parse(&alloc::format!("{longest}a"), TokenKind::Static).is_err());
851        // Which also bounds the pairing code as a whole, both halves of it.
852        assert!(PairingCode::parse(&alloc::format!("hub7-{longest}a"), TokenKind::Static).is_err());
853    }
854
855    #[test]
856    fn a_secret_never_prints_itself() {
857        let code = PairingCode::parse("evse7-SuperSecret", TokenKind::Static).unwrap();
858        let rendered = alloc::format!("{:?}", code.token);
859        assert!(!rendered.contains("SuperSecret"), "{rendered}");
860        let access = AccessToken::new("hunter2");
861        assert_eq!(alloc::format!("{access:?}"), "AccessToken(<redacted>)");
862    }
863
864    #[test]
865    fn a_token_needs_the_entropy_the_specification_demands() {
866        assert!(AccessToken::from_entropy(&[0u8; 31]).is_err());
867        let token = AccessToken::from_entropy(&[0u8; 32]).unwrap();
868        // Base64 of 32 bytes is 44 characters.
869        assert_eq!(token.as_str().len(), 44);
870        assert_eq!(CommunicationToken::lifetime(), Duration::from_secs(30));
871    }
872
873    #[test]
874    fn the_challenge_binds_to_the_server_it_was_answered_by() {
875        let challenge = [9u8; 32];
876        let here = HmacBinding::DomainName("pairing.example.com".into());
877        let there = HmacBinding::DomainName("pairing.example.com.evil.test".into());
878
879        let ours = ChallengeResponse::compute(&challenge, &token(), &here).unwrap();
880        let theirs = ChallengeResponse::compute(&challenge, &token(), &here).unwrap();
881        assert!(ours.verify(&theirs.as_base64()));
882
883        // A man in the middle with his own name gets a different answer, which is the
884        // whole point of binding it.
885        let forged = ChallengeResponse::compute(&challenge, &token(), &there).unwrap();
886        assert!(!ours.verify(&forged.as_base64()));
887
888        // So does the wrong token.
889        let wrong = PairingToken::parse("Z9y8X7", TokenKind::Static).unwrap();
890        let forged = ChallengeResponse::compute(&challenge, &wrong, &here).unwrap();
891        assert!(!ours.verify(&forged.as_base64()));
892    }
893
894    #[test]
895    fn a_short_challenge_is_refused_rather_than_padded() {
896        let binding = HmacBinding::DomainName("x.example".into());
897        assert!(matches!(
898            ChallengeResponse::compute(&[0u8; 31], &token(), &binding),
899            Err(ConnectError::WeakSecret { need: 32, .. })
900        ));
901    }
902
903    #[test]
904    fn a_fingerprint_is_read_with_or_without_colons() {
905        let colons = "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:\
906                      AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99";
907        let plain = colons.replace(':', "");
908        assert_eq!(
909            HmacBinding::from_hex_fingerprint(colons).unwrap(),
910            HmacBinding::from_hex_fingerprint(&plain).unwrap()
911        );
912        // And a fingerprint that is not a SHA-256 is refused.
913        assert!(HmacBinding::from_hex_fingerprint("AABB").is_err());
914        assert!(HmacBinding::from_hex_fingerprint("nonsense").is_err());
915    }
916
917    #[test]
918    fn verification_refuses_anything_that_is_not_a_response() {
919        let ours = ChallengeResponse::compute(
920            &[1u8; 32],
921            &token(),
922            &HmacBinding::DomainName("x.example".into()),
923        )
924        .unwrap();
925        assert!(!ours.verify("not base64 at all !!"));
926        assert!(!ours.verify(""));
927        // Right encoding, wrong length.
928        assert!(!ours.verify(&base64::engine::general_purpose::STANDARD.encode([0u8; 16])));
929    }
930
931    #[test]
932    fn only_a_cem_and_an_rm_may_pair() {
933        assert!(Role::Cem.can_pair_with(Role::Rm));
934        assert!(Role::Rm.can_pair_with(Role::Cem));
935        assert!(!Role::Cem.can_pair_with(Role::Cem));
936        assert!(!Role::Rm.can_pair_with(Role::Rm));
937    }
938
939    #[test]
940    fn the_communication_server_is_the_one_the_standard_names() {
941        use Deployment::{Lan, Wan};
942        // "If a connection is set up between a WAN node and a LAN node, the WAN node must
943        // act as a communication server."
944        assert_eq!(Deployment::communication_server(Wan, Lan), Role::Cem);
945        assert_eq!(Deployment::communication_server(Lan, Wan), Role::Rm);
946        // "If ... both in WAN, or both in LAN ... the CEM must act as a communication
947        // server."
948        assert_eq!(Deployment::communication_server(Wan, Wan), Role::Cem);
949        assert_eq!(Deployment::communication_server(Lan, Lan), Role::Cem);
950    }
951
952    #[test]
953    fn the_dns_sd_record_round_trips_and_accepts_both_spellings() {
954        use dnssd::ServiceRecord;
955        let record = ServiceRecord {
956            endpoint_name: Some("EVSE1038".into()),
957            endpoint_logo_url: None,
958            pairing_url: Some("https://EVSE1038.local:443/pairing/".into()),
959            longpolling_url: None,
960            roles: alloc::vec![Role::Rm],
961        };
962        let pairs = record.txt_pairs();
963        assert_eq!(pairs[0], ("txtver", "1".to_string()));
964        assert_eq!(record.subtypes(), alloc::vec!["_rm"]);
965
966        let borrowed: alloc::vec::Vec<(&str, &str)> =
967            pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
968        let back = ServiceRecord::from_txt(borrowed).unwrap();
969        assert_eq!(back.pairing_url, record.pairing_url);
970
971        // The specification's own avahi example writes `txtvers`; both are accepted (E7).
972        let back =
973            ServiceRecord::from_txt([("txtvers", "1"), ("pairingUrl", "https://x.local/pairing/")])
974                .unwrap();
975        assert!(back.has_pairing_server());
976
977        // A record with neither URL is useless and is refused.
978        assert!(ServiceRecord::from_txt([("txtver", "1")]).is_none());
979        // As is one from a future version of the specification.
980        assert!(ServiceRecord::from_txt([("txtver", "2"), ("pairingUrl", "x")]).is_none());
981    }
982
983    #[test]
984    fn long_polling_is_a_lan_only_arrangement() {
985        use dnssd::ServiceRecord;
986        let record = ServiceRecord {
987            longpolling_url: Some("https://rm.local/pairing/".into()),
988            roles: alloc::vec![Role::Rm],
989            ..ServiceRecord::default()
990        };
991        assert!(record.is_consistent_with(Deployment::Lan));
992        assert!(!record.is_consistent_with(Deployment::Wan));
993    }
994}