pub mod lan;
pub mod pairing;
pub mod session_init;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use base64::Engine as _;
use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, ZeroizeOnDrop};
use crate::types::Duration;
pub use lan::{
CancelPreparePairing, LONG_POLL_HOLD, LONG_POLL_TIMEOUT, NodeListing, PreparePairing,
PrepareRefused, WaitAction, WaitErrorMessage, WaitForPairing, WaitInstruction,
};
pub use pairing::{
ConnectionDetails, ConnectionDetailsPost, ConnectionDetailsRequest, FinalizePairing,
MINIMUM_SERVER_DELAY, NextStep, PAIRING_BUDGET, Pairing, PairingAccepted, PairingAttemptId,
PairingClient, PairingErrorMessage, PairingRefused, PairingRequest, PairingServer, PairingStep,
};
pub use session_init::{
COMMUNICATION_TOKEN_LIFETIME, CommunicationDetails, SessionCredentials, SessionErrorMessage,
SessionGrant, SessionInitClient, SessionInitServer, SessionRefused, SessionRequest, TokenStore,
UnpairRequest,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Role {
Cem,
Rm,
}
impl Role {
#[must_use]
pub const fn service_subtype(self) -> &'static str {
match self {
Role::Cem => "_cem",
Role::Rm => "_rm",
}
}
#[must_use]
pub const fn can_pair_with(self, other: Self) -> bool {
!matches!((self, other), (Role::Cem, Role::Cem) | (Role::Rm, Role::Rm))
}
#[must_use]
pub const fn other(self) -> Self {
match self {
Role::Cem => Role::Rm,
Role::Rm => Role::Cem,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Deployment {
Wan,
Lan,
}
impl Deployment {
#[must_use]
pub const fn communication_server(cem: Self, rm: Self) -> Role {
match (cem, rm) {
(Deployment::Lan, Deployment::Wan) => Role::Rm,
_ => Role::Cem,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NodeId(pub crate::types::Id);
impl NodeId {
#[cfg(feature = "uuid")]
#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
#[must_use]
pub fn generate() -> Self {
Self(crate::types::Id::generate())
}
pub fn parse(s: &str) -> Result<Self, ConnectError> {
crate::types::Id::parse(s)
.map(Self)
.map_err(|_| ConnectError::MalformedNodeId)
}
}
impl core::fmt::Display for NodeId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct NodeIdAlias(pub String);
impl NodeIdAlias {
pub const MAX_LEN: usize = 64;
pub fn parse(s: &str) -> Result<Self, ConnectError> {
if s.is_empty() || s.len() > Self::MAX_LEN || !s.bytes().all(|b| b.is_ascii_alphanumeric())
{
return Err(ConnectError::MalformedPairingCode);
}
Ok(Self(s.to_string()))
}
}
impl<'de> Deserialize<'de> for NodeIdAlias {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
Self::parse(&raw).map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct PairingToken(Vec<u8>);
impl PartialEq for PairingToken {
fn eq(&self, other: &Self) -> bool {
use subtle::ConstantTimeEq as _;
self.0.ct_eq(&other.0).into()
}
}
impl Eq for PairingToken {}
impl PairingToken {
pub const MIN_DYNAMIC: usize = 4;
pub const MIN_STATIC: usize = 6;
pub const MAX_LEN: usize = 256;
pub fn parse(s: &str, kind: TokenKind) -> Result<Self, ConnectError> {
let minimum = match kind {
TokenKind::Dynamic => Self::MIN_DYNAMIC,
TokenKind::Static => Self::MIN_STATIC,
};
if s.len() < minimum
|| s.len() > Self::MAX_LEN
|| !s.bytes().all(|b| b.is_ascii_alphanumeric())
{
return Err(ConnectError::MalformedPairingCode);
}
Ok(Self(s.as_bytes().to_vec()))
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
}
impl core::fmt::Debug for PairingToken {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "PairingToken(<{} characters>)", self.0.len())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenKind {
Dynamic,
Static,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PairingCode {
pub alias: Option<NodeIdAlias>,
pub token: PairingToken,
}
impl PairingCode {
pub fn parse(code: &str, kind: TokenKind) -> Result<Self, ConnectError> {
match code.split_once('-') {
Some((alias, token)) => Ok(Self {
alias: Some(NodeIdAlias::parse(alias)?),
token: PairingToken::parse(token, kind)?,
}),
None => Ok(Self {
alias: None,
token: PairingToken::parse(code, kind)?,
}),
}
}
}
#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AccessToken(String);
#[derive(Clone, Zeroize, ZeroizeOnDrop, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CommunicationToken(String);
macro_rules! opaque_token {
($ty:ident, $name:literal, $lifetime:expr) => {
impl $ty {
pub const MIN_BYTES: usize = 32;
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
pub fn from_entropy(bytes: &[u8]) -> Result<Self, ConnectError> {
if bytes.len() < Self::MIN_BYTES {
return Err(ConnectError::WeakSecret {
got: bytes.len(),
need: Self::MIN_BYTES,
});
}
Ok(Self(
base64::engine::general_purpose::STANDARD.encode(bytes),
))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub const fn lifetime() -> Duration {
$lifetime
}
#[must_use]
pub fn verify(&self, other: &Self) -> bool {
self.verify_str(&other.0)
}
#[must_use]
pub fn verify_str(&self, presented: &str) -> bool {
use subtle::ConstantTimeEq as _;
self.0.len() == presented.len()
&& bool::from(self.0.as_bytes().ct_eq(presented.as_bytes()))
}
}
impl core::fmt::Debug for $ty {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, concat!($name, "(<redacted>)"))
}
}
};
}
opaque_token!(AccessToken, "AccessToken", Duration::from_secs(157_680_000));
opaque_token!(
CommunicationToken,
"CommunicationToken",
Duration::from_secs(30)
);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeDescription {
pub id: NodeId,
pub brand: String,
#[serde(rename = "logoUrl", skip_serializing_if = "Option::is_none")]
pub logo_url: Option<String>,
#[serde(rename = "type")]
pub kind: String,
#[serde(rename = "modelName")]
pub model_name: String,
#[serde(rename = "userDefinedName", skip_serializing_if = "Option::is_none")]
pub user_defined_name: Option<String>,
pub role: Role,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EndpointDescription {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "logoUrl", skip_serializing_if = "Option::is_none")]
pub logo_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment: Option<Deployment>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ConnectError {
#[error("the pairing code is malformed")]
MalformedPairingCode,
#[error("the node identifier is malformed")]
MalformedNodeId,
#[error("a secret of {got} bytes is weaker than the {need} the specification requires")]
WeakSecret {
got: usize,
need: usize,
},
#[error("the challenge response does not match")]
ChallengeFailed,
#[error("a {0:?} cannot pair with another {0:?}")]
SameRole(Role),
#[error("{got} arrived while waiting for {expected}")]
OutOfOrder {
got: &'static str,
expected: &'static str,
},
#[error("the {what} budget of {} seconds ran out", limit.as_secs_f64())]
Expired {
what: &'static str,
limit: Duration,
},
#[error("another pairing attempt for this node is in progress")]
RateLimited,
#[error("no common {0}")]
NoOverlap(&'static str),
#[error("not paired")]
NotPaired,
#[error("pairing refused: {:?}", .0.error_message)]
Refused(pairing::PairingRefused),
#[error("session refused: {:?}", .0.error_message)]
SessionRefused(session_init::SessionRefused),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HmacBinding {
LeafFingerprint(Vec<u8>),
DomainName(String),
}
impl HmacBinding {
pub fn from_hex_fingerprint(hex: &str) -> Result<Self, ConnectError> {
let digits: Vec<u8> = hex.bytes().filter(|b| *b != b':' && *b != b' ').collect();
if !digits.len().is_multiple_of(2) || digits.is_empty() {
return Err(ConnectError::WeakSecret {
got: digits.len() / 2,
need: 32,
});
}
let mut bytes = Vec::with_capacity(digits.len() / 2);
for pair in digits.chunks(2) {
let hi = hex_value(*pair.first().unwrap_or(&0))?;
let lo = hex_value(*pair.get(1).unwrap_or(&0))?;
bytes.push(hi << 4 | lo);
}
if bytes.len() < 32 {
return Err(ConnectError::WeakSecret {
got: bytes.len(),
need: 32,
});
}
Ok(Self::LeafFingerprint(bytes))
}
fn as_bytes(&self) -> &[u8] {
match self {
HmacBinding::LeafFingerprint(bytes) => bytes,
HmacBinding::DomainName(name) => name.as_bytes(),
}
}
}
fn hex_value(b: u8) -> Result<u8, ConnectError> {
match b {
b'0'..=b'9' => Ok(b - b'0'),
b'a'..=b'f' => Ok(b - b'a' + 10),
b'A'..=b'F' => Ok(b - b'A' + 10),
_ => Err(ConnectError::MalformedPairingCode),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum CommunicationProtocol {
WebSocket,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum HmacHashingAlgorithm {
#[serde(rename = "SHA256")]
Sha256,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChallengeResponse {
bytes: [u8; 32],
}
impl ChallengeResponse {
pub fn compute(
challenge: &[u8],
token: &PairingToken,
binding: &HmacBinding,
) -> Result<Self, ConnectError> {
use hmac::Mac as _;
if challenge.len() < 32 {
return Err(ConnectError::WeakSecret {
got: challenge.len(),
need: 32,
});
}
let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::KeyInit>::new_from_slice(challenge)
.map_err(|_| ConnectError::ChallengeFailed)?;
mac.update(token.as_bytes());
mac.update(binding.as_bytes());
let out = mac.finalize().into_bytes();
let mut bytes = [0u8; 32];
bytes.copy_from_slice(&out);
Ok(Self { bytes })
}
pub fn from_base64(encoded: &str) -> Result<Self, ConnectError> {
let decoded = base64::engine::general_purpose::STANDARD
.decode(encoded)
.map_err(|_| ConnectError::ChallengeFailed)?;
if decoded.len() != 32 {
return Err(ConnectError::ChallengeFailed);
}
let mut bytes = [0u8; 32];
bytes.copy_from_slice(&decoded);
Ok(Self { bytes })
}
#[must_use]
pub fn as_base64(&self) -> String {
base64::engine::general_purpose::STANDARD.encode(self.bytes)
}
#[must_use]
pub fn verify(&self, theirs: &str) -> bool {
use subtle::ConstantTimeEq as _;
let Ok(other) = Self::from_base64(theirs) else {
return false;
};
self.bytes.ct_eq(&other.bytes).into()
}
}
pub(crate) fn base64_encode(bytes: &[u8]) -> String {
base64::engine::general_purpose::STANDARD.encode(bytes)
}
pub(crate) fn base64_decode(encoded: &str) -> Option<Vec<u8>> {
base64::engine::general_purpose::STANDARD
.decode(encoded)
.ok()
}
pub type Backoff = crate::session::Backoff;
pub mod dnssd {
use super::{Deployment, Role};
use alloc::string::{String, ToString};
use alloc::vec::Vec;
pub const SERVICE_TYPE: &str = "_s2connect";
pub const PROTOCOL: &str = "_tcp";
pub const TXT_VERSION: &str = "1";
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ServiceRecord {
pub endpoint_name: Option<String>,
pub endpoint_logo_url: Option<String>,
pub pairing_url: Option<String>,
pub longpolling_url: Option<String>,
pub roles: Vec<Role>,
}
impl ServiceRecord {
#[must_use]
pub fn txt_pairs(&self) -> Vec<(&'static str, String)> {
let mut out = alloc::vec![("txtver", TXT_VERSION.to_string())];
if let Some(name) = &self.endpoint_name {
out.push(("e_name", name.clone()));
}
if let Some(logo) = &self.endpoint_logo_url {
out.push(("e_logoUrl", logo.clone()));
}
if let Some(url) = &self.pairing_url {
out.push(("pairingUrl", url.clone()));
}
if let Some(url) = &self.longpolling_url {
out.push(("longpollingUrl", url.clone()));
}
out
}
#[must_use]
pub fn from_txt<'a, I>(pairs: I) -> Option<Self>
where
I: IntoIterator<Item = (&'a str, &'a str)>,
{
let mut record = Self::default();
let mut version_seen = false;
for (key, value) in pairs {
match key {
"txtver" | "txtvers" => {
if value != TXT_VERSION {
return None;
}
version_seen = true;
}
"e_name" => record.endpoint_name = Some(value.to_string()),
"e_logoUrl" => record.endpoint_logo_url = Some(value.to_string()),
"pairingUrl" => record.pairing_url = Some(value.to_string()),
"longpollingUrl" => record.longpolling_url = Some(value.to_string()),
_ => {}
}
}
if !version_seen || (record.pairing_url.is_none() && record.longpolling_url.is_none()) {
return None;
}
Some(record)
}
#[must_use]
pub fn has_pairing_server(&self) -> bool {
self.pairing_url.is_some()
}
#[must_use]
pub fn subtypes(&self) -> Vec<&'static str> {
self.roles.iter().map(|r| r.service_subtype()).collect()
}
#[must_use]
pub fn is_consistent_with(&self, deployment: Deployment) -> bool {
self.longpolling_url.is_none() || deployment == Deployment::Lan
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn token() -> PairingToken {
PairingToken::parse("A1b2C3", TokenKind::Static).expect("a legal token")
}
#[test]
fn an_alias_is_validated_however_the_body_was_parsed() {
assert!(serde_json::from_str::<NodeIdAlias>(r#""evse7""#).is_ok());
assert!(serde_json::from_str::<NodeIdAlias>(r#""evse 7""#).is_err());
assert!(serde_json::from_str::<NodeIdAlias>(r#""""#).is_err());
assert!(serde_json::from_str::<NodeIdAlias>(r#""evse\u0037""#).is_ok());
assert_eq!(
serde_json::from_value::<NodeIdAlias>(serde_json::json!("evse7")).ok(),
Some(NodeIdAlias("evse7".into()))
);
}
#[test]
fn a_pairing_code_splits_at_the_first_dash() {
let code = PairingCode::parse("evse7-A1b2C3", TokenKind::Static).unwrap();
assert_eq!(code.alias.unwrap().0, "evse7");
assert_eq!(code.token.as_bytes(), b"A1b2C3");
let code = PairingCode::parse("A1b2C3", TokenKind::Static).unwrap();
assert!(code.alias.is_none());
}
#[test]
fn a_pairing_code_is_checked_before_the_network_is() {
assert!(PairingCode::parse("abc", TokenKind::Dynamic).is_err());
assert!(PairingCode::parse("abcd", TokenKind::Dynamic).is_ok());
assert!(PairingCode::parse("abcde", TokenKind::Static).is_err());
assert!(PairingCode::parse("abcdef", TokenKind::Static).is_ok());
assert!(PairingCode::parse("ab cd", TokenKind::Dynamic).is_err());
assert!(PairingCode::parse("ab.cd", TokenKind::Dynamic).is_err());
assert!(PairingCode::parse("", TokenKind::Dynamic).is_err());
assert!(PairingCode::parse("-abcd", TokenKind::Dynamic).is_err());
}
#[test]
fn everything_an_unauthenticated_peer_chooses_is_bounded() {
use alloc::string::ToString;
assert!(NodeIdAlias::parse(&"a".repeat(NodeIdAlias::MAX_LEN)).is_ok());
assert!(NodeIdAlias::parse(&"a".repeat(NodeIdAlias::MAX_LEN + 1)).is_err());
let long = alloc::format!("\"{}\"", "a".repeat(NodeIdAlias::MAX_LEN + 1));
assert!(serde_json::from_str::<NodeIdAlias>(&long).is_err());
assert!(serde_json::from_str::<NodeIdAlias>("\"has space\"").is_err());
assert!(serde_json::from_str::<NodeIdAlias>("\"\"").is_err());
assert_eq!(
serde_json::from_str::<NodeIdAlias>("\"hub7\"").unwrap().0,
"hub7".to_string()
);
let longest = "a".repeat(PairingToken::MAX_LEN);
assert!(PairingToken::parse(&longest, TokenKind::Static).is_ok());
assert!(PairingToken::parse(&alloc::format!("{longest}a"), TokenKind::Static).is_err());
assert!(PairingCode::parse(&alloc::format!("hub7-{longest}a"), TokenKind::Static).is_err());
}
#[test]
fn a_secret_never_prints_itself() {
let code = PairingCode::parse("evse7-SuperSecret", TokenKind::Static).unwrap();
let rendered = alloc::format!("{:?}", code.token);
assert!(!rendered.contains("SuperSecret"), "{rendered}");
let access = AccessToken::new("hunter2");
assert_eq!(alloc::format!("{access:?}"), "AccessToken(<redacted>)");
}
#[test]
fn a_token_needs_the_entropy_the_specification_demands() {
assert!(AccessToken::from_entropy(&[0u8; 31]).is_err());
let token = AccessToken::from_entropy(&[0u8; 32]).unwrap();
assert_eq!(token.as_str().len(), 44);
assert_eq!(CommunicationToken::lifetime(), Duration::from_secs(30));
}
#[test]
fn the_challenge_binds_to_the_server_it_was_answered_by() {
let challenge = [9u8; 32];
let here = HmacBinding::DomainName("pairing.example.com".into());
let there = HmacBinding::DomainName("pairing.example.com.evil.test".into());
let ours = ChallengeResponse::compute(&challenge, &token(), &here).unwrap();
let theirs = ChallengeResponse::compute(&challenge, &token(), &here).unwrap();
assert!(ours.verify(&theirs.as_base64()));
let forged = ChallengeResponse::compute(&challenge, &token(), &there).unwrap();
assert!(!ours.verify(&forged.as_base64()));
let wrong = PairingToken::parse("Z9y8X7", TokenKind::Static).unwrap();
let forged = ChallengeResponse::compute(&challenge, &wrong, &here).unwrap();
assert!(!ours.verify(&forged.as_base64()));
}
#[test]
fn a_short_challenge_is_refused_rather_than_padded() {
let binding = HmacBinding::DomainName("x.example".into());
assert!(matches!(
ChallengeResponse::compute(&[0u8; 31], &token(), &binding),
Err(ConnectError::WeakSecret { need: 32, .. })
));
}
#[test]
fn a_fingerprint_is_read_with_or_without_colons() {
let colons = "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:\
AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99";
let plain = colons.replace(':', "");
assert_eq!(
HmacBinding::from_hex_fingerprint(colons).unwrap(),
HmacBinding::from_hex_fingerprint(&plain).unwrap()
);
assert!(HmacBinding::from_hex_fingerprint("AABB").is_err());
assert!(HmacBinding::from_hex_fingerprint("nonsense").is_err());
}
#[test]
fn verification_refuses_anything_that_is_not_a_response() {
let ours = ChallengeResponse::compute(
&[1u8; 32],
&token(),
&HmacBinding::DomainName("x.example".into()),
)
.unwrap();
assert!(!ours.verify("not base64 at all !!"));
assert!(!ours.verify(""));
assert!(!ours.verify(&base64::engine::general_purpose::STANDARD.encode([0u8; 16])));
}
#[test]
fn only_a_cem_and_an_rm_may_pair() {
assert!(Role::Cem.can_pair_with(Role::Rm));
assert!(Role::Rm.can_pair_with(Role::Cem));
assert!(!Role::Cem.can_pair_with(Role::Cem));
assert!(!Role::Rm.can_pair_with(Role::Rm));
}
#[test]
fn the_communication_server_is_the_one_the_standard_names() {
use Deployment::{Lan, Wan};
assert_eq!(Deployment::communication_server(Wan, Lan), Role::Cem);
assert_eq!(Deployment::communication_server(Lan, Wan), Role::Rm);
assert_eq!(Deployment::communication_server(Wan, Wan), Role::Cem);
assert_eq!(Deployment::communication_server(Lan, Lan), Role::Cem);
}
#[test]
fn the_dns_sd_record_round_trips_and_accepts_both_spellings() {
use dnssd::ServiceRecord;
let record = ServiceRecord {
endpoint_name: Some("EVSE1038".into()),
endpoint_logo_url: None,
pairing_url: Some("https://EVSE1038.local:443/pairing/".into()),
longpolling_url: None,
roles: alloc::vec![Role::Rm],
};
let pairs = record.txt_pairs();
assert_eq!(pairs[0], ("txtver", "1".to_string()));
assert_eq!(record.subtypes(), alloc::vec!["_rm"]);
let borrowed: alloc::vec::Vec<(&str, &str)> =
pairs.iter().map(|(k, v)| (*k, v.as_str())).collect();
let back = ServiceRecord::from_txt(borrowed).unwrap();
assert_eq!(back.pairing_url, record.pairing_url);
let back =
ServiceRecord::from_txt([("txtvers", "1"), ("pairingUrl", "https://x.local/pairing/")])
.unwrap();
assert!(back.has_pairing_server());
assert!(ServiceRecord::from_txt([("txtver", "1")]).is_none());
assert!(ServiceRecord::from_txt([("txtver", "2"), ("pairingUrl", "x")]).is_none());
}
#[test]
fn long_polling_is_a_lan_only_arrangement() {
use dnssd::ServiceRecord;
let record = ServiceRecord {
longpolling_url: Some("https://rm.local/pairing/".into()),
roles: alloc::vec![Role::Rm],
..ServiceRecord::default()
};
assert!(record.is_consistent_with(Deployment::Lan));
assert!(!record.is_consistent_with(Deployment::Wan));
}
}