#![cfg(any(feature = "rest", feature = "amqp"))]
use crate::time::{Duration, SystemTime, UNIX_EPOCH};
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use subtle::{Choice, ConstantTimeEq};
use crate::AxiamError;
use crate::Sensitive;
type HmacSha256 = Hmac<Sha256>;
pub const DEFAULT_TOLERANCE: Duration = Duration::from_secs(300);
const MAC_LEN: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct WebhookEvent<'a> {
pub timestamp: i64,
pub event_type: Option<&'a str>,
pub delivery_id: Option<&'a str>,
pub body: &'a [u8],
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum WebhookVerifyError {
#[error("malformed X-Axiam-Signature header: {reason}")]
MalformedHeader {
reason: &'static str,
},
#[error("X-Axiam-Signature header carried no v1 signature")]
MissingSignature,
#[error("X-Axiam-Signature `t` is not a unix timestamp")]
InvalidTimestamp,
#[error("X-Axiam-Timestamp does not match the signed `t` value")]
TimestampMismatch,
#[error("webhook signature verification failed")]
SignatureMismatch,
#[error("webhook timestamp is {skew_secs}s from now, outside the {tolerance_secs}s window")]
Stale {
skew_secs: u64,
tolerance_secs: u64,
},
}
impl From<WebhookVerifyError> for AxiamError {
fn from(err: WebhookVerifyError) -> Self {
AxiamError::auth(err.to_string())
}
}
#[derive(Debug, Clone, Copy)]
pub struct WebhookVerifyOptions<'a> {
tolerance: Duration,
now: Option<i64>,
timestamp_header: Option<&'a str>,
event_type: Option<&'a str>,
delivery_id: Option<&'a str>,
}
impl Default for WebhookVerifyOptions<'_> {
fn default() -> Self {
Self {
tolerance: DEFAULT_TOLERANCE,
now: None,
timestamp_header: None,
event_type: None,
delivery_id: None,
}
}
}
impl<'a> WebhookVerifyOptions<'a> {
pub fn new() -> Self {
Self::default()
}
pub fn tolerance(mut self, tolerance: Duration) -> Self {
self.tolerance = tolerance;
self
}
pub fn now(mut self, now_unix_secs: i64) -> Self {
self.now = Some(now_unix_secs);
self
}
pub fn timestamp_header(mut self, raw: &'a str) -> Self {
self.timestamp_header = Some(raw);
self
}
pub fn event_type(mut self, raw: &'a str) -> Self {
self.event_type = Some(raw);
self
}
pub fn delivery_id(mut self, raw: &'a str) -> Self {
self.delivery_id = Some(raw);
self
}
}
pub fn verify_webhook<'a>(
secret: &Sensitive<String>,
signature_header: &str,
body: &'a [u8],
options: &WebhookVerifyOptions<'a>,
) -> Result<WebhookEvent<'a>, WebhookVerifyError> {
let mut raw_t: Option<&str> = None;
let mut v1_values: Vec<&str> = Vec::new();
for pair in signature_header.split(',') {
let pair = pair.trim();
if pair.is_empty() {
continue;
}
let (key, value) = match pair.split_once('=') {
Some((k, v)) => (k.trim(), v.trim()),
None => {
return Err(WebhookVerifyError::MalformedHeader {
reason: "expected comma-separated key=value pairs",
});
}
};
match key {
"t" => {
if raw_t.is_some() {
return Err(WebhookVerifyError::MalformedHeader {
reason: "duplicate `t` field",
});
}
raw_t = Some(value);
}
"v1" => v1_values.push(value),
_ => {}
}
}
let raw_t = raw_t.ok_or(WebhookVerifyError::InvalidTimestamp)?;
let timestamp: i64 = raw_t
.parse()
.map_err(|_| WebhookVerifyError::InvalidTimestamp)?;
if let Some(header_ts) = options.timestamp_header {
let header_ts: i64 = header_ts
.trim()
.parse()
.map_err(|_| WebhookVerifyError::TimestampMismatch)?;
if header_ts != timestamp {
return Err(WebhookVerifyError::TimestampMismatch);
}
}
if v1_values.is_empty() {
return Err(WebhookVerifyError::MissingSignature);
}
let mut mac = <HmacSha256 as KeyInit>::new_from_slice(secret.expose().as_bytes())
.expect("HMAC-SHA256 accepts a key of any length");
mac.update(raw_t.as_bytes());
mac.update(b".");
mac.update(body);
let expected = mac.finalize().into_bytes();
let mut matched = Choice::from(0u8);
let mut decoded = [0u8; MAC_LEN];
for candidate in &v1_values {
let is_match = match hex::decode_to_slice(candidate.as_bytes(), &mut decoded) {
Ok(()) => expected.as_slice().ct_eq(&decoded),
Err(_) => Choice::from(0u8),
};
matched |= is_match;
}
if !bool::from(matched) {
return Err(WebhookVerifyError::SignatureMismatch);
}
let now = options.now.unwrap_or_else(current_unix_secs);
let skew_secs = now.saturating_sub(timestamp).unsigned_abs();
let tolerance_secs = options.tolerance.as_secs();
if skew_secs > tolerance_secs {
return Err(WebhookVerifyError::Stale {
skew_secs,
tolerance_secs,
});
}
Ok(WebhookEvent {
timestamp,
event_type: options.event_type,
delivery_id: options.delivery_id,
body,
})
}
fn current_unix_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
const SECRET: &str = "whsec_test_0123456789abcdef";
const TS: i64 = 1_785_700_000;
const BODY: &[u8] = br#"{"event":"user.created","id":"01JQ0000000000000000000000"}"#;
fn server_signature(secret: &str, timestamp: i64, body: &[u8]) -> String {
let mut mac = <HmacSha256 as KeyInit>::new_from_slice(secret.as_bytes()).unwrap();
mac.update(timestamp.to_string().as_bytes());
mac.update(b".");
mac.update(body);
hex::encode(mac.finalize().into_bytes())
}
fn header(secret: &str, timestamp: i64, body: &[u8]) -> String {
format!(
"t={timestamp},v1={}",
server_signature(secret, timestamp, body)
)
}
fn secret() -> Sensitive<String> {
Sensitive::new(SECRET.to_string())
}
#[test]
fn valid_fresh_signature_is_accepted() {
let opts = WebhookVerifyOptions::new().now(TS + 5);
let event = verify_webhook(&secret(), &header(SECRET, TS, BODY), BODY, &opts)
.expect("a fresh, correctly-signed delivery must verify");
assert_eq!(event.timestamp, TS);
assert_eq!(event.body, BODY);
}
#[test]
fn cross_sdk_shared_vector_round_trips() {
let sig = server_signature(SECRET, TS, BODY);
assert_eq!(sig.len(), 64, "hex-encoded HMAC-SHA256 is 64 chars");
assert_eq!(sig, sig.to_lowercase(), "hex must be lowercase");
let opts = WebhookVerifyOptions::new().now(TS);
let event = verify_webhook(&secret(), &format!("t={TS},v1={sig}"), BODY, &opts)
.expect("the shared vector must verify");
assert_eq!(event.timestamp, TS);
let mut tampered = BODY.to_vec();
tampered[0] ^= 0x01;
assert_eq!(
verify_webhook(&secret(), &format!("t={TS},v1={sig}"), &tampered, &opts),
Err(WebhookVerifyError::SignatureMismatch)
);
}
#[test]
fn tampered_body_is_rejected() {
let hdr = header(SECRET, TS, BODY);
let opts = WebhookVerifyOptions::new().now(TS);
for idx in [0usize, BODY.len() / 2, BODY.len() - 1] {
let mut tampered = BODY.to_vec();
tampered[idx] ^= 0x01;
assert_eq!(
verify_webhook(&secret(), &hdr, &tampered, &opts),
Err(WebhookVerifyError::SignatureMismatch),
"flipping byte {idx} must invalidate the MAC"
);
}
}
#[test]
fn wrong_secret_is_rejected() {
let hdr = header("whsec_some_other_secret", TS, BODY);
let opts = WebhookVerifyOptions::new().now(TS);
assert_eq!(
verify_webhook(&secret(), &hdr, BODY, &opts),
Err(WebhookVerifyError::SignatureMismatch)
);
}
#[test]
fn stale_timestamp_is_rejected() {
let hdr = header(SECRET, TS, BODY);
let opts = WebhookVerifyOptions::new().now(TS + 301);
assert_eq!(
verify_webhook(&secret(), &hdr, BODY, &opts),
Err(WebhookVerifyError::Stale {
skew_secs: 301,
tolerance_secs: 300,
})
);
let at_edge = WebhookVerifyOptions::new().now(TS + 300);
assert!(verify_webhook(&secret(), &hdr, BODY, &at_edge).is_ok());
}
#[test]
fn future_timestamp_beyond_tolerance_is_rejected() {
let hdr = header(SECRET, TS, BODY);
let opts = WebhookVerifyOptions::new().now(TS - 301);
assert_eq!(
verify_webhook(&secret(), &hdr, BODY, &opts),
Err(WebhookVerifyError::Stale {
skew_secs: 301,
tolerance_secs: 300,
})
);
let at_edge = WebhookVerifyOptions::new().now(TS - 300);
assert!(
verify_webhook(&secret(), &hdr, BODY, &at_edge).is_ok(),
"a future-dated delivery inside the window is still accepted"
);
}
#[test]
fn header_with_no_v1_is_rejected() {
let opts = WebhookVerifyOptions::new().now(TS);
assert_eq!(
verify_webhook(&secret(), &format!("t={TS}"), BODY, &opts),
Err(WebhookVerifyError::MissingSignature),
"\"nothing to verify\" must never be treated as success"
);
assert_eq!(
verify_webhook(&secret(), &format!("t={TS},v2=deadbeef"), BODY, &opts),
Err(WebhookVerifyError::MissingSignature)
);
}
#[test]
fn header_with_non_numeric_t_is_rejected() {
let sig = server_signature(SECRET, TS, BODY);
let opts = WebhookVerifyOptions::new().now(TS);
for bad in ["t=not-a-number", "t=", "t=17857000000000000000000"] {
assert_eq!(
verify_webhook(&secret(), &format!("{bad},v1={sig}"), BODY, &opts),
Err(WebhookVerifyError::InvalidTimestamp),
"`{bad}` must be rejected"
);
}
}
#[test]
fn empty_and_shapeless_headers_are_rejected() {
let opts = WebhookVerifyOptions::new().now(TS);
assert_eq!(
verify_webhook(&secret(), "", BODY, &opts),
Err(WebhookVerifyError::InvalidTimestamp)
);
assert_eq!(
verify_webhook(&secret(), " ", BODY, &opts),
Err(WebhookVerifyError::InvalidTimestamp)
);
assert!(matches!(
verify_webhook(&secret(), "garbage-without-equals", BODY, &opts),
Err(WebhookVerifyError::MalformedHeader { .. })
));
assert!(matches!(
verify_webhook(&secret(), &format!("t={TS},t={TS}"), BODY, &opts),
Err(WebhookVerifyError::MalformedHeader { .. })
));
}
#[test]
fn non_hex_and_short_v1_fail_closed() {
let opts = WebhookVerifyOptions::new().now(TS);
for bad_sig in ["zz", "", "deadbeef", &"a".repeat(63), &"a".repeat(66)] {
assert_eq!(
verify_webhook(&secret(), &format!("t={TS},v1={bad_sig}"), BODY, &opts),
Err(WebhookVerifyError::SignatureMismatch),
"an undecodable v1 must fail closed, not pass"
);
}
}
#[test]
fn multiple_v1_values_accept_when_any_matches() {
let good = server_signature(SECRET, TS, BODY);
let opts = WebhookVerifyOptions::new().now(TS);
let hdr = format!("t={TS},v1={},v1={good}", "0".repeat(64));
assert!(verify_webhook(&secret(), &hdr, BODY, &opts).is_ok());
}
#[test]
fn unknown_keys_and_whitespace_are_tolerated() {
let sig = server_signature(SECRET, TS, BODY);
let hdr = format!(" t = {TS} , scheme=v2 , v1 = {sig} ");
let opts = WebhookVerifyOptions::new().now(TS);
assert!(verify_webhook(&secret(), &hdr, BODY, &opts).is_ok());
}
#[test]
fn timestamp_header_must_equal_the_signed_t() {
let hdr = header(SECRET, TS, BODY);
let matching = WebhookVerifyOptions::new()
.now(TS)
.timestamp_header("1785700000");
assert!(verify_webhook(&secret(), &hdr, BODY, &matching).is_ok());
let mismatched = WebhookVerifyOptions::new()
.now(TS)
.timestamp_header("1785700001");
assert_eq!(
verify_webhook(&secret(), &hdr, BODY, &mismatched),
Err(WebhookVerifyError::TimestampMismatch)
);
let garbage = WebhookVerifyOptions::new().now(TS).timestamp_header("nope");
assert_eq!(
verify_webhook(&secret(), &hdr, BODY, &garbage),
Err(WebhookVerifyError::TimestampMismatch)
);
}
#[test]
fn event_and_delivery_headers_are_carried_through() {
let hdr = header(SECRET, TS, BODY);
let opts = WebhookVerifyOptions::new()
.now(TS)
.event_type("user.created")
.delivery_id("018f4c1a-0000-7000-8000-000000000000");
let event = verify_webhook(&secret(), &hdr, BODY, &opts).expect("verifies");
assert_eq!(event.event_type, Some("user.created"));
assert_eq!(
event.delivery_id,
Some("018f4c1a-0000-7000-8000-000000000000")
);
}
#[test]
fn custom_tolerance_is_respected() {
let hdr = header(SECRET, TS, BODY);
let tight = WebhookVerifyOptions::new()
.now(TS + 30)
.tolerance(Duration::from_secs(10));
assert_eq!(
verify_webhook(&secret(), &hdr, BODY, &tight),
Err(WebhookVerifyError::Stale {
skew_secs: 30,
tolerance_secs: 10,
})
);
}
#[test]
fn errors_never_surface_the_expected_signature_or_secret() {
let expected = server_signature(SECRET, TS, BODY);
let opts = WebhookVerifyOptions::new().now(TS);
let err = verify_webhook(
&secret(),
&format!("t={TS},v1={}", "0".repeat(64)),
BODY,
&opts,
)
.expect_err("must reject");
let rendered = format!("{err} / {err:?}");
assert!(!rendered.contains(&expected), "leaked MAC: {rendered}");
assert!(!rendered.contains(SECRET), "leaked secret: {rendered}");
}
#[test]
fn system_clock_is_used_when_no_now_is_injected() {
let now = current_unix_secs();
let hdr = header(SECRET, now, BODY);
assert!(verify_webhook(&secret(), &hdr, BODY, &WebhookVerifyOptions::new()).is_ok());
let old = header(SECRET, now - 86_400, BODY);
assert!(matches!(
verify_webhook(&secret(), &old, BODY, &WebhookVerifyOptions::new()),
Err(WebhookVerifyError::Stale { .. })
));
}
#[test]
fn verify_error_converts_to_an_axiam_auth_error() {
let err: AxiamError = WebhookVerifyError::SignatureMismatch.into();
assert!(matches!(err, AxiamError::Auth { .. }));
}
}