Skip to main content

oicp_kit/client/
identity.rs

1//! Mutual TLS, and the local check that turns a production `017` into a startup error.
2
3use crate::transport::OicpError;
4use crate::types::{OperatorId, ProviderId};
5
6/// The client certificate and key Hubject issued for this partner.
7///
8/// # OICP has no tokens
9///
10/// There is no API key, no OAuth, no bearer. Authentication *is* the TLS client certificate, and
11/// authorisation is Hubject comparing the `OperatorID`/`ProviderID` in the URL path against that
12/// certificate:
13///
14/// > *Hubject compares the given Provider- or OperatorID to the partner's SSL client certificate
15/// > information with every web service request. […] If Hubject detects a mismatch […] Hubject
16/// > will not perform the operation and will respond with the status code 017 "Unauthorized
17/// > Access".*
18///
19/// That failure arrives as a `017` on every request, with no indication of which of the two sides
20/// is wrong. [`ClientIdentity::check_against`] does the comparison locally, at startup, and says
21/// which — see [`IdentityWarning`].
22#[derive(Clone)]
23pub struct ClientIdentity {
24    pem: Vec<u8>,
25    subject: Option<String>,
26    sans: Vec<String>,
27}
28
29impl core::fmt::Debug for ClientIdentity {
30    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
31        // Never print the key material.
32        f.debug_struct("ClientIdentity")
33            .field("subject", &self.subject)
34            .field("sans", &self.sans)
35            .finish_non_exhaustive()
36    }
37}
38
39impl ClientIdentity {
40    /// Loads a certificate chain and private key from one PEM buffer.
41    ///
42    /// # Errors
43    ///
44    /// Returns [`OicpError::Transport`] when the buffer holds no certificate, or no private key.
45    pub fn from_pem(pem: impl Into<Vec<u8>>) -> Result<Self, OicpError> {
46        use rustls_pki_types::pem::PemObject as _;
47        use rustls_pki_types::{CertificateDer, PrivateKeyDer};
48
49        let pem = pem.into();
50        let certs: Vec<CertificateDer<'_>> =
51            CertificateDer::pem_slice_iter(&pem).collect::<Result<_, _>>().map_err(|e| {
52                OicpError::transport_from("the client certificate PEM could not be parsed", e)
53            })?;
54        if certs.is_empty() {
55            return Err(OicpError::transport("the PEM buffer holds no certificate"));
56        }
57        // Hubject issues both halves and mutual TLS needs both. A PEM with only the certificate is
58        // the commonest onboarding mistake, and `reqwest` reports it much later and less clearly.
59        PrivateKeyDer::from_pem_slice(&pem).map_err(|_| {
60            OicpError::transport(
61                "the PEM buffer holds a certificate but no private key; OICP needs both for mutual TLS",
62            )
63        })?;
64        let (subject, sans) = extract_names(certs.first().map_or(&[][..], |c| c.as_ref()));
65        Ok(Self { pem, subject, sans })
66    }
67
68    /// Loads a certificate and key from a PEM file.
69    ///
70    /// # Errors
71    ///
72    /// Returns [`OicpError::Transport`] when the file cannot be read or does not hold both parts.
73    pub fn from_pem_file(path: impl AsRef<std::path::Path>) -> Result<Self, OicpError> {
74        let path = path.as_ref();
75        let pem = std::fs::read(path)
76            .map_err(|e| OicpError::transport_from(format!("{} could not be read", path.display()), e))?;
77        Self::from_pem(pem)
78    }
79
80    /// The PEM bytes, for handing to the HTTP client.
81    #[must_use]
82    pub fn pem(&self) -> &[u8] {
83        &self.pem
84    }
85
86    /// The certificate's subject, as far as it could be read.
87    #[must_use]
88    pub fn subject(&self) -> Option<&str> {
89        self.subject.as_deref()
90    }
91
92    /// The subject alternative names, as far as they could be read.
93    #[must_use]
94    pub fn subject_alternative_names(&self) -> &[String] {
95        &self.sans
96    }
97
98    /// Checks that `id` appears somewhere in the certificate's names.
99    ///
100    /// Returns `None` when it does, or when the certificate's names could not be read at all —
101    /// this is a helpful local check, not a security boundary, and refusing to start because a
102    /// certificate encoding was unfamiliar would be worse than useless.
103    #[must_use]
104    pub fn check_against(&self, id: &str) -> Option<IdentityWarning> {
105        if self.subject.is_none() && self.sans.is_empty() {
106            return None;
107        }
108        let needle = canonical(id);
109        let found = core::iter::once(self.subject.as_deref())
110            .flatten()
111            .chain(self.sans.iter().map(String::as_str))
112            .any(|name| canonical(name).contains(&needle));
113        if found {
114            None
115        } else {
116            Some(IdentityWarning {
117                id: id.to_owned(),
118                subject: self.subject.clone(),
119                sans: self.sans.clone(),
120            })
121        }
122    }
123}
124
125/// Strips the separators that make `DE*ABC` and `DEABC` the same operator, and folds case.
126fn canonical(s: &str) -> String {
127    s.bytes().filter(|c| !matches!(c, b'*' | b'-' | b' ')).map(|c| c.to_ascii_uppercase() as char).collect()
128}
129
130/// Pulls the subject CN and the DNS SANs out of a DER certificate.
131///
132/// A deliberately shallow scan rather than a full X.509 parser: this exists to produce a helpful
133/// message, so a certificate it cannot read costs nothing. Bringing an ASN.1 dependency into the
134/// crate for a diagnostic would be the wrong trade.
135fn extract_names(der: &[u8]) -> (Option<String>, Vec<String>) {
136    let mut subject = None;
137    let mut sans = vec![];
138    // Printable/UTF8 strings inside the certificate that look like an OICP identifier.
139    let mut i = 0;
140    while i + 2 < der.len() {
141        let tag = der[i];
142        let len = der[i + 1] as usize;
143        // 0x0c UTF8String, 0x13 PrintableString, 0x16 IA5String — the ones names live in.
144        if matches!(tag, 0x0c | 0x13 | 0x16) && len > 0 && len < 128 && i + 2 + len <= der.len() {
145            if let Ok(text) = core::str::from_utf8(&der[i + 2..i + 2 + len])
146                && text.chars().all(|c| c.is_ascii_graphic() || c == ' ')
147                && text.len() >= 3
148            {
149                if subject.is_none() {
150                    subject = Some(text.to_owned());
151                }
152                sans.push(text.to_owned());
153            }
154            i += 2 + len;
155        } else {
156            i += 1;
157        }
158    }
159    sans.dedup();
160    (subject, sans)
161}
162
163/// The identifier configured does not appear in the client certificate.
164///
165/// Almost certainly [`Code::UnauthorizedAccess`](crate::types::Code::UnauthorizedAccess) waiting to
166/// happen on every request. Reported rather than refused, because a **hub operator** legitimately
167/// acts for bundled sub-partners whose ids are not in its certificate — the spec's hub-partner
168/// chapter — and because a certificate this crate could not fully parse must not stop a partner
169/// from working.
170#[derive(Clone, Debug, PartialEq, Eq)]
171pub struct IdentityWarning {
172    /// The identifier that was configured.
173    pub id: String,
174    /// The certificate's subject, as far as it was read.
175    pub subject: Option<String>,
176    /// The names found in the certificate.
177    pub sans: Vec<String>,
178}
179
180impl core::fmt::Display for IdentityWarning {
181    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
182        write!(
183            f,
184            "the configured identifier {:?} does not appear in the client certificate (names found: {}). \
185             Hubject compares the two on every request and answers a mismatch with 017 Unauthorized \
186             Access. This is legitimate only if you are a hub partner acting for a bundled sub-partner.",
187            self.id,
188            if self.sans.is_empty() { "none".to_owned() } else { self.sans.join(", ") }
189        )
190    }
191}
192
193/// Which party this client acts as, and with which identifier.
194#[derive(Clone, Debug, PartialEq, Eq)]
195pub enum PartyId {
196    /// A Charge Point Operator.
197    Cpo(OperatorId),
198    /// An e-Mobility Provider.
199    Emp(ProviderId),
200}
201
202impl PartyId {
203    /// The identifier as it goes into a URL path.
204    #[must_use]
205    pub fn as_str(&self) -> &str {
206        match self {
207            Self::Cpo(id) => id.as_str(),
208            Self::Emp(id) => id.as_str(),
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn a_pem_without_a_key_is_refused_with_a_useful_message() {
219        let cert_only = b"-----BEGIN CERTIFICATE-----\nMIIBkTCB+w==\n-----END CERTIFICATE-----\n";
220        let err = ClientIdentity::from_pem(cert_only.to_vec()).unwrap_err();
221        assert!(err.to_string().contains("private key"), "{err}");
222    }
223
224    #[test]
225    fn an_empty_pem_is_refused() {
226        let err = ClientIdentity::from_pem(b"not a pem".to_vec()).unwrap_err();
227        assert!(err.to_string().contains("no certificate"), "{err}");
228    }
229
230    #[test]
231    fn identifiers_are_matched_ignoring_separators_and_case() {
232        let identity = ClientIdentity {
233            pem: vec![],
234            subject: Some("DEABC Operator GmbH".into()),
235            sans: vec!["de-abc.example.com".into()],
236        };
237        // The same operator, three spellings.
238        assert!(identity.check_against("DE*ABC").is_none());
239        assert!(identity.check_against("DEABC").is_none());
240        assert!(identity.check_against("de*abc").is_none());
241        // A different one.
242        assert!(identity.check_against("DE*XYZ").is_some());
243    }
244
245    #[test]
246    fn a_mismatch_explains_what_will_happen_and_when_it_is_legitimate() {
247        let identity =
248            ClientIdentity { pem: vec![], subject: Some("DEABC".into()), sans: vec!["DEABC".into()] };
249        let warning = identity.check_against("DE*XYZ").unwrap();
250        let message = warning.to_string();
251        assert!(message.contains("017"));
252        assert!(message.contains("hub partner"));
253    }
254
255    #[test]
256    fn an_unreadable_certificate_produces_no_warning_rather_than_a_wrong_one() {
257        let identity = ClientIdentity { pem: vec![], subject: None, sans: vec![] };
258        assert!(identity.check_against("DE*ABC").is_none());
259    }
260
261    #[test]
262    fn the_debug_output_never_contains_key_material() {
263        let identity = ClientIdentity {
264            pem: b"-----BEGIN PRIVATE KEY-----secret-----END PRIVATE KEY-----".to_vec(),
265            subject: Some("DEABC".into()),
266            sans: vec![],
267        };
268        let debug = format!("{identity:?}");
269        assert!(!debug.contains("secret"));
270        assert!(!debug.contains("PRIVATE"));
271    }
272}