use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use base64::Engine;
use chrono::{DateTime, Utc};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, SystemClock};
type HmacSha256 = Hmac<Sha256>;
pub const WEBHOOK_ID_HEADER: &str = "webhook-id";
pub const WEBHOOK_TIMESTAMP_HEADER: &str = "webhook-timestamp";
pub const WEBHOOK_SIGNATURE_HEADER: &str = "webhook-signature";
pub const DEFAULT_WEBHOOK_TOLERANCE: Duration = Duration::from_secs(300);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum WebhookError {
#[error(
"invalid webhook secret: {0}; pass the base64 secret, optionally prefixed with `whsec_`"
)]
InvalidSecret(String),
#[error("missing webhook header `{0}`; forward the delivery's headers unchanged")]
MissingHeader(&'static str),
#[error("malformed `{header}` header: {reason}")]
MalformedHeader {
header: &'static str,
reason: String,
},
#[error(
"webhook signature does not match; verify the raw request body, not re-serialized JSON, \
and check the signing secret"
)]
SignatureMismatch,
#[error("webhook delivery is {age_seconds}s old (max {max_age_seconds}s)")]
TimestampExpired {
age_seconds: u64,
max_age_seconds: u64,
},
#[error(
"webhook timestamp is {skew_seconds}s in the future (max {max_skew_seconds}s); check the \
sender's clock"
)]
TimestampInFuture {
skew_seconds: u64,
max_skew_seconds: u64,
},
#[error("webhook `{0}` was already received; a replay is ignored")]
Replayed(String),
}
impl WebhookError {
pub fn code(&self) -> &'static str {
match self {
Self::InvalidSecret(_) => "webhook.invalid_secret",
Self::MissingHeader(_) => "webhook.missing_header",
Self::MalformedHeader { .. } => "webhook.malformed_header",
Self::SignatureMismatch => "webhook.signature_mismatch",
Self::TimestampExpired { .. } => "webhook.timestamp_expired",
Self::TimestampInFuture { .. } => "webhook.timestamp_in_future",
Self::Replayed(_) => "webhook.replayed",
}
}
}
impl From<WebhookError> for AdkError {
fn from(error: WebhookError) -> Self {
let category = match error {
WebhookError::InvalidSecret(_) => ErrorCategory::InvalidInput,
WebhookError::Replayed(_) => ErrorCategory::Conflict,
WebhookError::MissingHeader(_)
| WebhookError::MalformedHeader { .. }
| WebhookError::SignatureMismatch
| WebhookError::TimestampExpired { .. }
| WebhookError::TimestampInFuture { .. } => ErrorCategory::Unauthorized,
};
AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct WebhookSecret {
key: Arc<[u8]>,
}
impl std::fmt::Debug for WebhookSecret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WebhookSecret").field("key", &"[REDACTED]").finish()
}
}
impl WebhookSecret {
pub fn from_base64(secret: &str) -> Result<Self, WebhookError> {
let encoded = secret.trim().strip_prefix("whsec_").unwrap_or(secret.trim());
let key = base64::engine::general_purpose::STANDARD
.decode(encoded)
.map_err(|e| WebhookError::InvalidSecret(format!("base64 decode failed: {e}")))?;
Self::from_bytes(key)
}
pub fn from_bytes(key: impl Into<Vec<u8>>) -> Result<Self, WebhookError> {
let key = key.into();
if key.is_empty() {
return Err(WebhookError::InvalidSecret("the secret is empty".to_string()));
}
Ok(Self { key: key.into() })
}
pub fn to_whsec(&self) -> String {
format!("whsec_{}", base64::engine::general_purpose::STANDARD.encode(&self.key))
}
fn mac(&self, id: &str, timestamp: &str, body: &[u8]) -> HmacSha256 {
let mut mac = HmacSha256::new_from_slice(&self.key).expect("HMAC accepts any key length");
mac.update(id.as_bytes());
mac.update(b".");
mac.update(timestamp.as_bytes());
mac.update(b".");
mac.update(body);
mac
}
pub fn signature(&self, id: &str, timestamp: i64, body: &[u8]) -> String {
let digest = self.mac(id, ×tamp.to_string(), body).finalize().into_bytes();
format!("v1,{}", base64::engine::general_purpose::STANDARD.encode(digest))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedWebhook {
pub id: String,
pub timestamp: i64,
pub signature: String,
}
impl SignedWebhook {
pub fn as_headers(&self) -> WebhookHeaders<'_> {
WebhookHeaders {
id: &self.id,
timestamp: std::borrow::Cow::Owned(self.timestamp.to_string()),
signature: &self.signature,
}
}
pub fn header_pairs(&self) -> [(&'static str, String); 3] {
[
(WEBHOOK_ID_HEADER, self.id.clone()),
(WEBHOOK_TIMESTAMP_HEADER, self.timestamp.to_string()),
(WEBHOOK_SIGNATURE_HEADER, self.signature.clone()),
]
}
}
#[derive(Debug, Clone)]
pub struct WebhookSigner {
secrets: Vec<WebhookSecret>,
clock: Arc<dyn Clock>,
}
impl WebhookSigner {
pub fn new(secret: WebhookSecret) -> Self {
Self { secrets: vec![secret], clock: Arc::new(SystemClock) }
}
pub fn with_secret(mut self, secret: WebhookSecret) -> Self {
self.secrets.push(secret);
self
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
pub fn sign(&self, id: &str, timestamp: i64, body: &[u8]) -> SignedWebhook {
let signature = self
.secrets
.iter()
.map(|secret| secret.signature(id, timestamp, body))
.collect::<Vec<_>>()
.join(" ");
SignedWebhook { id: id.to_string(), timestamp, signature }
}
pub fn sign_now(&self, id: &str, body: &[u8]) -> SignedWebhook {
self.sign(id, self.clock.now().timestamp(), body)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebhookHeaders<'a> {
pub id: &'a str,
pub timestamp: std::borrow::Cow<'a, str>,
pub signature: &'a str,
}
impl<'a> WebhookHeaders<'a> {
pub fn from_lookup(
lookup: impl Fn(&'static str) -> Option<&'a str>,
) -> Result<Self, WebhookError> {
let header = |name| lookup(name).ok_or(WebhookError::MissingHeader(name));
let id = header(WEBHOOK_ID_HEADER)?;
if id.trim().is_empty() || id.len() > 256 {
return Err(WebhookError::MalformedHeader {
header: WEBHOOK_ID_HEADER,
reason: "must contain 1 to 256 bytes".to_string(),
});
}
Ok(Self {
id,
timestamp: std::borrow::Cow::Borrowed(header(WEBHOOK_TIMESTAMP_HEADER)?),
signature: header(WEBHOOK_SIGNATURE_HEADER)?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedWebhook {
pub id: String,
pub timestamp: DateTime<Utc>,
}
#[derive(Debug, Clone)]
pub struct WebhookVerifier {
secrets: Vec<WebhookSecret>,
tolerance: Duration,
clock: Arc<dyn Clock>,
}
impl WebhookVerifier {
pub fn new(secret: WebhookSecret) -> Self {
Self {
secrets: vec![secret],
tolerance: DEFAULT_WEBHOOK_TOLERANCE,
clock: Arc::new(SystemClock),
}
}
pub fn with_secret(mut self, secret: WebhookSecret) -> Self {
self.secrets.push(secret);
self
}
pub fn with_tolerance(mut self, tolerance: Duration) -> Self {
self.tolerance = tolerance;
self
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
pub fn tolerance(&self) -> Duration {
self.tolerance
}
pub fn verify(
&self,
headers: &WebhookHeaders<'_>,
body: &[u8],
) -> Result<VerifiedWebhook, WebhookError> {
let raw_timestamp = headers.timestamp.trim();
let timestamp: i64 = raw_timestamp.parse().map_err(|_| WebhookError::MalformedHeader {
header: WEBHOOK_TIMESTAMP_HEADER,
reason: "not an integer number of seconds".to_string(),
})?;
let now = self.clock.now().timestamp();
let tolerance = self.tolerance.as_secs();
let distance = now.abs_diff(timestamp);
if distance > tolerance {
return Err(if timestamp < now {
WebhookError::TimestampExpired { age_seconds: distance, max_age_seconds: tolerance }
} else {
WebhookError::TimestampInFuture {
skew_seconds: distance,
max_skew_seconds: tolerance,
}
});
}
let candidates: Vec<Vec<u8>> = headers
.signature
.split_whitespace()
.filter_map(|entry| entry.strip_prefix("v1,"))
.filter_map(|encoded| base64::engine::general_purpose::STANDARD.decode(encoded).ok())
.collect();
if candidates.is_empty() {
return Err(WebhookError::MalformedHeader {
header: WEBHOOK_SIGNATURE_HEADER,
reason: "no `v1,<base64>` signature".to_string(),
});
}
let matched = self.secrets.iter().any(|secret| {
let mac = secret.mac(headers.id, raw_timestamp, body);
candidates.iter().any(|candidate| mac.clone().verify_slice(candidate).is_ok())
});
if !matched {
return Err(WebhookError::SignatureMismatch);
}
let timestamp = DateTime::from_timestamp(timestamp, 0).ok_or_else(|| {
WebhookError::MalformedHeader {
header: WEBHOOK_TIMESTAMP_HEADER,
reason: "out of range".to_string(),
}
})?;
Ok(VerifiedWebhook { id: headers.id.to_string(), timestamp })
}
}
#[async_trait]
pub trait WebhookReplayGuard: Send + Sync {
async fn first_seen(&self, id: &str, keep_until: DateTime<Utc>) -> crate::Result<bool>;
}
#[derive(Debug)]
pub struct InMemoryWebhookReplayGuard {
seen: std::sync::Mutex<HashMap<String, DateTime<Utc>>>,
clock: Arc<dyn Clock>,
}
impl Default for InMemoryWebhookReplayGuard {
fn default() -> Self {
Self::new()
}
}
impl InMemoryWebhookReplayGuard {
pub fn new() -> Self {
Self { seen: std::sync::Mutex::new(HashMap::new()), clock: Arc::new(SystemClock) }
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
pub fn record(&self, id: &str, keep_until: DateTime<Utc>) -> bool {
let now = self.clock.now();
let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
seen.retain(|_, until| *until > now);
if seen.contains_key(id) {
return false;
}
seen.insert(id.to_string(), keep_until);
true
}
}
#[async_trait]
impl WebhookReplayGuard for InMemoryWebhookReplayGuard {
async fn first_seen(&self, id: &str, keep_until: DateTime<Utc>) -> crate::Result<bool> {
Ok(self.record(id, keep_until))
}
}
pub fn replay_window(tolerance: Duration) -> Duration {
tolerance.saturating_mul(2)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ManualClock;
const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
const NOW: i64 = 1_760_000_000;
fn clock() -> Arc<ManualClock> {
Arc::new(ManualClock::new(DateTime::from_timestamp(NOW, 0).unwrap()))
}
fn secret(text: &str) -> WebhookSecret {
WebhookSecret::from_bytes(text.as_bytes().to_vec()).unwrap()
}
#[test]
fn reference_vector_matches() {
let secret = WebhookSecret::from_base64(SECRET).unwrap();
let body = br#"{"test": 2432232314}"#;
let signed = WebhookSigner::new(secret.clone()).sign(
"msg_p5jXN8AQM9LWM0D4loKWxJek",
1_614_265_330,
body,
);
assert_eq!(signed.signature, "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=");
let verifier = WebhookVerifier::new(secret).with_clock(Arc::new(ManualClock::new(
DateTime::from_timestamp(1_614_265_330, 0).unwrap(),
)));
assert_eq!(verifier.verify(&signed.as_headers(), body).unwrap().id, signed.id);
}
#[test]
fn valid_signature_is_accepted() {
let clock = clock();
let signer = WebhookSigner::new(secret("a")).with_clock(clock.clone());
let signed = signer.sign_now("msg_1", b"{}");
let verified =
WebhookVerifier::new(secret("a")).with_clock(clock).verify(&signed.as_headers(), b"{}");
assert_eq!(
verified,
Ok(VerifiedWebhook {
id: "msg_1".to_string(),
timestamp: DateTime::from_timestamp(NOW, 0).unwrap()
})
);
}
#[test]
fn tampered_body_wrong_secret_and_wrong_id_are_rejected() {
let clock = clock();
let signed = WebhookSigner::new(secret("a")).sign("msg_1", NOW, b"{}");
let verifier = WebhookVerifier::new(secret("a")).with_clock(clock.clone());
assert_eq!(
verifier.verify(&signed.as_headers(), b"{\"x\":1}"),
Err(WebhookError::SignatureMismatch)
);
let other = WebhookVerifier::new(secret("b")).with_clock(clock.clone());
assert_eq!(other.verify(&signed.as_headers(), b"{}"), Err(WebhookError::SignatureMismatch));
let mut renamed = signed.clone();
renamed.id = "msg_other".to_string();
assert_eq!(
verifier.verify(&renamed.as_headers(), b"{}"),
Err(WebhookError::SignatureMismatch)
);
}
#[test]
fn expired_and_future_timestamps_are_rejected() {
let clock = clock();
let verifier = WebhookVerifier::new(secret("a")).with_clock(clock);
let signer = WebhookSigner::new(secret("a"));
let old = signer.sign("msg_1", NOW - 301, b"{}");
assert_eq!(
verifier.verify(&old.as_headers(), b"{}"),
Err(WebhookError::TimestampExpired { age_seconds: 301, max_age_seconds: 300 })
);
let future = signer.sign("msg_1", NOW + 301, b"{}");
assert_eq!(
verifier.verify(&future.as_headers(), b"{}"),
Err(WebhookError::TimestampInFuture { skew_seconds: 301, max_skew_seconds: 300 })
);
let edge = signer.sign("msg_1", NOW - 300, b"{}");
assert!(verifier.verify(&edge.as_headers(), b"{}").is_ok());
}
#[test]
fn rotation_accepts_either_key_from_either_side() {
let clock = clock();
let both =
WebhookSigner::new(secret("old")).with_secret(secret("new")).sign("m", NOW, b"{}");
let old_receiver = WebhookVerifier::new(secret("old")).with_clock(clock.clone());
let new_receiver = WebhookVerifier::new(secret("new")).with_clock(clock.clone());
assert!(old_receiver.verify(&both.as_headers(), b"{}").is_ok());
assert!(new_receiver.verify(&both.as_headers(), b"{}").is_ok());
let receiver =
WebhookVerifier::new(secret("old")).with_secret(secret("new")).with_clock(clock);
for key in ["old", "new"] {
let signed = WebhookSigner::new(secret(key)).sign("m", NOW, b"{}");
assert!(receiver.verify(&signed.as_headers(), b"{}").is_ok(), "{key}");
}
let retired = WebhookSigner::new(secret("retired")).sign("m", NOW, b"{}");
assert_eq!(
receiver.verify(&retired.as_headers(), b"{}"),
Err(WebhookError::SignatureMismatch)
);
}
#[test]
fn malformed_headers_are_rejected() {
let verifier = WebhookVerifier::new(secret("a")).with_clock(clock());
let headers = WebhookHeaders { id: "m", timestamp: "soon".into(), signature: "v1,AAAA" };
assert!(matches!(
verifier.verify(&headers, b"{}"),
Err(WebhookError::MalformedHeader { header: WEBHOOK_TIMESTAMP_HEADER, .. })
));
let headers =
WebhookHeaders { id: "m", timestamp: NOW.to_string().into(), signature: "v2,AAAA" };
assert!(matches!(
verifier.verify(&headers, b"{}"),
Err(WebhookError::MalformedHeader { header: WEBHOOK_SIGNATURE_HEADER, .. })
));
assert_eq!(
WebhookHeaders::from_lookup(|_| None),
Err(WebhookError::MissingHeader(WEBHOOK_ID_HEADER))
);
assert!(WebhookSecret::from_base64("whsec_").is_err());
assert!(WebhookSecret::from_base64("not base64!").is_err());
}
#[tokio::test]
async fn replay_guard_refuses_a_second_delivery_until_the_window_passes() {
let clock = clock();
let guard = InMemoryWebhookReplayGuard::new().with_clock(clock.clone());
let until = clock.now()
+ chrono::Duration::from_std(replay_window(DEFAULT_WEBHOOK_TOLERANCE)).unwrap();
assert!(guard.first_seen("m", until).await.unwrap());
assert!(!guard.first_seen("m", until).await.unwrap());
clock.advance(Duration::from_secs(601));
assert!(guard.first_seen("m", until).await.unwrap());
}
}