use std::collections::HashMap;
use std::fmt;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use hmac::{Hmac, Mac};
use serde_json::{Map, Value};
use sha2::Sha256;
pub const DEFAULT_TOLERANCE: Duration = Duration::from_secs(300);
const MAX_SAFE_INT: f64 = 9_007_199_254_740_991.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RejectReason {
MissingSecret,
UnknownKeyVersion,
MalformedSignature,
BadSignature,
MissingTimestamp,
StaleTimestamp,
FutureTimestamp,
TimestampMismatch,
VersionMismatch,
MalformedEnvelope,
}
impl RejectReason {
pub fn as_str(&self) -> &'static str {
match self {
RejectReason::MissingSecret => "missing-secret",
RejectReason::UnknownKeyVersion => "unknown-key-version",
RejectReason::MalformedSignature => "malformed-signature",
RejectReason::BadSignature => "bad-signature",
RejectReason::MissingTimestamp => "missing-timestamp",
RejectReason::StaleTimestamp => "stale-timestamp",
RejectReason::FutureTimestamp => "future-timestamp",
RejectReason::TimestampMismatch => "timestamp-mismatch",
RejectReason::VersionMismatch => "version-mismatch",
RejectReason::MalformedEnvelope => "malformed-envelope",
}
}
}
impl fmt::Display for RejectReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::error::Error for RejectReason {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebhookSecret {
pub version: i64,
pub secret: String,
}
impl WebhookSecret {
pub fn new(version: i64, secret: impl Into<String>) -> Self {
WebhookSecret {
version,
secret: secret.into(),
}
}
}
#[derive(Debug, Clone)]
pub struct VerifyOptions {
pub secrets: Vec<WebhookSecret>,
pub timestamp: Option<String>,
pub key_version: Option<String>,
pub tolerance_secs: f64,
pub now: Option<SystemTime>,
}
impl VerifyOptions {
pub fn new(secrets: Vec<WebhookSecret>) -> Self {
VerifyOptions {
secrets,
timestamp: None,
key_version: None,
tolerance_secs: DEFAULT_TOLERANCE.as_secs_f64(),
now: None,
}
}
pub fn timestamp(mut self, value: Option<&str>) -> Self {
self.timestamp = value.map(str::to_string);
self
}
pub fn key_version(mut self, value: Option<&str>) -> Self {
self.key_version = value.map(str::to_string);
self
}
pub fn tolerance_secs(mut self, secs: f64) -> Self {
self.tolerance_secs = secs;
self
}
pub fn now(mut self, now: SystemTime) -> Self {
self.now = Some(now);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Envelope {
pub delivery_id: String,
pub event: String,
pub attempt: i64,
pub sent_at: String,
pub occurred_at: Option<String>,
pub sequence: i64,
pub key_version: i64,
}
fn is_hex64(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
pub fn verify_signature(payload: &[u8], signature: &str, secret: &str) -> bool {
if secret.is_empty() || !is_hex64(signature) {
return false;
}
let Ok(expected) = hex::decode(signature) else {
return false;
};
let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(secret.as_bytes()) else {
return false;
};
mac.update(payload);
mac.verify_slice(&expected).is_ok()
}
fn parse_int(s: &str) -> Option<i64> {
let t = s.trim();
let digits = t
.strip_prefix('+')
.or_else(|| t.strip_prefix('-'))
.unwrap_or(t);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
t.trim_start_matches('+').parse().ok()
}
pub fn parse_timestamp(s: &str) -> Option<SystemTime> {
let secs = parse_rfc3339(s)?;
if secs >= 0.0 {
UNIX_EPOCH.checked_add(Duration::from_secs_f64(secs))
} else {
UNIX_EPOCH.checked_sub(Duration::from_secs_f64(-secs))
}
}
fn parse_rfc3339(s: &str) -> Option<f64> {
let b = s.as_bytes();
if b.len() < 20 {
return None;
}
let num = |range: std::ops::Range<usize>| -> Option<i64> {
let part = s.get(range)?;
if part.bytes().all(|c| c.is_ascii_digit()) {
part.parse().ok()
} else {
None
}
};
let (year, month, day) = (num(0..4)?, num(5..7)?, num(8..10)?);
let (hour, minute, second) = (num(11..13)?, num(14..16)?, num(17..19)?);
if b[4] != b'-'
|| b[7] != b'-'
|| !matches!(b[10], b'T' | b't')
|| b[13] != b':'
|| b[16] != b':'
{
return None;
}
let mut i = 19;
let mut nanos = 0f64;
if b[i] == b'.' {
let start = i + 1;
let mut end = start;
while end < b.len() && b[end].is_ascii_digit() {
end += 1;
}
if end == start {
return None;
}
nanos = format!("0.{}", &s[start..end.min(start + 9)])
.parse()
.ok()?;
i = end;
}
let offset_secs = match b.get(i)? {
b'Z' | b'z' if i + 1 == b.len() => 0,
sign @ (b'+' | b'-') if i + 6 == b.len() && b[i + 3] == b':' => {
let (oh, om) = (num(i + 1..i + 3)?, num(i + 4..i + 6)?);
if oh > 23 || om > 59 {
return None;
}
let total = oh * 3600 + om * 60;
if *sign == b'+' {
total
} else {
-total
}
}
_ => return None,
};
let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
let days_in_month = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return None,
};
if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 59 {
return None;
}
let y = if month <= 2 { year - 1 } else { year };
let era = (if y >= 0 { y } else { y - 399 }) / 400;
let yoe = y - era * 400;
let mp = (month + 9) % 12;
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
let secs = days * 86_400 + hour * 3600 + minute * 60 + second - offset_secs;
Some(secs as f64 + nanos)
}
fn number(value: Option<&Value>) -> Option<&serde_json::Number> {
match value? {
Value::Number(n) => Some(n),
_ => None,
}
}
fn safe_int(value: Option<&Value>) -> Option<i64> {
let n = number(value)?;
if let Some(i) = n.as_i64() {
return (i.unsigned_abs() as f64 <= MAX_SAFE_INT).then_some(i);
}
let f = n.as_f64()?;
(f.is_finite() && f.fract() == 0.0 && f.abs() <= MAX_SAFE_INT).then_some(f as i64)
}
fn non_blank(value: Option<&Value>) -> bool {
value
.and_then(Value::as_str)
.is_some_and(|s| !s.trim().is_empty())
}
pub fn verify_event(
raw_body: &[u8],
signature: &str,
opts: &VerifyOptions,
) -> Result<Envelope, RejectReason> {
if opts.secrets.is_empty() {
return Err(RejectReason::MissingSecret);
}
let version = match opts.key_version.as_deref() {
Some(header) if !header.is_empty() => {
parse_int(header).ok_or(RejectReason::UnknownKeyVersion)?
}
_ if opts.secrets.len() == 1 => opts.secrets[0].version,
_ => return Err(RejectReason::UnknownKeyVersion),
};
let secret = opts
.secrets
.iter()
.find(|s| s.version == version)
.filter(|s| !s.secret.is_empty())
.ok_or(RejectReason::UnknownKeyVersion)?;
if !is_hex64(signature) {
return Err(RejectReason::MalformedSignature);
}
if !verify_signature(raw_body, signature, &secret.secret) {
return Err(RejectReason::BadSignature);
}
let text = String::from_utf8_lossy(raw_body);
let doc: Value = serde_json::from_str(&text).map_err(|_| RejectReason::MissingTimestamp)?;
let empty = Map::new();
let top = doc.as_object();
let meta = top
.and_then(|o| o.get("_meta"))
.and_then(Value::as_object)
.unwrap_or(&empty);
let sent_at = match meta.get("sent_at").and_then(Value::as_str) {
Some(s) if !s.is_empty() => s,
_ => return Err(RejectReason::MissingTimestamp),
};
let tolerance = opts.tolerance_secs;
if !tolerance.is_finite() || tolerance < 0.0 {
return Err(RejectReason::MalformedEnvelope);
}
let sent = parse_rfc3339(sent_at).ok_or(RejectReason::MissingTimestamp)?;
let now = opts.now.unwrap_or_else(SystemTime::now);
let now_secs = match now.duration_since(UNIX_EPOCH) {
Ok(d) => d.as_secs_f64(),
Err(e) => -e.duration().as_secs_f64(),
};
let skew = now_secs - sent;
if skew > tolerance {
return Err(RejectReason::StaleTimestamp);
}
if skew < -tolerance {
return Err(RejectReason::FutureTimestamp);
}
if let Some(header) = opts.timestamp.as_deref() {
if header != sent_at {
return Err(RejectReason::TimestampMismatch);
}
}
if let Some(n) = number(meta.get("key_version")) {
if n.as_f64() != Some(version as f64) {
return Err(RejectReason::VersionMismatch);
}
}
let attempt = safe_int(meta.get("attempt"));
let sequence = safe_int(meta.get("sequence"));
let signed_version = safe_int(meta.get("key_version"));
if !non_blank(meta.get("delivery_id"))
|| !non_blank(meta.get("event"))
|| attempt.is_none_or(|a| a < 1)
|| sequence.is_none_or(|s| s < 1)
|| signed_version.is_none_or(|v| v < 1)
{
return Err(RejectReason::MalformedEnvelope);
}
let event = meta
.get("event")
.and_then(Value::as_str)
.unwrap_or_default();
if let Some(top_event) = top.and_then(|o| o.get("event")) {
if top_event.as_str() != Some(event) {
return Err(RejectReason::MalformedEnvelope);
}
}
let occurred_at = match meta.get("occurred_at") {
None => None,
Some(Value::String(s)) if parse_rfc3339(s).is_some() => Some(s.clone()),
Some(_) => return Err(RejectReason::MalformedEnvelope),
};
Ok(Envelope {
delivery_id: meta
.get("delivery_id")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
event: event.to_string(),
attempt: attempt.unwrap_or_default(),
sent_at: sent_at.to_string(),
occurred_at,
sequence: sequence.unwrap_or_default(),
key_version: version,
})
}
#[derive(Debug)]
pub struct DeliveryDedupeCache {
ttl: Duration,
seen: Mutex<HashMap<String, Instant>>,
}
impl Default for DeliveryDedupeCache {
fn default() -> Self {
DeliveryDedupeCache::new(Duration::from_secs(24 * 60 * 60))
}
}
impl DeliveryDedupeCache {
pub fn new(ttl: Duration) -> Self {
DeliveryDedupeCache {
ttl,
seen: Mutex::new(HashMap::new()),
}
}
pub fn seen(&self, delivery_id: &str) -> bool {
self.seen_at(delivery_id, Instant::now())
}
pub(crate) fn seen_at(&self, delivery_id: &str, now: Instant) -> bool {
let mut map = self
.seen
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if map.get(delivery_id).is_some_and(|expires| *expires > now) {
return true;
}
if map.len() >= 1024 {
map.retain(|_, expires| *expires > now);
}
map.insert(delivery_id.to_string(), now + self.ttl);
false
}
pub fn len(&self) -> usize {
self.seen
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_rfc3339() {
assert_eq!(parse_rfc3339("1970-01-01T00:00:00Z"), Some(0.0));
assert_eq!(
parse_rfc3339("2026-11-15T22:57:30+00:00"),
Some(1_794_783_450.0)
);
assert_eq!(
parse_rfc3339("2026-11-15T23:57:30+01:00"),
Some(1_794_783_450.0)
);
let nanos = parse_rfc3339("2026-11-15T22:57:30.123456789+00:00").unwrap();
assert!((nanos - 1_794_783_450.123).abs() < 1e-3);
for bad in [
"yesterday",
"2026-11-15",
"2026-11-15 22:57:30Z",
"2026-02-30T00:00:00Z",
"2026-11-15T24:00:00Z",
"2026-11-15T22:57:30",
"2026-11-15T22:57:30.Z",
"2026-11-15T22:57:30+0000",
"2026-11-15T22:57:30+24:00",
] {
assert_eq!(parse_rfc3339(bad), None, "{bad}");
}
}
#[test]
fn dedupe_cache_expires_and_prunes() {
let cache = DeliveryDedupeCache::new(Duration::from_secs(10));
let t0 = Instant::now();
assert!(!cache.seen_at("d-1", t0));
assert!(cache.seen_at("d-1", t0));
assert!(!cache.seen_at("d-2", t0));
assert_eq!(cache.len(), 2);
assert!(!cache.seen_at("d-1", t0 + Duration::from_secs(11)));
let big = DeliveryDedupeCache::new(Duration::from_secs(1));
for i in 0..1024 {
big.seen_at(&format!("old-{i}"), t0);
}
big.seen_at("fresh", t0 + Duration::from_secs(5));
assert_eq!(big.len(), 1);
}
}