use alloc::vec::Vec;
use core::fmt;
pub const BASIC_AUTH_MIN_LEN: usize = 16;
pub const BASIC_AUTH_MAX_LEN: usize = 64;
pub const BASIC_AUTH_INTEROPERABLE_MAX_LEN: usize = 40;
pub const AUTHORIZATION_KEY_MIN_BYTES: usize = 16;
pub const AUTHORIZATION_KEY_MAX_BYTES: usize = 20;
pub const PASSWORD_STRING_CHARSET: &[u8; 71] =
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*-_=:+|@.";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CredentialError {
PasswordLength(usize),
Character(char),
NotHex,
KeyLength(usize),
Entropy,
}
impl fmt::Display for CredentialError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CredentialError::PasswordLength(len) => write!(
f,
"BasicAuthPassword is {len} characters; OCPP 2.x allows {BASIC_AUTH_MIN_LEN} to the \
variable's maxLimit, at most {BASIC_AUTH_MAX_LEN} (A00.FR.205)"
),
CredentialError::Character(c) => write!(
f,
"BasicAuthPassword contains {c:?}; a passwordString allows only a-z, A-Z, 0-9 and * - _ = : + | @ ."
),
CredentialError::NotHex => {
f.write_str("the 1.6 AuthorizationKey must be an even-length hexadecimal string")
}
CredentialError::KeyLength(len) => write!(
f,
"the 1.6 AuthorizationKey is {len} bytes; it must be \
{AUTHORIZATION_KEY_MIN_BYTES}–{AUTHORIZATION_KEY_MAX_BYTES} (A00.FR.205)"
),
CredentialError::Entropy => f.write_str("the operating system's entropy source failed"),
}
}
}
impl core::error::Error for CredentialError {}
pub fn check_password(text: &str, max_len: usize) -> Result<(), CredentialError> {
if let Some(c) = text
.chars()
.find(|c| !c.is_ascii() || !PASSWORD_STRING_CHARSET.contains(&(*c as u8)))
{
return Err(CredentialError::Character(c));
}
if !(BASIC_AUTH_MIN_LEN..=max_len).contains(&text.len()) {
return Err(CredentialError::PasswordLength(text.len()));
}
Ok(())
}
pub fn authorization_key_octets(hex: &str) -> Result<Vec<u8>, CredentialError> {
let text = hex.trim().as_bytes();
if text.is_empty() || !text.len().is_multiple_of(2) {
return Err(CredentialError::NotHex);
}
let bytes = text
.chunks(2)
.map(|pair| Some(nibble(pair[0])? << 4 | nibble(pair[1])?))
.collect::<Option<Vec<u8>>>()
.ok_or(CredentialError::NotHex)?;
if !(AUTHORIZATION_KEY_MIN_BYTES..=AUTHORIZATION_KEY_MAX_BYTES).contains(&bytes.len()) {
return Err(CredentialError::KeyLength(bytes.len()));
}
Ok(bytes)
}
const fn nibble(digit: u8) -> Option<u8> {
match digit {
b'0'..=b'9' => Some(digit - b'0'),
b'a'..=b'f' => Some(digit - b'a' + 10),
b'A'..=b'F' => Some(digit - b'A' + 10),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_charset_is_the_one_part_2_lists() {
assert_eq!(PASSWORD_STRING_CHARSET.len(), 71);
let mut sorted = PASSWORD_STRING_CHARSET.to_vec();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), 71, "no duplicates");
for c in b"*-_=:+|@." {
assert!(PASSWORD_STRING_CHARSET.contains(c));
}
}
#[test]
fn a_password_is_a_password_string_of_16_to_the_limit() {
assert!(check_password(&"a".repeat(16), 40).is_ok());
assert!(check_password(&"Z9*-_=:+|@.".repeat(4)[..40], 40).is_ok());
assert_eq!(
check_password(&"a".repeat(15), 40),
Err(CredentialError::PasswordLength(15))
);
assert_eq!(
check_password(&"a".repeat(41), 40),
Err(CredentialError::PasswordLength(41))
);
assert!(check_password(&"a".repeat(64), BASIC_AUTH_MAX_LEN).is_ok());
assert_eq!(
check_password("short!", 40),
Err(CredentialError::Character('!'))
);
assert_eq!(
check_password("sixteen chars ok", 40),
Err(CredentialError::Character(' '))
);
assert_eq!(
check_password("sixteen-chars-ü-ok", 40),
Err(CredentialError::Character('ü'))
);
}
#[test]
fn an_authorization_key_is_16_to_20_octets_of_hex() {
assert_eq!(
authorization_key_octets("000102030405060708090a0b0c0d0E0F").unwrap(),
(0..16).collect::<Vec<u8>>()
);
assert_eq!(
authorization_key_octets(" 00112233445566778899aabbccddeeff\n")
.unwrap()
.len(),
16
);
assert_eq!(authorization_key_octets("zz"), Err(CredentialError::NotHex));
assert_eq!(
authorization_key_octets("abc"),
Err(CredentialError::NotHex)
);
assert_eq!(authorization_key_octets(""), Err(CredentialError::NotHex));
assert_eq!(
authorization_key_octets(&"ab".repeat(15)),
Err(CredentialError::KeyLength(15))
);
assert_eq!(
authorization_key_octets(&"ab".repeat(21)),
Err(CredentialError::KeyLength(21))
);
assert!(authorization_key_octets(&"ab".repeat(20)).is_ok());
assert_eq!(
authorization_key_octets(&"0g".repeat(16)),
Err(CredentialError::NotHex)
);
}
}