Skip to main content

ocpp_kit/
credentials.rs

1//! The rules a Charging Station's HTTP Basic password must follow, per version.
2//!
3//! Pure checks with no dependencies, so the station blocks can refuse a credential they could
4//! not present without pulling in the transport. The password type itself, which zeroizes and
5//! generates, is [`transport::BasicAuthPassword`](crate::transport) (feature `tokio`).
6//!
7//! * **1.6** `AuthorizationKey`: "Minimal 16-bytes long … Hexadecimal represented (20 bytes
8//!   maximum, represented as a string of up to 40 hexadecimal digits)" (1.6 Security
9//!   Whitepaper ed. 4, A00.FR.205). The decoded octets are the password.
10//! * **2.x** `BasicAuthPassword`: "a randomly chosen passwordString … consisting of minimum 16
11//!   and a maximum as defined by the maxLimit of configuration variable `BasicAuthPassword`,
12//!   which must be at least 40 characters and at most 64" (A00.FR.205), where `passwordString`
13//!   "can only contain characters from the following character set: a-z, A-Z, 0-9, '*', '-',
14//!   '_', '=', ':', '+', '|', '@', '.'" (Part 2 §2.1.4, primitive datatypes).
15//!
16//! ```
17//! use ocpp_kit::credentials::{self, CredentialError};
18//!
19//! assert!(credentials::check_password("a-sixteen-char-pw", 40).is_ok());
20//! assert_eq!(
21//!     credentials::check_password("sixteen-chars-ok!", 40),
22//!     Err(CredentialError::Character('!'))
23//! );
24//! assert_eq!(credentials::authorization_key_octets("00112233445566778899AABBCCDDEEFF")?.len(), 16);
25//! # Ok::<(), CredentialError>(())
26//! ```
27
28use alloc::vec::Vec;
29use core::fmt;
30
31/// The shortest `BasicAuthPassword` OCPP 2.x allows (A00.FR.205).
32pub const BASIC_AUTH_MIN_LEN: usize = 16;
33
34/// The longest `BasicAuthPassword` OCPP 2.x can define.
35///
36/// A00.FR.205 does not name a single maximum: it says the ceiling is the `maxLimit` of the
37/// `BasicAuthPassword` variable, "which must be at least 40 characters and at most 64". 40 is
38/// therefore the shortest maximum a CSMS may impose — the *floor* of the ceiling — and 64 is
39/// the longest password the specification can ever describe. This constant is the latter,
40/// because refusing a 48-character password an operator legitimately configured would be a
41/// bug in this crate, not a conformance win.
42pub const BASIC_AUTH_MAX_LEN: usize = 64;
43
44/// The smallest `maxLimit` a CSMS may configure for `BasicAuthPassword` (A00.FR.205).
45///
46/// A Charging Station that must interoperate with any CSMS should stay at or below this; it is
47/// also the length of a generated 2.x password.
48pub const BASIC_AUTH_INTEROPERABLE_MAX_LEN: usize = 40;
49
50/// The shortest 1.6 `AuthorizationKey`, in octets (Security Whitepaper A00.FR.205).
51pub const AUTHORIZATION_KEY_MIN_BYTES: usize = 16;
52
53/// The longest 1.6 `AuthorizationKey`, in octets (Security Whitepaper A00.FR.205).
54pub const AUTHORIZATION_KEY_MAX_BYTES: usize = 20;
55
56/// Every character a 2.x `passwordString` may contain (Part 2 §2.1.4), 71 in all.
57pub const PASSWORD_STRING_CHARSET: &[u8; 71] =
58    b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*-_=:+|@.";
59
60/// Why a credential was rejected.
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62#[non_exhaustive]
63pub enum CredentialError {
64    /// The password is shorter than [`BASIC_AUTH_MIN_LEN`] or longer than the maximum in force
65    /// (A00.FR.205).
66    PasswordLength(usize),
67    /// The password contains a character outside [`PASSWORD_STRING_CHARSET`] — the first one.
68    Character(char),
69    /// The 1.6 `AuthorizationKey` is not a hexadecimal string.
70    NotHex,
71    /// The 1.6 `AuthorizationKey` decodes to fewer than [`AUTHORIZATION_KEY_MIN_BYTES`] or
72    /// more than [`AUTHORIZATION_KEY_MAX_BYTES`] octets (1.6 Security Whitepaper A00.FR.205).
73    KeyLength(usize),
74    /// The operating system's entropy source failed, so no password was generated.
75    Entropy,
76}
77
78impl fmt::Display for CredentialError {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            CredentialError::PasswordLength(len) => write!(
82                f,
83                "BasicAuthPassword is {len} characters; OCPP 2.x allows {BASIC_AUTH_MIN_LEN} to the \
84                 variable's maxLimit, at most {BASIC_AUTH_MAX_LEN} (A00.FR.205)"
85            ),
86            CredentialError::Character(c) => write!(
87                f,
88                "BasicAuthPassword contains {c:?}; a passwordString allows only a-z, A-Z, 0-9 and * - _ = : + | @ ."
89            ),
90            CredentialError::NotHex => {
91                f.write_str("the 1.6 AuthorizationKey must be an even-length hexadecimal string")
92            }
93            CredentialError::KeyLength(len) => write!(
94                f,
95                "the 1.6 AuthorizationKey is {len} bytes; it must be \
96                 {AUTHORIZATION_KEY_MIN_BYTES}–{AUTHORIZATION_KEY_MAX_BYTES} (A00.FR.205)"
97            ),
98            CredentialError::Entropy => f.write_str("the operating system's entropy source failed"),
99        }
100    }
101}
102
103impl core::error::Error for CredentialError {}
104
105/// Checks a 2.x `BasicAuthPassword`: [`BASIC_AUTH_MIN_LEN`]`..=max_len` characters, every one a
106/// `passwordString` character.
107///
108/// `max_len` is the `maxLimit` in force — the variable's, on a station; [`BASIC_AUTH_MAX_LEN`]
109/// when the caller does not know it.
110pub fn check_password(text: &str, max_len: usize) -> Result<(), CredentialError> {
111    if let Some(c) = text
112        .chars()
113        .find(|c| !c.is_ascii() || !PASSWORD_STRING_CHARSET.contains(&(*c as u8)))
114    {
115        return Err(CredentialError::Character(c));
116    }
117    // ASCII only from here, so bytes are characters.
118    if !(BASIC_AUTH_MIN_LEN..=max_len).contains(&text.len()) {
119        return Err(CredentialError::PasswordLength(text.len()));
120    }
121    Ok(())
122}
123
124/// Decodes a 1.6 `AuthorizationKey` into the password octets: hexadecimal (either case,
125/// surrounding whitespace ignored), [`AUTHORIZATION_KEY_MIN_BYTES`] to
126/// [`AUTHORIZATION_KEY_MAX_BYTES`] octets.
127pub fn authorization_key_octets(hex: &str) -> Result<Vec<u8>, CredentialError> {
128    let text = hex.trim().as_bytes();
129    if text.is_empty() || !text.len().is_multiple_of(2) {
130        return Err(CredentialError::NotHex);
131    }
132    let bytes = text
133        .chunks(2)
134        .map(|pair| Some(nibble(pair[0])? << 4 | nibble(pair[1])?))
135        .collect::<Option<Vec<u8>>>()
136        .ok_or(CredentialError::NotHex)?;
137    if !(AUTHORIZATION_KEY_MIN_BYTES..=AUTHORIZATION_KEY_MAX_BYTES).contains(&bytes.len()) {
138        return Err(CredentialError::KeyLength(bytes.len()));
139    }
140    Ok(bytes)
141}
142
143const fn nibble(digit: u8) -> Option<u8> {
144    match digit {
145        b'0'..=b'9' => Some(digit - b'0'),
146        b'a'..=b'f' => Some(digit - b'a' + 10),
147        b'A'..=b'F' => Some(digit - b'A' + 10),
148        _ => None,
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn the_charset_is_the_one_part_2_lists() {
158        assert_eq!(PASSWORD_STRING_CHARSET.len(), 71);
159        let mut sorted = PASSWORD_STRING_CHARSET.to_vec();
160        sorted.sort_unstable();
161        sorted.dedup();
162        assert_eq!(sorted.len(), 71, "no duplicates");
163        for c in b"*-_=:+|@." {
164            assert!(PASSWORD_STRING_CHARSET.contains(c));
165        }
166    }
167
168    #[test]
169    fn a_password_is_a_password_string_of_16_to_the_limit() {
170        assert!(check_password(&"a".repeat(16), 40).is_ok());
171        assert!(check_password(&"Z9*-_=:+|@.".repeat(4)[..40], 40).is_ok());
172        assert_eq!(
173            check_password(&"a".repeat(15), 40),
174            Err(CredentialError::PasswordLength(15))
175        );
176        assert_eq!(
177            check_password(&"a".repeat(41), 40),
178            Err(CredentialError::PasswordLength(41))
179        );
180        assert!(check_password(&"a".repeat(64), BASIC_AUTH_MAX_LEN).is_ok());
181        // The first offender is named, even before the length is checked.
182        assert_eq!(
183            check_password("short!", 40),
184            Err(CredentialError::Character('!'))
185        );
186        assert_eq!(
187            check_password("sixteen chars ok", 40),
188            Err(CredentialError::Character(' '))
189        );
190        assert_eq!(
191            check_password("sixteen-chars-ü-ok", 40),
192            Err(CredentialError::Character('ü'))
193        );
194    }
195
196    #[test]
197    fn an_authorization_key_is_16_to_20_octets_of_hex() {
198        assert_eq!(
199            authorization_key_octets("000102030405060708090a0b0c0d0E0F").unwrap(),
200            (0..16).collect::<Vec<u8>>()
201        );
202        assert_eq!(
203            authorization_key_octets(" 00112233445566778899aabbccddeeff\n")
204                .unwrap()
205                .len(),
206            16
207        );
208        assert_eq!(authorization_key_octets("zz"), Err(CredentialError::NotHex));
209        assert_eq!(
210            authorization_key_octets("abc"),
211            Err(CredentialError::NotHex)
212        );
213        assert_eq!(authorization_key_octets(""), Err(CredentialError::NotHex));
214        assert_eq!(
215            authorization_key_octets(&"ab".repeat(15)),
216            Err(CredentialError::KeyLength(15))
217        );
218        assert_eq!(
219            authorization_key_octets(&"ab".repeat(21)),
220            Err(CredentialError::KeyLength(21))
221        );
222        assert!(authorization_key_octets(&"ab".repeat(20)).is_ok());
223        // Not hex even though it is ASCII and of even length.
224        assert_eq!(
225            authorization_key_octets(&"0g".repeat(16)),
226            Err(CredentialError::NotHex)
227        );
228    }
229}