use core::fmt;
use zeroize::Zeroizing;
use crate::types::Identity;
use crate::version::Version;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum SecurityProfile {
Unsecured,
BasicAuth,
TlsBasicAuth,
TlsClientCertificate,
}
impl SecurityProfile {
#[must_use]
pub const fn number(self) -> u8 {
match self {
SecurityProfile::Unsecured => 0,
SecurityProfile::BasicAuth => 1,
SecurityProfile::TlsBasicAuth => 2,
SecurityProfile::TlsClientCertificate => 3,
}
}
#[must_use]
pub const fn from_number(number: u8) -> Option<Self> {
Some(match number {
0 => SecurityProfile::Unsecured,
1 => SecurityProfile::BasicAuth,
2 => SecurityProfile::TlsBasicAuth,
3 => SecurityProfile::TlsClientCertificate,
_ => return None,
})
}
#[must_use]
pub const fn is_transport_encrypted(self) -> bool {
!matches!(
self,
SecurityProfile::Unsecured | SecurityProfile::BasicAuth
)
}
#[must_use]
pub const fn uses_basic_auth(self) -> bool {
matches!(
self,
SecurityProfile::BasicAuth | SecurityProfile::TlsBasicAuth
)
}
}
impl fmt::Display for SecurityProfile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "security profile {}", self.number())
}
}
#[derive(Clone)]
pub struct BasicAuthPassword {
secret: Zeroizing<Vec<u8>>,
}
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;
impl BasicAuthPassword {
pub fn utf8(password: impl Into<String>) -> Result<Self, CredentialError> {
let password = password.into();
let len = password.chars().count();
if !(BASIC_AUTH_MIN_LEN..=BASIC_AUTH_MAX_LEN).contains(&len) {
return Err(CredentialError::PasswordLength(len));
}
Ok(Self {
secret: Zeroizing::new(password.into_bytes()),
})
}
pub fn hex(key: &str) -> Result<Self, CredentialError> {
let text = key.trim();
if !text.len().is_multiple_of(2) || text.is_empty() {
return Err(CredentialError::NotHex);
}
let mut bytes = Vec::with_capacity(text.len() / 2);
for pair in text.as_bytes().chunks(2) {
let digits = core::str::from_utf8(pair).map_err(|_| CredentialError::NotHex)?;
bytes.push(u8::from_str_radix(digits, 16).map_err(|_| CredentialError::NotHex)?);
}
if !(AUTHORIZATION_KEY_MIN_BYTES..=AUTHORIZATION_KEY_MAX_BYTES).contains(&bytes.len()) {
return Err(CredentialError::KeyLength(bytes.len()));
}
Ok(Self {
secret: Zeroizing::new(bytes),
})
}
#[must_use]
pub fn raw(bytes: impl Into<Vec<u8>>) -> Self {
Self {
secret: Zeroizing::new(bytes.into()),
}
}
pub fn for_version(version: Version, secret: &str) -> Result<Self, CredentialError> {
match version {
Version::V1_6 => Self::hex(secret),
_ => Self::utf8(secret),
}
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.secret
}
#[must_use]
pub fn verify(&self, candidate: &[u8]) -> bool {
constant_time_eq(&self.secret, candidate)
}
}
impl fmt::Debug for BasicAuthPassword {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("BasicAuthPassword(<redacted>)")
}
}
#[must_use]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (x, y) in a.iter().zip(b) {
diff |= x ^ y;
}
diff == 0
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CredentialError {
PasswordLength(usize),
NotHex,
KeyLength(usize),
}
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}–{BASIC_AUTH_MAX_LEN} (A00.FR.205)"
),
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)"
),
}
}
}
impl std::error::Error for CredentialError {}
#[must_use]
pub fn basic_auth_header(identity: &Identity, password: &BasicAuthPassword) -> String {
use base64::Engine as _;
let mut credentials = Vec::new();
credentials.extend_from_slice(identity.as_str().as_bytes());
credentials.push(b':');
credentials.extend_from_slice(password.as_bytes());
let credentials = Zeroizing::new(credentials);
format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(&*credentials)
)
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Credentials {
None,
Basic {
user: String,
password: Zeroizing<Vec<u8>>,
},
ClientCertificate {
der: Vec<u8>,
},
}
impl Credentials {
#[must_use]
pub fn from_authorization_header(value: &str) -> Self {
use base64::Engine as _;
let Some(encoded) = value
.strip_prefix("Basic ")
.or_else(|| value.strip_prefix("basic "))
else {
return Credentials::None;
};
let Ok(decoded) = base64::engine::general_purpose::STANDARD.decode(encoded.trim()) else {
return Credentials::None;
};
match decoded.iter().position(|byte| *byte == b':') {
Some(index) => {
let (user, password) = decoded.split_at(index);
match core::str::from_utf8(user) {
Ok(user) => Credentials::Basic {
user: user.to_owned(),
password: Zeroizing::new(password[1..].to_vec()),
},
Err(_) => Credentials::None,
}
}
None => Credentials::None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_16_authorization_key_is_hex_and_a_2x_password_is_utf8() {
let legacy = BasicAuthPassword::hex("000102030405060708090a0b0c0d0e0f").unwrap();
assert_eq!(legacy.as_bytes(), &(0..16).collect::<Vec<u8>>()[..]);
assert_eq!(
BasicAuthPassword::hex("xyz").unwrap_err(),
CredentialError::NotHex
);
assert_eq!(
BasicAuthPassword::hex("0001020304").unwrap_err(),
CredentialError::KeyLength(5)
);
assert_eq!(
BasicAuthPassword::hex(&"ab".repeat(21)).unwrap_err(),
CredentialError::KeyLength(21)
);
assert!(BasicAuthPassword::hex(&"ab".repeat(20)).is_ok());
let modern = BasicAuthPassword::utf8("0123456789abcdef").unwrap();
assert_eq!(modern.as_bytes(), b"0123456789abcdef");
assert_eq!(
BasicAuthPassword::utf8("short").unwrap_err(),
CredentialError::PasswordLength(5)
);
assert!(BasicAuthPassword::utf8("x".repeat(41)).is_ok());
assert!(BasicAuthPassword::utf8("x".repeat(64)).is_ok());
assert!(BasicAuthPassword::utf8("x".repeat(65)).is_err());
}
#[test]
fn basic_auth_round_trips_through_the_header() {
let identity = Identity::new("CS-0001").unwrap();
let password = BasicAuthPassword::utf8("0123456789abcdef").unwrap();
let header = basic_auth_header(&identity, &password);
let parsed = Credentials::from_authorization_header(&header);
let Credentials::Basic {
user,
password: bytes,
} = parsed
else {
panic!("{parsed:?}")
};
assert_eq!(user, "CS-0001");
assert!(password.verify(&bytes));
assert!(!password.verify(b"0123456789abcdee"));
}
#[test]
fn profiles_report_what_they_secure() {
assert!(!SecurityProfile::BasicAuth.is_transport_encrypted());
assert!(SecurityProfile::TlsBasicAuth.is_transport_encrypted());
assert!(!SecurityProfile::TlsClientCertificate.uses_basic_auth());
assert_eq!(
SecurityProfile::from_number(3),
Some(SecurityProfile::TlsClientCertificate)
);
assert_eq!(SecurityProfile::from_number(4), None);
}
}