Skip to main content

s2_kit/connect/
tls.rs

1//! The TLS half of S2 Connect, which is where its trust model actually lives.
2//!
3//! # Why this module exists at all
4//!
5//! In a LAN there is no certificate authority. A heat pump discovered over DNS-SD answers
6//! on `https://EVSE1038.local` with a certificate it minted itself, and no amount of
7//! public PKI will ever say anything useful about it. S2 Connect's answer is not to
8//! weaken TLS but to move the authentication somewhere else: the pairing token, which the
9//! end user carried from one device to the other, and which is mixed with the server's
10//! **leaf certificate fingerprint** to produce the challenge response
11//! (`S2C §Challenge response process`).
12//!
13//! That inverts the usual order. The certificate is not trusted and then used; it is used
14//! and then, if the HMAC comes out right, trusted:
15//!
16//! > `S2C §4. HTTPS Client checks clientHmacChallengeResponse`: "in case of a local
17//! > server, the TLS certificate fingerprint is part of the challenge. So if the challenge
18//! > succeeds, the certificate fingerprint is correct, and the certificate can be trusted.
19//! > The client **must** pin the self-signed CA (root) certificate, and trust this
20//! > certificate for the remainder of the pairing relation."
21//!
22//! So exactly one operation in this crate talks to a server whose certificate has not been
23//! verified — LAN pairing — and it is the operation whose whole purpose is to find out
24//! whether that certificate is the right one. Everything afterwards runs against a pinned
25//! CA. [`TlsPolicy`] is that distinction made structural, so a driver cannot accidentally
26//! carry the pairing posture into a session.
27//!
28//! # Two fingerprints that are not the same fingerprint
29//!
30//! The HMAC binds the **leaf**; `ConnectionDetails.certificateFingerprint` pins the **CA**
31//! (erratum E19). They are a paragraph apart in the specification and
32//! named almost identically. Conflating them yields a pairing that verifies and a
33//! connection that does not, so they are different types here: [`Fingerprint`] is carried
34//! by [`CapturedIdentity`] for the first and by [`TlsPolicy::PinnedCa`] for the second.
35
36use alloc::string::String;
37use alloc::sync::Arc;
38// `Vec` comes from the `std` prelude: both features that enable this module imply `std`.
39
40#[cfg(feature = "connect-client")]
41use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
42use rustls::crypto::CryptoProvider;
43#[cfg(feature = "connect-client")]
44use rustls::crypto::{verify_tls12_signature, verify_tls13_signature};
45use rustls::pki_types::CertificateDer;
46#[cfg(feature = "connect-client")]
47use rustls::pki_types::{ServerName, UnixTime};
48#[cfg(feature = "connect-client")]
49use rustls::{DigitallySignedStruct, Error as TlsError, RootCertStore, SignatureScheme};
50
51use super::proto::HmacBinding;
52
53/// A SHA-256 certificate fingerprint: the 32 bytes, not the string.
54///
55/// Kept as bytes because that is what goes into the HMAC. The specification writes them
56/// as hexadecimal, usually with colons, and "must be decoded as hexadecimal string before
57/// it can be used as input" — a step that is easy to skip and produces a response that is
58/// wrong in a way nothing else reports.
59#[derive(Clone, Copy, PartialEq, Eq, Hash)]
60pub struct Fingerprint([u8; 32]);
61
62impl Fingerprint {
63    /// The fingerprint of a DER-encoded certificate.
64    #[must_use]
65    pub fn of(der: &CertificateDer<'_>) -> Self {
66        use sha2::Digest as _;
67        let digest = sha2::Sha256::digest(der.as_ref());
68        let mut bytes = [0u8; 32];
69        bytes.copy_from_slice(&digest);
70        Self(bytes)
71    }
72
73    /// Parse one written as hexadecimal, with or without colons.
74    pub fn parse(hex: &str) -> Result<Self, Error> {
75        match HmacBinding::from_hex_fingerprint(hex)? {
76            HmacBinding::LeafFingerprint(bytes) => {
77                let mut out = [0u8; 32];
78                if bytes.len() != 32 {
79                    return Err(Error::Fingerprint);
80                }
81                out.copy_from_slice(&bytes);
82                Ok(Self(out))
83            }
84            HmacBinding::DomainName(_) => Err(Error::Fingerprint),
85        }
86    }
87
88    /// The bytes.
89    #[must_use]
90    pub const fn as_bytes(&self) -> &[u8; 32] {
91        &self.0
92    }
93
94    /// Lowercase hexadecimal, colon-separated, which is how every tool prints one.
95    #[must_use]
96    pub fn to_hex(&self) -> String {
97        use core::fmt::Write as _;
98        let mut out = String::with_capacity(32 * 3 - 1);
99        for (i, b) in self.0.iter().enumerate() {
100            if i > 0 {
101                out.push(':');
102            }
103            // Writing into a String cannot fail.
104            let _ = write!(out, "{b:02X}");
105        }
106        out
107    }
108
109    /// The HMAC binding this fingerprint makes, for a LAN pairing server.
110    #[must_use]
111    pub fn binding(&self) -> HmacBinding {
112        HmacBinding::LeafFingerprint(self.0.to_vec())
113    }
114
115    /// Whether two fingerprints match, compared in constant time.
116    ///
117    /// A fingerprint is not a secret, but comparing it in constant time costs nothing and
118    /// removes the question.
119    #[must_use]
120    pub fn matches(&self, other: &Self) -> bool {
121        use subtle::ConstantTimeEq as _;
122        self.0.ct_eq(&other.0).into()
123    }
124}
125
126impl core::fmt::Debug for Fingerprint {
127    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
128        write!(f, "Fingerprint({})", self.to_hex())
129    }
130}
131
132impl core::fmt::Display for Fingerprint {
133    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
134        f.write_str(&self.to_hex())
135    }
136}
137
138#[cfg(feature = "connect-client")]
139#[cfg_attr(docsrs, doc(cfg(feature = "connect-client")))]
140/// What a handshake revealed about the server.
141#[derive(Debug, Clone)]
142pub struct CapturedIdentity {
143    /// The leaf certificate's fingerprint — the one the HMAC binds to.
144    pub leaf: Fingerprint,
145    /// The root of the chain the server presented, which is what gets pinned afterwards.
146    ///
147    /// For the usual LAN arrangement — a self-signed CA and one leaf it signed — this is
148    /// the CA. For a server that presented only a leaf, it is that leaf. For one that
149    /// sent a leaf and an intermediate but not its root, it is the intermediate: still
150    /// sound, since that is what signed the leaf the HMAC verified, but it will need
151    /// re-pairing when the intermediate rotates.
152    ///
153    /// Taking it from **this** chain matters. The specification says to pin "the
154    /// self-signed CA (root) certificate" once the challenge succeeds, but the challenge
155    /// binds the *leaf* — so a certificate obtained any other way would be pinned on no
156    /// evidence at all (erratum E22).
157    pub root: CertificateDer<'static>,
158    /// The whole chain, leaf first, for a caller that wants to look at it.
159    pub chain: Vec<CertificateDer<'static>>,
160}
161
162#[cfg(feature = "connect-client")]
163#[cfg_attr(docsrs, doc(cfg(feature = "connect-client")))]
164/// How a connection decides whether to trust the server.
165#[derive(Debug, Clone)]
166pub enum TlsPolicy {
167    /// The public PKI, through the **platform's own trust store**. For WAN endpoints.
168    ///
169    /// Not a bundled root list: a WAN endpoint may well be behind a corporate middlebox
170    /// whose CA the operating system trusts and Mozilla's bundle has never heard of, and
171    /// an administrator who has distributed a root expects it to be used. Revocation and
172    /// local policy come with it for free, which a static list can never provide.
173    Web,
174    /// Exactly one certificate, and nothing else. For every LAN connection after pairing.
175    PinnedCa(CertificateDer<'static>),
176    /// **Trust nothing, record everything.** For LAN *pairing* and nothing else.
177    ///
178    /// The handshake is allowed to succeed against any certificate, because at this point
179    /// in the protocol there is nothing to check it against; the challenge response that
180    /// follows is what decides whether the server was genuine, and it fails closed. See
181    /// the module documentation.
182    ///
183    /// Using this for anything other than the four pairing requests is a security bug: it
184    /// is an unauthenticated channel until the HMAC says otherwise, and the HMAC only says
185    /// anything during pairing.
186    LanPairingOnly,
187}
188
189#[cfg(feature = "connect-client")]
190impl TlsPolicy {
191    /// Whether this policy actually authenticates the peer.
192    #[must_use]
193    pub const fn authenticates(&self) -> bool {
194        !matches!(self, TlsPolicy::LanPairingOnly)
195    }
196}
197
198#[cfg(feature = "connect-client")]
199#[cfg_attr(docsrs, doc(cfg(feature = "connect-client")))]
200/// A `rustls` client configuration, and the identity the handshake captured.
201///
202/// The capture is shared with the verifier, so it fills in during the handshake and is
203/// readable afterwards without threading anything through the HTTP client.
204#[derive(Debug, Clone)]
205pub struct TlsClient {
206    config: Arc<rustls::ClientConfig>,
207    captured: Arc<Capture>,
208}
209
210#[cfg(feature = "connect-client")]
211impl TlsClient {
212    /// Build a client configuration for a policy.
213    pub fn new(policy: &TlsPolicy) -> Result<Self, Error> {
214        let provider = default_provider()?;
215        let captured = Arc::new(Capture::default());
216
217        let builder = rustls::ClientConfig::builder_with_provider(provider.clone())
218            .with_safe_default_protocol_versions()
219            .map_err(|e| Error::Tls(e.to_string()))?;
220
221        let config = match policy {
222            TlsPolicy::Web => {
223                let inner = rustls_platform_verifier::Verifier::new(provider)
224                    .map_err(|e| Error::Tls(e.to_string()))?;
225                builder
226                    .dangerous()
227                    .with_custom_certificate_verifier(Arc::new(Recording {
228                        inner: Verifier::Real(Arc::new(inner)),
229                        captured: captured.clone(),
230                    }))
231                    .with_no_client_auth()
232            }
233            TlsPolicy::PinnedCa(ca) => {
234                let mut roots = RootCertStore::empty();
235                roots
236                    .add(ca.clone())
237                    .map_err(|e| Error::Tls(e.to_string()))?;
238                let inner = rustls::client::WebPkiServerVerifier::builder_with_provider(
239                    Arc::new(roots),
240                    provider,
241                )
242                .build()
243                .map_err(|e| Error::Tls(e.to_string()))?;
244                builder
245                    .dangerous()
246                    .with_custom_certificate_verifier(Arc::new(Recording {
247                        inner: Verifier::Real(inner),
248                        captured: captured.clone(),
249                    }))
250                    .with_no_client_auth()
251            }
252            TlsPolicy::LanPairingOnly => builder
253                .dangerous()
254                .with_custom_certificate_verifier(Arc::new(Recording {
255                    inner: Verifier::AcceptAnything(provider),
256                    captured: captured.clone(),
257                }))
258                .with_no_client_auth(),
259        };
260
261        Ok(Self {
262            config: Arc::new(config),
263            captured,
264        })
265    }
266
267    /// The configuration, to hand to `reqwest` or `tokio-rustls`.
268    #[must_use]
269    pub fn config(&self) -> Arc<rustls::ClientConfig> {
270        self.config.clone()
271    }
272
273    /// What the last handshake revealed, if one has happened.
274    #[must_use]
275    pub fn captured(&self) -> Option<CapturedIdentity> {
276        self.captured.get()
277    }
278
279    /// The leaf fingerprint the last handshake presented, as an HMAC binding.
280    ///
281    /// This is the `F` of `R = HMAC(C, T ‖ F)`, and it is available only after a request
282    /// has actually been made — which is why a pairing driver does the first request
283    /// before it can check anything.
284    #[must_use]
285    pub fn binding(&self) -> Option<HmacBinding> {
286        self.captured.get().map(|c| c.leaf.binding())
287    }
288
289    /// Whether every handshake so far presented the same leaf.
290    ///
291    /// A LAN pairing runs four requests against a connection pool. If the fingerprint
292    /// changes between them, something has moved underneath us and the attempt must not
293    /// continue — the HMAC was computed against a certificate that is no longer the one
294    /// answering.
295    #[must_use]
296    pub fn identity_is_stable(&self) -> bool {
297        !self.captured.changed()
298    }
299}
300
301#[cfg(feature = "connect-client")]
302#[cfg_attr(docsrs, doc(cfg(feature = "connect-client")))]
303#[derive(Debug, Default)]
304struct Capture {
305    inner: std::sync::Mutex<Option<CapturedIdentity>>,
306    changed: core::sync::atomic::AtomicBool,
307}
308
309#[cfg(feature = "connect-client")]
310impl Capture {
311    fn set(&self, identity: CapturedIdentity) {
312        let Ok(mut slot) = self.inner.lock() else {
313            // A poisoned lock means another thread panicked mid-capture. Treat the
314            // identity as unstable rather than pretending we know it.
315            self.changed
316                .store(true, core::sync::atomic::Ordering::Relaxed);
317            return;
318        };
319        if let Some(previous) = slot.as_ref()
320            && !previous.leaf.matches(&identity.leaf)
321        {
322            self.changed
323                .store(true, core::sync::atomic::Ordering::Relaxed);
324        }
325        *slot = Some(identity);
326    }
327
328    fn get(&self) -> Option<CapturedIdentity> {
329        self.inner.lock().ok()?.clone()
330    }
331
332    fn changed(&self) -> bool {
333        self.changed.load(core::sync::atomic::Ordering::Relaxed)
334    }
335}
336
337#[cfg(feature = "connect-client")]
338#[cfg_attr(docsrs, doc(cfg(feature = "connect-client")))]
339#[derive(Debug)]
340enum Verifier {
341    Real(Arc<dyn ServerCertVerifier>),
342    AcceptAnything(Arc<CryptoProvider>),
343}
344
345#[cfg(feature = "connect-client")]
346#[cfg_attr(docsrs, doc(cfg(feature = "connect-client")))]
347/// Wraps a verifier so that the chain is recorded whatever the verdict.
348#[derive(Debug)]
349struct Recording {
350    inner: Verifier,
351    captured: Arc<Capture>,
352}
353
354#[cfg(feature = "connect-client")]
355impl ServerCertVerifier for Recording {
356    fn verify_server_cert(
357        &self,
358        end_entity: &CertificateDer<'_>,
359        intermediates: &[CertificateDer<'_>],
360        server_name: &ServerName<'_>,
361        ocsp_response: &[u8],
362        now: UnixTime,
363    ) -> Result<ServerCertVerified, TlsError> {
364        let leaf = end_entity.clone().into_owned();
365        let mut chain = alloc::vec![leaf.clone()];
366        chain.extend(intermediates.iter().map(|c| c.clone().into_owned()));
367        // Record before verifying: a driver that wants to report *which* certificate was
368        // refused needs it even when the verdict is no. A server that sent only a leaf
369        // roots at that leaf, which is what a self-signed single certificate means.
370        self.captured.set(CapturedIdentity {
371            leaf: Fingerprint::of(end_entity),
372            root: chain.last().cloned().unwrap_or(leaf),
373            chain,
374        });
375
376        match &self.inner {
377            Verifier::Real(inner) => {
378                inner.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
379            }
380            // The whole point: no trust anchor exists yet, and the HMAC that follows is
381            // what decides. See `TlsPolicy::LanPairingOnly`.
382            Verifier::AcceptAnything(_) => Ok(ServerCertVerified::assertion()),
383        }
384    }
385
386    fn verify_tls12_signature(
387        &self,
388        message: &[u8],
389        cert: &CertificateDer<'_>,
390        dss: &DigitallySignedStruct,
391    ) -> Result<HandshakeSignatureValid, TlsError> {
392        match &self.inner {
393            Verifier::Real(inner) => inner.verify_tls12_signature(message, cert, dss),
394            // Still a real signature check: an attacker must at least hold the key for
395            // the certificate he presented, so he cannot replay somebody else's.
396            Verifier::AcceptAnything(provider) => verify_tls12_signature(
397                message,
398                cert,
399                dss,
400                &provider.signature_verification_algorithms,
401            ),
402        }
403    }
404
405    fn verify_tls13_signature(
406        &self,
407        message: &[u8],
408        cert: &CertificateDer<'_>,
409        dss: &DigitallySignedStruct,
410    ) -> Result<HandshakeSignatureValid, TlsError> {
411        match &self.inner {
412            Verifier::Real(inner) => inner.verify_tls13_signature(message, cert, dss),
413            Verifier::AcceptAnything(provider) => verify_tls13_signature(
414                message,
415                cert,
416                dss,
417                &provider.signature_verification_algorithms,
418            ),
419        }
420    }
421
422    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
423        match &self.inner {
424            Verifier::Real(inner) => inner.supported_verify_schemes(),
425            Verifier::AcceptAnything(provider) => provider
426                .signature_verification_algorithms
427                .supported_schemes(),
428        }
429    }
430}
431
432/// The crypto provider, installed if the process has not installed one.
433///
434/// `rustls` requires a process-wide default before any configuration can be built and
435/// panics if two are installed. Doing it here, once, keeps that out of every consumer's
436/// `main`.
437pub fn default_provider() -> Result<Arc<CryptoProvider>, Error> {
438    // The application's choice always wins. A library that installs a provider over one
439    // the application already chose would give it two crypto stacks and silently use the
440    // wrong one; `install_default` also panics on a second call, which is why this is a
441    // read first and a write second.
442    if let Some(provider) = CryptoProvider::get_default() {
443        return Ok(provider.clone());
444    }
445
446    // Otherwise fall back to whichever this build bundled. `aws-lc-rs` wins when both are
447    // enabled, because a build that went to the trouble of asking for it wanted it.
448    #[cfg(feature = "tls-aws-lc-rs")]
449    let bundled = Some(rustls::crypto::aws_lc_rs::default_provider());
450    #[cfg(all(feature = "tls-ring", not(feature = "tls-aws-lc-rs")))]
451    let bundled = Some(rustls::crypto::ring::default_provider());
452    #[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
453    let bundled: Option<CryptoProvider> = None;
454
455    let Some(provider) = bundled else {
456        return Err(Error::Tls(
457            "no TLS crypto provider: build with the `tls-ring` or `tls-aws-lc-rs` feature, \
458             or install one yourself with rustls::crypto::CryptoProvider::install_default"
459                .to_string(),
460        ));
461    };
462    // Racing with another thread is fine: whoever wins, we read back the winner.
463    let _ = provider.install_default();
464    CryptoProvider::get_default()
465        .cloned()
466        .ok_or_else(|| Error::Tls("no crypto provider could be installed".to_string()))
467}
468
469/// A self-signed CA and the leaf it signed: what a LAN endpoint needs to serve HTTPS.
470///
471/// S2 Connect expects LAN endpoints to mint their own, because there is no authority that
472/// could issue a certificate for `EVSE1038.local`. The pairing HMAC is what makes that
473/// safe, so generating one is not a shortcut — it is the specified arrangement.
474/// Minting a key pair needs a cryptography backend, so this type exists only when one is
475/// compiled in — `tls-ring` (the default) or `tls-aws-lc-rs`. An application that installs
476/// its own `rustls` provider and brings its own certificates does not need it.
477#[cfg(all(
478    feature = "connect-server",
479    any(feature = "tls-ring", feature = "tls-aws-lc-rs")
480))]
481#[cfg_attr(
482    docsrs,
483    doc(cfg(all(
484        feature = "connect-server",
485        any(feature = "tls-ring", feature = "tls-aws-lc-rs")
486    )))
487)]
488#[derive(Debug)]
489pub struct SelfSignedEndpoint {
490    /// The CA certificate, which a paired client pins.
491    pub ca: CertificateDer<'static>,
492    /// The chain to serve: leaf first, then the CA.
493    pub chain: Vec<CertificateDer<'static>>,
494    /// The leaf's private key.
495    pub key: rustls::pki_types::PrivateKeyDer<'static>,
496    /// The leaf's fingerprint — the `F` of the challenge response.
497    pub leaf: Fingerprint,
498}
499
500#[cfg(all(
501    feature = "connect-server",
502    any(feature = "tls-ring", feature = "tls-aws-lc-rs")
503))]
504impl SelfSignedEndpoint {
505    /// Mint a CA and a leaf valid for the given names.
506    ///
507    /// Names are whatever a client will dial: `EVSE1038.local`, `127.0.0.1`, an IPv6
508    /// literal. A name the certificate does not carry will fail once the client has
509    /// pinned the CA, even though it passed during pairing — which is a confusing failure
510    /// to debug later, so pass every name the endpoint answers on.
511    pub fn generate(names: impl IntoIterator<Item = String>) -> Result<Self, Error> {
512        use rcgen::{
513            BasicConstraints, CertificateParams, DnType, IsCa, KeyPair, KeyUsagePurpose, SanType,
514        };
515
516        let names: Vec<String> = names.into_iter().collect();
517        let Some(primary) = names.first().cloned() else {
518            return Err(Error::Tls(
519                "a certificate needs at least one name".to_string(),
520            ));
521        };
522
523        let ca_key = KeyPair::generate().map_err(|e| Error::Tls(e.to_string()))?;
524        let mut ca_params = CertificateParams::default();
525        ca_params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
526        ca_params.key_usages = alloc::vec![
527            KeyUsagePurpose::KeyCertSign,
528            KeyUsagePurpose::CrlSign,
529            KeyUsagePurpose::DigitalSignature,
530        ];
531        ca_params
532            .distinguished_name
533            .push(DnType::CommonName, "s2-kit LAN endpoint CA");
534        let ca_cert = ca_params
535            .self_signed(&ca_key)
536            .map_err(|e| Error::Tls(e.to_string()))?;
537
538        let leaf_key = KeyPair::generate().map_err(|e| Error::Tls(e.to_string()))?;
539        let mut leaf_params = CertificateParams::default();
540        leaf_params
541            .distinguished_name
542            .push(DnType::CommonName, primary);
543        for name in &names {
544            let san = match name.parse::<core::net::IpAddr>() {
545                Ok(ip) => SanType::IpAddress(ip),
546                Err(_) => SanType::DnsName(
547                    name.clone()
548                        .try_into()
549                        .map_err(|_| Error::Tls(alloc::format!("{name} is not a usable name")))?,
550                ),
551            };
552            leaf_params.subject_alt_names.push(san);
553        }
554        let issuer = rcgen::Issuer::new(ca_params, ca_key);
555        let leaf_cert = leaf_params
556            .signed_by(&leaf_key, &issuer)
557            .map_err(|e| Error::Tls(e.to_string()))?;
558
559        let leaf_der = leaf_cert.der().clone();
560        let ca_der = ca_cert.der().clone();
561        Ok(Self {
562            leaf: Fingerprint::of(&leaf_der),
563            chain: alloc::vec![leaf_der, ca_der.clone()],
564            ca: ca_der,
565            key: rustls::pki_types::PrivateKeyDer::Pkcs8(leaf_key.serialize_der().into()),
566        })
567    }
568
569    /// A `rustls` server configuration serving this chain.
570    pub fn server_config(&self) -> Result<Arc<rustls::ServerConfig>, Error> {
571        let provider = default_provider()?;
572        let config = rustls::ServerConfig::builder_with_provider(provider)
573            .with_safe_default_protocol_versions()
574            .map_err(|e| Error::Tls(e.to_string()))?
575            .with_no_client_auth()
576            .with_single_cert(self.chain.clone(), self.key.clone_key())
577            .map_err(|e| Error::Tls(e.to_string()))?;
578        Ok(Arc::new(config))
579    }
580}
581
582/// Something went wrong setting up or inspecting TLS.
583#[derive(Debug, thiserror::Error)]
584#[non_exhaustive]
585pub enum Error {
586    /// The fingerprint is not 32 bytes of hexadecimal.
587    #[error("not a SHA-256 certificate fingerprint")]
588    Fingerprint,
589    /// `rustls` refused the configuration, or no provider could be installed.
590    #[error("TLS: {0}")]
591    Tls(String),
592}
593
594impl From<super::proto::ConnectError> for Error {
595    fn from(_: super::proto::ConnectError) -> Self {
596        Error::Fingerprint
597    }
598}
599
600use alloc::string::ToString as _;
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605
606    #[test]
607    fn a_fingerprint_round_trips_through_the_form_tools_print() {
608        let der = CertificateDer::from(alloc::vec![1u8, 2, 3, 4]);
609        let fp = Fingerprint::of(&der);
610        let text = fp.to_hex();
611        assert_eq!(text.len(), 32 * 3 - 1, "32 bytes, colon-separated");
612        assert_eq!(Fingerprint::parse(&text).unwrap(), fp);
613        // And without the colons, which is the other way tools print them.
614        assert_eq!(Fingerprint::parse(&text.replace(':', "")).unwrap(), fp);
615        assert!(fp.matches(&Fingerprint::of(&der)));
616    }
617
618    #[test]
619    fn a_fingerprint_is_the_binding_the_hmac_takes() {
620        let der = CertificateDer::from(alloc::vec![9u8; 64]);
621        let fp = Fingerprint::of(&der);
622        let HmacBinding::LeafFingerprint(bytes) = fp.binding() else {
623            panic!("a leaf fingerprint binds as a leaf fingerprint");
624        };
625        // Not the hex string: "must be decoded as hexadecimal string before it can be
626        // used as input".
627        assert_eq!(bytes.len(), 32);
628        assert_eq!(&bytes[..], fp.as_bytes());
629    }
630
631    #[test]
632    fn something_that_is_not_a_fingerprint_is_refused() {
633        assert!(Fingerprint::parse("").is_err());
634        assert!(Fingerprint::parse("AA:BB").is_err());
635        assert!(Fingerprint::parse("not hexadecimal at all").is_err());
636        // The right length of the wrong thing.
637        assert!(Fingerprint::parse(&"zz".repeat(32)).is_err());
638    }
639
640    #[cfg(feature = "connect-client")]
641    #[test]
642    fn only_one_policy_declines_to_authenticate_and_it_says_so() {
643        assert!(TlsPolicy::Web.authenticates());
644        assert!(!TlsPolicy::LanPairingOnly.authenticates());
645        let der = CertificateDer::from(alloc::vec![1u8, 2, 3]);
646        assert!(TlsPolicy::PinnedCa(der).authenticates());
647    }
648
649    #[cfg(feature = "connect-client")]
650    #[test]
651    fn every_policy_builds_a_usable_configuration() {
652        assert!(TlsClient::new(&TlsPolicy::Web).is_ok());
653        assert!(TlsClient::new(&TlsPolicy::LanPairingOnly).is_ok());
654        // Nothing has been captured before a handshake, which is why a pairing driver
655        // must make its first request before it can check anything.
656        let client = TlsClient::new(&TlsPolicy::LanPairingOnly).unwrap();
657        assert!(client.captured().is_none());
658        assert!(client.binding().is_none());
659        assert!(client.identity_is_stable());
660    }
661
662    #[cfg(feature = "connect-client")]
663    #[test]
664    fn a_pinned_policy_refuses_something_that_is_not_a_certificate() {
665        let nonsense = CertificateDer::from(alloc::vec![0u8; 8]);
666        assert!(TlsClient::new(&TlsPolicy::PinnedCa(nonsense)).is_err());
667    }
668
669    #[cfg(feature = "connect-client")]
670    #[test]
671    fn a_changed_leaf_mid_attempt_is_noticed() {
672        let capture = Capture::default();
673        let one = CertificateDer::from(alloc::vec![1u8; 32]);
674        let two = CertificateDer::from(alloc::vec![2u8; 32]);
675        let identity = |der: &CertificateDer<'static>| CapturedIdentity {
676            leaf: Fingerprint::of(der),
677            root: der.clone(),
678            chain: alloc::vec![der.clone()],
679        };
680        capture.set(identity(&one));
681        assert!(!capture.changed());
682        capture.set(identity(&one));
683        assert!(!capture.changed(), "the same certificate twice is fine");
684        capture.set(identity(&two));
685        assert!(capture.changed(), "a different one is not");
686    }
687
688    #[cfg(feature = "connect-server")]
689    #[test]
690    fn a_lan_endpoint_can_mint_the_certificate_the_specification_expects() {
691        let endpoint =
692            SelfSignedEndpoint::generate(["EVSE1038.local".to_string(), "127.0.0.1".to_string()])
693                .expect("a self-signed CA and leaf");
694
695        // Leaf first, then the CA it was signed by — the order a server sends them.
696        assert_eq!(endpoint.chain.len(), 2);
697        assert_eq!(endpoint.chain[1], endpoint.ca);
698        // The fingerprint the HMAC binds to is the leaf's, not the CA's.
699        assert_eq!(endpoint.leaf, Fingerprint::of(&endpoint.chain[0]));
700        assert_ne!(endpoint.leaf, Fingerprint::of(&endpoint.ca));
701        assert!(endpoint.server_config().is_ok());
702
703        // A client that pins this CA builds.
704        #[cfg(feature = "connect-client")]
705        assert!(TlsClient::new(&TlsPolicy::PinnedCa(endpoint.ca.clone())).is_ok());
706    }
707
708    #[cfg(feature = "connect-server")]
709    #[test]
710    fn a_certificate_needs_a_name() {
711        assert!(SelfSignedEndpoint::generate([]).is_err());
712    }
713}