emob_session/auth.rs
1//! How a charging session was authorised.
2//!
3//! Six paths reach the same outcome — a station starts delivering energy — and
4//! they are not interchangeable. Two things depend on which one was used:
5//!
6//! - **AFIR.** A publicly accessible point must offer at least one path that
7//! needs no contract `[AFIR Art. 5(1)]`, and the price on that path carries
8//! no roaming surcharge `[AFIR Art. 5(4)]`.
9//! - **Eichrecht.** The signed record states how strongly the user was
10//! identified `[OCMF Tab. 11]`. A session recorded as recognised by its MAC
11//! address, whose signed record claims a secure feature established the
12//! assignment, is telling two different stories, and
13//! [`AuthPath::strongest_plausible_level`] is what lets the CDR layer notice.
14//!
15//! The comparison runs in **one direction only**, and that is deliberate: the
16//! record over-claiming against the path is a fault, the record under-claiming
17//! is not. A station may omit its identification section, and a chain that did
18//! not hold up reports no identification at all — so treating a weak record as
19//! contradicting a strong path would refuse a session for the crime of having
20//! less evidence than it might have had.
21
22use emob_core::{ContractId, Emaid, IdentificationStrength};
23
24/// The mechanism that authorised a session.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
28#[non_exhaustive]
29pub enum AuthPath {
30 /// The station's own local authorisation list or cache decided.
31 LocalList,
32 /// An `Authorize` went to the e-mobility provider, directly or through a
33 /// roaming hub, and came back affirmative.
34 Roaming,
35 /// No contract at all: a payment card at the point, or a web/QR flow.
36 /// The path AFIR requires every public point to offer.
37 AdHoc,
38 /// ISO 15118 Plug & Charge: the vehicle presented a contract certificate.
39 PlugAndCharge,
40 /// The vehicle was recognised by its MAC address.
41 ///
42 /// Not a standard, not authenticated, and trivially spoofable — it is
43 /// modelled because the field uses it, and kept distinct from
44 /// [`Self::PlugAndCharge`] because the two are constantly conflated in
45 /// marketing and must never be conflated in evidence.
46 AutoCharge,
47 /// A backend command (`RemoteStartTransaction`, `StartSession`) began it.
48 RemoteCommand,
49}
50
51impl AuthPath {
52 /// Whether this path works without the driver holding a contract.
53 ///
54 /// The AFIR Art. 5(1) question, asked of a session rather than of a
55 /// station.
56 #[must_use]
57 pub const fn is_contract_free(self) -> bool {
58 matches!(self, Self::AdHoc)
59 }
60
61 /// Whether the driver was identified cryptographically.
62 #[must_use]
63 pub const fn is_cryptographic(self) -> bool {
64 matches!(self, Self::PlugAndCharge)
65 }
66
67 /// The strongest OCMF identification level this path can honestly support.
68 ///
69 /// Used to cross-check a session against its own signed records: a session
70 /// recorded as [`Self::AutoCharge`] whose record claims `SECURE` is two
71 /// stories about one event, and the one with a signature behind it is not
72 /// the one that can be right — a MAC address off the wire is not a secure
73 /// feature under any reading of `[OCMF Tab. 11]`.
74 ///
75 /// The mapping is deliberately generous — it is a ceiling, not an
76 /// expectation — because a station may under-report and that is not a
77 /// fault. Over-reporting is.
78 ///
79 /// # Read off Tables 13–16, not off the decision
80 ///
81 /// `[OCMF Tab. 11]` grades **how the user was identified**; Tables 13–16
82 /// say which identifications each mechanism can carry. The two axes are
83 /// largely orthogonal, so a ceiling set from *who decided* refuses ordinary
84 /// hardware: a local list decides against an RFID card, and `RFID_PSK`
85 /// `[OCMF Tab. 13]` — a secured card — is Table 11's own example of
86 /// `SECURE`. A backend `Authorize` can answer `OCPP_CERTIFIED`
87 /// `[OCMF Tab. 14]`, which is `CERTIFIED`; so can a remote start.
88 ///
89 /// What stays low is what cannot rise: an unauthenticated MAC address, and
90 /// an ad-hoc session that presented no contract for anything to certify.
91 #[must_use]
92 #[allow(
93 clippy::match_same_arms,
94 reason = "the arms coincide today and hold for different reasons, and each reason \
95 is a different row of OCMF Tables 13–16 that a reviewer has to check; \
96 merging them would delete the argument and make the next change silent"
97 )]
98 pub const fn strongest_plausible_level(self) -> IdentificationStrength {
99 match self {
100 // A contract certificate verified by the station — `ISO15118_PNC`
101 // `[OCMF Tab. 15]`, which is Table 11's other example of `SECURE`.
102 Self::PlugAndCharge => IdentificationStrength::Secure,
103 // An RFID card read locally, which `[OCMF Tab. 13]` grades from
104 // `RFID_PLAIN` up to `RFID_PSK` — a secured card, and `SECURE`.
105 Self::LocalList => IdentificationStrength::Secure,
106 // `OCPP_AUTH`, `OCPP_AUTH_TLS`, `OCPP_CACHE`, `OCPP_WHITELIST` or
107 // `OCPP_CERTIFIED` `[OCMF Tab. 14]`. The last certifies the user
108 // mapping with a backend certificate, which is `CERTIFIED` — but
109 // not `SECURE`, which Table 11 reserves for an assignment the
110 // signature component itself established by a secure feature.
111 Self::Roaming | Self::RemoteCommand => IdentificationStrength::Certified,
112 // A payment instrument or a web flow. There is no contract, so
113 // there is nothing for a certificate to certify and nothing a
114 // secure feature could have established.
115 Self::AdHoc => IdentificationStrength::Trusted,
116 // A MAC address off the wire: not a standard, not authenticated,
117 // trivially spoofable. `PLMN_NONE`-grade evidence at best.
118 Self::AutoCharge => IdentificationStrength::Hearsay,
119 }
120 }
121}
122
123impl core::fmt::Display for AuthPath {
124 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
125 f.write_str(match self {
126 Self::LocalList => "local authorisation list",
127 Self::Roaming => "roaming authorisation",
128 Self::AdHoc => "ad-hoc",
129 Self::PlugAndCharge => "Plug & Charge",
130 Self::AutoCharge => "AutoCharge",
131 Self::RemoteCommand => "remote command",
132 })
133 }
134}
135
136/// Who the session is for.
137///
138/// An ad-hoc session has no contract by construction, which is why this is an
139/// enum rather than an `Option<ContractId>`: "no contract" and "contract not
140/// recorded" are different facts, and only the first one is lawful to bill
141/// against an ad-hoc tariff.
142#[derive(Debug, Clone, PartialEq, Eq)]
143#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
144#[non_exhaustive]
145pub enum Subject {
146 /// A contract at an e-mobility provider.
147 Contract {
148 /// The provider-side contract.
149 id: ContractId,
150 /// The contract identifier the vehicle or token presented, when there
151 /// is one.
152 emaid: Option<Emaid>,
153 },
154 /// A driver with no contract, paying at the point.
155 AdHoc,
156}
157
158impl Subject {
159 /// The contract, if there is one.
160 #[must_use]
161 pub const fn contract_id(&self) -> Option<&ContractId> {
162 match self {
163 Self::Contract { id, .. } => Some(id),
164 Self::AdHoc => None,
165 }
166 }
167}
168
169/// The complete authorisation of a session.
170#[derive(Debug, Clone, PartialEq, Eq)]
171#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
172pub struct Authorization {
173 /// Which mechanism.
174 pub path: AuthPath,
175 /// Who for.
176 pub subject: Subject,
177 /// An opaque, keyed hash of the token that was presented.
178 ///
179 /// Never the RFID UID or the eMAID itself. A UID is a lifelong identifier
180 /// of a physical object a person carries; storing it in every session row
181 /// builds a movement profile that no part of this platform needs.
182 pub token_ref: Option<TokenRef>,
183 /// The provider's authorisation reference, for a roaming session.
184 pub authorization_reference: Option<String>,
185}
186
187impl Authorization {
188 /// An ad-hoc authorisation: no contract, by construction.
189 #[must_use]
190 pub const fn ad_hoc() -> Self {
191 Self {
192 path: AuthPath::AdHoc,
193 subject: Subject::AdHoc,
194 token_ref: None,
195 authorization_reference: None,
196 }
197 }
198
199 /// A Plug & Charge authorisation, off a verified contract certificate.
200 ///
201 /// # Both halves come from the certificate
202 ///
203 /// `emaid` is the identifier `[V2G2-108]` puts in the leaf's Common Name,
204 /// and `emob_pnc::verify_contract` is what reads it there — never a value a
205 /// caller supplied beside the chain. What the caller does supply is the
206 /// **contract** it maps to in this platform's own books, which is a
207 /// commercial fact no certificate carries.
208 ///
209 /// [`Self::token_ref`] is left empty on purpose. An eMAID is a lifelong
210 /// identifier of a person's contract, and the keyed digest that may be
211 /// stored in its place needs a key this crate does not have — see
212 /// [`TokenRef`], and `empd`, which holds it.
213 #[must_use]
214 pub const fn plug_and_charge(id: ContractId, emaid: Emaid) -> Self {
215 Self {
216 path: AuthPath::PlugAndCharge,
217 subject: Subject::Contract {
218 id,
219 emaid: Some(emaid),
220 },
221 token_ref: None,
222 authorization_reference: None,
223 }
224 }
225
226 /// Whether this session may be billed against an ad-hoc tariff.
227 ///
228 /// Both halves have to agree. A session on the ad-hoc *path* that carries a
229 /// contract is a contract session that used a card reader, and billing it
230 /// at the ad-hoc price would be charging a customer twice over.
231 #[must_use]
232 pub fn is_ad_hoc(&self) -> bool {
233 self.path.is_contract_free() && matches!(self.subject, Subject::AdHoc)
234 }
235}
236
237/// An opaque reference to a token, safe to store.
238///
239/// Constructed by hashing the token with a key the platform holds — the
240/// construction itself lives in a service, because it needs the key and this
241/// crate does no I/O. What is enforced here is that the type cannot be built
242/// from something that merely *looks* like a hash: a caller who passes a raw
243/// UID gets a refusal rather than a privacy incident.
244#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
245#[cfg_attr(feature = "serde", derive(serde::Serialize))]
246#[cfg_attr(feature = "serde", serde(transparent))]
247pub struct TokenRef(String);
248
249/// Read back through [`TokenRef::new`], because the refusal is the whole type.
250///
251/// *"A caller who passes a raw UID gets a refusal rather than a privacy
252/// incident"* — and a `#[serde(transparent)]` derive is a caller that never
253/// asked. An RFID UID or an eMAID arriving from a store, an outbox or a
254/// partner's document went straight into the field the platform stores instead
255/// of the driver's identity, which is the incident the type exists to prevent
256/// (D264).
257#[cfg(feature = "serde")]
258impl<'de> serde::Deserialize<'de> for TokenRef {
259 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
260 use serde::de::Error as _;
261 let raw = <std::borrow::Cow<'_, str> as serde::Deserialize>::deserialize(deserializer)?;
262 Self::new(raw.into_owned()).map_err(D::Error::custom)
263 }
264}
265
266impl TokenRef {
267 /// The length a reference must have: 64 lowercase hex characters, i.e. a
268 /// 256-bit digest.
269 pub const HEX_LEN: usize = 64;
270
271 /// Wrap a keyed digest.
272 ///
273 /// # Errors
274 ///
275 /// [`AuthError::NotADigest`] unless the value is exactly 64 lowercase hex
276 /// characters. An RFID UID is 8 or 14 hex characters and an eMAID is 14 or
277 /// 15 alphanumerics, so neither can pass — which is the point.
278 pub fn new(digest_hex: impl Into<String>) -> Result<Self, AuthError> {
279 let value = digest_hex.into();
280 if value.len() != Self::HEX_LEN
281 || !value
282 .bytes()
283 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
284 {
285 return Err(AuthError::NotADigest { len: value.len() });
286 }
287 Ok(Self(value))
288 }
289
290 /// The digest as text.
291 #[must_use]
292 pub fn as_str(&self) -> &str {
293 &self.0
294 }
295}
296
297/// What can be wrong with an authorisation.
298#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
299#[non_exhaustive]
300pub enum AuthError {
301 /// The value is not a 256-bit hex digest — very possibly a raw token.
302 #[error(
303 "a token reference is {} lowercase hex characters (a keyed digest), got {len}; never store a raw UID or eMAID",
304 TokenRef::HEX_LEN
305 )]
306 NotADigest {
307 /// The length that was offered.
308 len: usize,
309 },
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[cfg(feature = "serde")]
317 #[test]
318 fn a_raw_uid_cannot_arrive_as_a_token_reference() {
319 // The refusal is the whole type: *"a caller who passes a raw UID gets a
320 // refusal rather than a privacy incident"* — and a
321 // `#[serde(transparent)]` derive was a caller that never asked (D264).
322 assert!(serde_json::from_str::<TokenRef>("\"04A1B2C3D4E5F6\"").is_err());
323 assert!(serde_json::from_str::<TokenRef>("\"DE-8AA-CA2E4XY9-4\"").is_err());
324 let digest = "a".repeat(TokenRef::HEX_LEN);
325 assert_eq!(
326 serde_json::from_str::<TokenRef>(&format!("\"{digest}\""))
327 .unwrap()
328 .as_str(),
329 digest
330 );
331 }
332
333 #[test]
334 fn only_ad_hoc_is_contract_free() {
335 assert!(AuthPath::AdHoc.is_contract_free());
336 for path in [
337 AuthPath::LocalList,
338 AuthPath::Roaming,
339 AuthPath::PlugAndCharge,
340 AuthPath::AutoCharge,
341 AuthPath::RemoteCommand,
342 ] {
343 assert!(!path.is_contract_free());
344 }
345 }
346
347 #[test]
348 fn autocharge_is_not_plug_and_charge() {
349 // Conflated everywhere in marketing; never in evidence.
350 assert!(AuthPath::PlugAndCharge.is_cryptographic());
351 assert!(!AuthPath::AutoCharge.is_cryptographic());
352 assert!(
353 AuthPath::AutoCharge.strongest_plausible_level() < IdentificationStrength::Trusted,
354 "a MAC address is hearsay"
355 );
356 }
357
358 #[test]
359 fn the_ceiling_is_read_off_the_identification_tables_not_off_the_decision() {
360 // A station's own list decides against an RFID card, and `RFID_PSK`
361 // `[OCMF Tab. 13]` — a secured card — is `[OCMF Tab. 11]`'s own example
362 // of `SECURE`. A ceiling read off "who decided" would put this at
363 // hearsay and refuse every session from a secure-card installation:
364 // exactly the installation that went to the trouble of not being one.
365 assert_eq!(
366 AuthPath::LocalList.strongest_plausible_level(),
367 IdentificationStrength::Secure
368 );
369
370 // `OCPP_CERTIFIED` `[OCMF Tab. 14]` certifies the user mapping with a
371 // backend certificate — `CERTIFIED`, and not `SECURE`, which Table 11
372 // reserves for the signature component's own secure feature.
373 for path in [AuthPath::Roaming, AuthPath::RemoteCommand] {
374 assert_eq!(
375 path.strongest_plausible_level(),
376 IdentificationStrength::Certified,
377 "{path}"
378 );
379 }
380
381 // What stays low is what cannot rise: no contract was presented, so
382 // there is nothing for a certificate to certify.
383 assert_eq!(
384 AuthPath::AdHoc.strongest_plausible_level(),
385 IdentificationStrength::Trusted
386 );
387 assert_eq!(
388 AuthPath::AutoCharge.strongest_plausible_level(),
389 IdentificationStrength::Hearsay
390 );
391 }
392
393 #[test]
394 fn paths_and_strengths_render_as_prose() {
395 assert_eq!(AuthPath::AdHoc.to_string(), "ad-hoc");
396 assert_eq!(AuthPath::PlugAndCharge.to_string(), "Plug & Charge");
397 }
398
399 #[test]
400 fn an_ad_hoc_session_needs_both_halves() {
401 let ad_hoc = Authorization::ad_hoc();
402 assert!(ad_hoc.is_ad_hoc());
403
404 // The ad-hoc path with a contract behind it is a contract session that
405 // happened to use the card reader.
406 let mixed = Authorization {
407 path: AuthPath::AdHoc,
408 subject: Subject::Contract {
409 id: "c-1".parse().unwrap(),
410 emaid: None,
411 },
412 token_ref: None,
413 authorization_reference: None,
414 };
415 assert!(!mixed.is_ad_hoc());
416 }
417
418 #[test]
419 fn a_token_ref_refuses_a_raw_identifier() {
420 // An RFID UID…
421 assert!(TokenRef::new("1F2D3A4F5506C7").is_err());
422 // …an eMAID…
423 assert!(TokenRef::new("NLTNM000122045U").is_err());
424 // …and anything that is not a 256-bit digest.
425 assert!(TokenRef::new("").is_err());
426 assert!(
427 TokenRef::new("A".repeat(64)).is_err(),
428 "uppercase is not the canonical form"
429 );
430
431 let digest = "a".repeat(64);
432 assert_eq!(TokenRef::new(digest.clone()).unwrap().as_str(), digest);
433 }
434
435 #[test]
436 fn the_refusal_says_what_to_do_instead() {
437 let err = TokenRef::new("1F2D3A4F5506C7").unwrap_err();
438 assert!(err.to_string().contains("never store a raw UID"));
439 }
440}