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