use crate::std_shim::{String, ToString};
use core::fmt;
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use crate::model::Timestamp;
pub const SIGNATURE_HEADER: &str = "x-openadr-signature";
pub const TIMESTAMP_HEADER: &str = "x-openadr-timestamp";
pub const ATTEMPT_HEADER: &str = "x-openadr-attempt";
pub const ECHO_PARAM: &str = "echo";
pub const VERSION: &str = "v1";
pub const DEFAULT_TOLERANCE: i64 = 300;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SignatureError {
#[error("malformed signature header: expected `{VERSION}=<hex>`")]
Malformed,
#[error("unknown signature scheme {version:?}")]
UnknownVersion {
version: String,
},
#[error("signature does not match")]
Mismatch,
#[error("delivery timestamp is {drift}s from now, outside the {tolerance}s tolerance")]
Stale {
drift: i64,
tolerance: i64,
},
}
fn mac(key: &[u8], at: Timestamp, body: &[u8]) -> Hmac<Sha256> {
let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts any key length");
mac.update(VERSION.as_bytes());
mac.update(b".");
mac.update(at.as_second().to_string().as_bytes());
mac.update(b".");
mac.update(body);
mac
}
pub fn sign(key: &[u8], at: Timestamp, body: &[u8]) -> String {
Signature {
digest: mac(key, at, body).finalize().into_bytes().into(),
}
.to_string()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
digest: [u8; 32],
}
impl Signature {
pub fn parse(header: &str) -> Result<Self, SignatureError> {
let (version, hex) = header
.trim()
.split_once('=')
.ok_or(SignatureError::Malformed)?;
if version != VERSION {
return Err(SignatureError::UnknownVersion {
version: version.into(),
});
}
if hex.len() != 64 {
return Err(SignatureError::Malformed);
}
let mut digest = [0u8; 32];
let (pairs, _) = hex.as_bytes().as_chunks::<2>();
for (slot, &[hi, lo]) in digest.iter_mut().zip(pairs) {
*slot = (self::hex(hi).ok_or(SignatureError::Malformed)? << 4)
| self::hex(lo).ok_or(SignatureError::Malformed)?;
}
Ok(Self { digest })
}
pub fn verify(
&self,
key: &[u8],
body: &[u8],
at: Timestamp,
now: Timestamp,
tolerance: i64,
) -> Result<(), SignatureError> {
mac(key, at, body)
.verify_slice(&self.digest)
.map_err(|_| SignatureError::Mismatch)?;
let drift = now.as_second() - at.as_second();
if drift.abs() > tolerance {
return Err(SignatureError::Stale { drift, tolerance });
}
Ok(())
}
}
impl fmt::Display for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(VERSION)?;
f.write_str("=")?;
for byte in &self.digest {
write!(f, "{byte:02x}")?;
}
Ok(())
}
}
pub fn parse_timestamp(header: &str) -> Option<Timestamp> {
Timestamp::from_second(header.trim().parse().ok()?).ok()
}
pub fn echo_challenge(query: &str) -> Option<String> {
query
.split('&')
.filter_map(|pair| pair.split_once('='))
.find(|(key, _)| *key == ECHO_PARAM)
.map(|(_, value)| percent_decode(value))
}
fn percent_decode(value: &str) -> String {
let bytes = value.as_bytes();
let mut out: crate::std_shim::Vec<u8> = crate::std_shim::Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'+' => {
out.push(b' ');
i += 1;
}
b'%' if i + 2 < bytes.len() => match (hex(bytes[i + 1]), hex(bytes[i + 2])) {
(Some(hi), Some(lo)) => {
out.push(hi << 4 | lo);
i += 3;
}
_ => {
out.push(b'%');
i += 1;
}
},
byte => {
out.push(byte);
i += 1;
}
}
}
String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
}
fn hex(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_echo_challenge_is_read_wherever_it_sits_in_the_query() {
assert_eq!(echo_challenge("echo=abc123").as_deref(), Some("abc123"));
assert_eq!(
echo_challenge("tenant=north&echo=abc123").as_deref(),
Some("abc123")
);
assert_eq!(
echo_challenge("echo=abc123&tenant=north").as_deref(),
Some("abc123")
);
assert_eq!(echo_challenge(""), None);
assert_eq!(echo_challenge("tenant=north"), None);
assert_eq!(echo_challenge("echoes=abc123"), None);
}
#[test]
fn a_challenge_is_decoded_rather_than_echoed_back_encoded() {
assert_eq!(echo_challenge("echo=a%2Fb").as_deref(), Some("a/b"));
assert_eq!(echo_challenge("echo=a+b").as_deref(), Some("a b"));
assert_eq!(echo_challenge("echo=%E2%9C%93").as_deref(), Some("✓"));
assert_eq!(echo_challenge("echo=100%").as_deref(), Some("100%"));
assert_eq!(echo_challenge("echo=a%zz").as_deref(), Some("a%zz"));
}
fn ts(s: &str) -> Timestamp {
s.parse().unwrap()
}
const KEY: &[u8] = b"shared-secret";
const SENT: &str = "2026-01-01T00:00:00Z";
#[test]
fn the_signature_is_hmac_sha256_over_the_versioned_material() {
assert_eq!(
sign(KEY, ts(SENT), b"{}"),
"v1=3ac27b7bc527ab4aa470257d5c22173261bf321a13417b16fc9f13ad12e95174"
);
}
#[test]
fn a_signature_round_trips() {
let header = sign(KEY, ts(SENT), b"{}");
assert!(header.starts_with("v1="));
Signature::parse(&header)
.unwrap()
.verify(
KEY,
b"{}",
ts(SENT),
ts("2026-01-01T00:00:10Z"),
DEFAULT_TOLERANCE,
)
.unwrap();
}
#[test]
fn the_timestamp_is_part_of_what_is_signed() {
assert_ne!(
sign(KEY, ts(SENT), b"{}"),
sign(KEY, ts("2026-01-01T00:00:01Z"), b"{}")
);
}
#[test]
fn a_replay_is_refused_even_though_the_signature_is_genuine() {
let header = sign(KEY, ts(SENT), b"{}");
let err = Signature::parse(&header)
.unwrap()
.verify(
KEY,
b"{}",
ts(SENT),
ts("2026-01-01T01:00:00Z"),
DEFAULT_TOLERANCE,
)
.unwrap_err();
assert!(matches!(err, SignatureError::Stale { .. }));
}
#[test]
fn a_clock_ahead_of_the_sender_is_tolerated_symmetrically() {
let header = sign(KEY, ts("2026-01-01T00:01:00Z"), b"{}");
Signature::parse(&header)
.unwrap()
.verify(
KEY,
b"{}",
ts("2026-01-01T00:01:00Z"),
ts(SENT),
DEFAULT_TOLERANCE,
)
.unwrap();
}
#[test]
fn a_tampered_body_or_a_wrong_key_is_refused() {
let header = sign(KEY, ts(SENT), b"{\"a\":1}");
let signature = Signature::parse(&header).unwrap();
let now = ts(SENT);
assert_eq!(
signature.verify(KEY, b"{\"a\":2}", ts(SENT), now, DEFAULT_TOLERANCE),
Err(SignatureError::Mismatch)
);
assert_eq!(
signature.verify(b"other", b"{\"a\":1}", ts(SENT), now, DEFAULT_TOLERANCE),
Err(SignatureError::Mismatch)
);
assert_eq!(
signature.verify(
KEY,
b"{\"a\":1}",
ts("2026-01-01T00:00:01Z"),
ts("2026-01-01T00:00:01Z"),
DEFAULT_TOLERANCE
),
Err(SignatureError::Mismatch)
);
}
#[test]
fn malformed_headers_are_refused_rather_than_guessed_at() {
assert_eq!(Signature::parse("deadbeef"), Err(SignatureError::Malformed));
assert_eq!(Signature::parse("v1=short"), Err(SignatureError::Malformed));
assert_eq!(
Signature::parse(&format!("v1={}", "z".repeat(64))),
Err(SignatureError::Malformed)
);
assert_eq!(
Signature::parse(&format!("v1=é{}", "a".repeat(62))),
Err(SignatureError::Malformed)
);
assert!(matches!(
Signature::parse(&format!("v2={}", "a".repeat(64))),
Err(SignatureError::UnknownVersion { .. })
));
}
#[test]
fn a_timestamp_header_round_trips() {
assert_eq!(parse_timestamp("1767225600"), Some(ts(SENT)));
assert_eq!(parse_timestamp(" 1767225600 "), Some(ts(SENT)));
assert_eq!(parse_timestamp("not-a-number"), None);
}
}