1use std::collections::HashMap;
39use std::sync::Arc;
40use std::time::Duration;
41
42use async_trait::async_trait;
43use base64::Engine;
44use chrono::{DateTime, Utc};
45use hmac::{Hmac, Mac};
46use sha2::Sha256;
47
48use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, SystemClock};
49
50type HmacSha256 = Hmac<Sha256>;
51
52pub const WEBHOOK_ID_HEADER: &str = "webhook-id";
54pub const WEBHOOK_TIMESTAMP_HEADER: &str = "webhook-timestamp";
56pub const WEBHOOK_SIGNATURE_HEADER: &str = "webhook-signature";
58pub const DEFAULT_WEBHOOK_TOLERANCE: Duration = Duration::from_secs(300);
60
61#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
66#[non_exhaustive]
67pub enum WebhookError {
68 #[error(
70 "invalid webhook secret: {0}; pass the base64 secret, optionally prefixed with `whsec_`"
71 )]
72 InvalidSecret(String),
73 #[error("missing webhook header `{0}`; forward the delivery's headers unchanged")]
75 MissingHeader(&'static str),
76 #[error("malformed `{header}` header: {reason}")]
78 MalformedHeader {
79 header: &'static str,
81 reason: String,
83 },
84 #[error(
86 "webhook signature does not match; verify the raw request body, not re-serialized JSON, \
87 and check the signing secret"
88 )]
89 SignatureMismatch,
90 #[error("webhook delivery is {age_seconds}s old (max {max_age_seconds}s)")]
92 TimestampExpired {
93 age_seconds: u64,
95 max_age_seconds: u64,
97 },
98 #[error(
100 "webhook timestamp is {skew_seconds}s in the future (max {max_skew_seconds}s); check the \
101 sender's clock"
102 )]
103 TimestampInFuture {
104 skew_seconds: u64,
106 max_skew_seconds: u64,
108 },
109 #[error("webhook `{0}` was already received; a replay is ignored")]
111 Replayed(String),
112}
113
114impl WebhookError {
115 pub fn code(&self) -> &'static str {
117 match self {
118 Self::InvalidSecret(_) => "webhook.invalid_secret",
119 Self::MissingHeader(_) => "webhook.missing_header",
120 Self::MalformedHeader { .. } => "webhook.malformed_header",
121 Self::SignatureMismatch => "webhook.signature_mismatch",
122 Self::TimestampExpired { .. } => "webhook.timestamp_expired",
123 Self::TimestampInFuture { .. } => "webhook.timestamp_in_future",
124 Self::Replayed(_) => "webhook.replayed",
125 }
126 }
127}
128
129impl From<WebhookError> for AdkError {
130 fn from(error: WebhookError) -> Self {
131 let category = match error {
132 WebhookError::InvalidSecret(_) => ErrorCategory::InvalidInput,
133 WebhookError::Replayed(_) => ErrorCategory::Conflict,
134 WebhookError::MissingHeader(_)
135 | WebhookError::MalformedHeader { .. }
136 | WebhookError::SignatureMismatch
137 | WebhookError::TimestampExpired { .. }
138 | WebhookError::TimestampInFuture { .. } => ErrorCategory::Unauthorized,
139 };
140 AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
141 }
142}
143
144#[derive(Clone, PartialEq, Eq)]
159pub struct WebhookSecret {
160 key: Arc<[u8]>,
161}
162
163impl std::fmt::Debug for WebhookSecret {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 f.debug_struct("WebhookSecret").field("key", &"[REDACTED]").finish()
166 }
167}
168
169impl WebhookSecret {
170 pub fn from_base64(secret: &str) -> Result<Self, WebhookError> {
177 let encoded = secret.trim().strip_prefix("whsec_").unwrap_or(secret.trim());
178 let key = base64::engine::general_purpose::STANDARD
179 .decode(encoded)
180 .map_err(|e| WebhookError::InvalidSecret(format!("base64 decode failed: {e}")))?;
181 Self::from_bytes(key)
182 }
183
184 pub fn from_bytes(key: impl Into<Vec<u8>>) -> Result<Self, WebhookError> {
190 let key = key.into();
191 if key.is_empty() {
192 return Err(WebhookError::InvalidSecret("the secret is empty".to_string()));
193 }
194 Ok(Self { key: key.into() })
195 }
196
197 pub fn to_whsec(&self) -> String {
199 format!("whsec_{}", base64::engine::general_purpose::STANDARD.encode(&self.key))
200 }
201
202 fn mac(&self, id: &str, timestamp: &str, body: &[u8]) -> HmacSha256 {
203 let mut mac = HmacSha256::new_from_slice(&self.key).expect("HMAC accepts any key length");
205 mac.update(id.as_bytes());
206 mac.update(b".");
207 mac.update(timestamp.as_bytes());
208 mac.update(b".");
209 mac.update(body);
210 mac
211 }
212
213 pub fn signature(&self, id: &str, timestamp: i64, body: &[u8]) -> String {
227 let digest = self.mac(id, ×tamp.to_string(), body).finalize().into_bytes();
228 format!("v1,{}", base64::engine::general_purpose::STANDARD.encode(digest))
229 }
230}
231
232#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct SignedWebhook {
235 pub id: String,
237 pub timestamp: i64,
239 pub signature: String,
241}
242
243impl SignedWebhook {
244 pub fn as_headers(&self) -> WebhookHeaders<'_> {
246 WebhookHeaders {
247 id: &self.id,
248 timestamp: std::borrow::Cow::Owned(self.timestamp.to_string()),
249 signature: &self.signature,
250 }
251 }
252
253 pub fn header_pairs(&self) -> [(&'static str, String); 3] {
255 [
256 (WEBHOOK_ID_HEADER, self.id.clone()),
257 (WEBHOOK_TIMESTAMP_HEADER, self.timestamp.to_string()),
258 (WEBHOOK_SIGNATURE_HEADER, self.signature.clone()),
259 ]
260 }
261}
262
263#[derive(Debug, Clone)]
280pub struct WebhookSigner {
281 secrets: Vec<WebhookSecret>,
282 clock: Arc<dyn Clock>,
283}
284
285impl WebhookSigner {
286 pub fn new(secret: WebhookSecret) -> Self {
288 Self { secrets: vec![secret], clock: Arc::new(SystemClock) }
289 }
290
291 pub fn with_secret(mut self, secret: WebhookSecret) -> Self {
293 self.secrets.push(secret);
294 self
295 }
296
297 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
299 self.clock = clock;
300 self
301 }
302
303 pub fn sign(&self, id: &str, timestamp: i64, body: &[u8]) -> SignedWebhook {
305 let signature = self
306 .secrets
307 .iter()
308 .map(|secret| secret.signature(id, timestamp, body))
309 .collect::<Vec<_>>()
310 .join(" ");
311 SignedWebhook { id: id.to_string(), timestamp, signature }
312 }
313
314 pub fn sign_now(&self, id: &str, body: &[u8]) -> SignedWebhook {
316 self.sign(id, self.clock.now().timestamp(), body)
317 }
318}
319
320#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct WebhookHeaders<'a> {
340 pub id: &'a str,
342 pub timestamp: std::borrow::Cow<'a, str>,
344 pub signature: &'a str,
346}
347
348impl<'a> WebhookHeaders<'a> {
349 pub fn from_lookup(
357 lookup: impl Fn(&'static str) -> Option<&'a str>,
358 ) -> Result<Self, WebhookError> {
359 let header = |name| lookup(name).ok_or(WebhookError::MissingHeader(name));
360 let id = header(WEBHOOK_ID_HEADER)?;
361 if id.trim().is_empty() || id.len() > 256 {
362 return Err(WebhookError::MalformedHeader {
363 header: WEBHOOK_ID_HEADER,
364 reason: "must contain 1 to 256 bytes".to_string(),
365 });
366 }
367 Ok(Self {
368 id,
369 timestamp: std::borrow::Cow::Borrowed(header(WEBHOOK_TIMESTAMP_HEADER)?),
370 signature: header(WEBHOOK_SIGNATURE_HEADER)?,
371 })
372 }
373}
374
375#[derive(Debug, Clone, PartialEq, Eq)]
377pub struct VerifiedWebhook {
378 pub id: String,
380 pub timestamp: DateTime<Utc>,
382}
383
384#[derive(Debug, Clone)]
402pub struct WebhookVerifier {
403 secrets: Vec<WebhookSecret>,
404 tolerance: Duration,
405 clock: Arc<dyn Clock>,
406}
407
408impl WebhookVerifier {
409 pub fn new(secret: WebhookSecret) -> Self {
411 Self {
412 secrets: vec![secret],
413 tolerance: DEFAULT_WEBHOOK_TOLERANCE,
414 clock: Arc::new(SystemClock),
415 }
416 }
417
418 pub fn with_secret(mut self, secret: WebhookSecret) -> Self {
420 self.secrets.push(secret);
421 self
422 }
423
424 pub fn with_tolerance(mut self, tolerance: Duration) -> Self {
426 self.tolerance = tolerance;
427 self
428 }
429
430 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
432 self.clock = clock;
433 self
434 }
435
436 pub fn tolerance(&self) -> Duration {
438 self.tolerance
439 }
440
441 pub fn verify(
451 &self,
452 headers: &WebhookHeaders<'_>,
453 body: &[u8],
454 ) -> Result<VerifiedWebhook, WebhookError> {
455 let raw_timestamp = headers.timestamp.trim();
456 let timestamp: i64 = raw_timestamp.parse().map_err(|_| WebhookError::MalformedHeader {
457 header: WEBHOOK_TIMESTAMP_HEADER,
458 reason: "not an integer number of seconds".to_string(),
459 })?;
460 let now = self.clock.now().timestamp();
461 let tolerance = self.tolerance.as_secs();
462 let distance = now.abs_diff(timestamp);
463 if distance > tolerance {
464 return Err(if timestamp < now {
465 WebhookError::TimestampExpired { age_seconds: distance, max_age_seconds: tolerance }
466 } else {
467 WebhookError::TimestampInFuture {
468 skew_seconds: distance,
469 max_skew_seconds: tolerance,
470 }
471 });
472 }
473
474 let candidates: Vec<Vec<u8>> = headers
475 .signature
476 .split_whitespace()
477 .filter_map(|entry| entry.strip_prefix("v1,"))
478 .filter_map(|encoded| base64::engine::general_purpose::STANDARD.decode(encoded).ok())
479 .collect();
480 if candidates.is_empty() {
481 return Err(WebhookError::MalformedHeader {
482 header: WEBHOOK_SIGNATURE_HEADER,
483 reason: "no `v1,<base64>` signature".to_string(),
484 });
485 }
486 let matched = self.secrets.iter().any(|secret| {
487 let mac = secret.mac(headers.id, raw_timestamp, body);
488 candidates.iter().any(|candidate| mac.clone().verify_slice(candidate).is_ok())
490 });
491 if !matched {
492 return Err(WebhookError::SignatureMismatch);
493 }
494 let timestamp = DateTime::from_timestamp(timestamp, 0).ok_or_else(|| {
495 WebhookError::MalformedHeader {
496 header: WEBHOOK_TIMESTAMP_HEADER,
497 reason: "out of range".to_string(),
498 }
499 })?;
500 Ok(VerifiedWebhook { id: headers.id.to_string(), timestamp })
501 }
502}
503
504#[async_trait]
510pub trait WebhookReplayGuard: Send + Sync {
511 async fn first_seen(&self, id: &str, keep_until: DateTime<Utc>) -> crate::Result<bool>;
518}
519
520#[derive(Debug)]
536pub struct InMemoryWebhookReplayGuard {
537 seen: std::sync::Mutex<HashMap<String, DateTime<Utc>>>,
538 clock: Arc<dyn Clock>,
539}
540
541impl Default for InMemoryWebhookReplayGuard {
542 fn default() -> Self {
543 Self::new()
544 }
545}
546
547impl InMemoryWebhookReplayGuard {
548 pub fn new() -> Self {
550 Self { seen: std::sync::Mutex::new(HashMap::new()), clock: Arc::new(SystemClock) }
551 }
552
553 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
555 self.clock = clock;
556 self
557 }
558
559 pub fn record(&self, id: &str, keep_until: DateTime<Utc>) -> bool {
562 let now = self.clock.now();
563 let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
564 seen.retain(|_, until| *until > now);
565 if seen.contains_key(id) {
566 return false;
567 }
568 seen.insert(id.to_string(), keep_until);
569 true
570 }
571}
572
573#[async_trait]
574impl WebhookReplayGuard for InMemoryWebhookReplayGuard {
575 async fn first_seen(&self, id: &str, keep_until: DateTime<Utc>) -> crate::Result<bool> {
576 Ok(self.record(id, keep_until))
577 }
578}
579
580pub fn replay_window(tolerance: Duration) -> Duration {
590 tolerance.saturating_mul(2)
591}
592
593#[cfg(test)]
594mod tests {
595 use super::*;
596 use crate::ManualClock;
597
598 const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
599 const NOW: i64 = 1_760_000_000;
600
601 fn clock() -> Arc<ManualClock> {
602 Arc::new(ManualClock::new(DateTime::from_timestamp(NOW, 0).unwrap()))
603 }
604
605 fn secret(text: &str) -> WebhookSecret {
606 WebhookSecret::from_bytes(text.as_bytes().to_vec()).unwrap()
607 }
608
609 #[test]
610 fn reference_vector_matches() {
611 let secret = WebhookSecret::from_base64(SECRET).unwrap();
612 let body = br#"{"test": 2432232314}"#;
613 let signed = WebhookSigner::new(secret.clone()).sign(
614 "msg_p5jXN8AQM9LWM0D4loKWxJek",
615 1_614_265_330,
616 body,
617 );
618 assert_eq!(signed.signature, "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=");
619 let verifier = WebhookVerifier::new(secret).with_clock(Arc::new(ManualClock::new(
620 DateTime::from_timestamp(1_614_265_330, 0).unwrap(),
621 )));
622 assert_eq!(verifier.verify(&signed.as_headers(), body).unwrap().id, signed.id);
623 }
624
625 #[test]
626 fn valid_signature_is_accepted() {
627 let clock = clock();
628 let signer = WebhookSigner::new(secret("a")).with_clock(clock.clone());
629 let signed = signer.sign_now("msg_1", b"{}");
630 let verified =
631 WebhookVerifier::new(secret("a")).with_clock(clock).verify(&signed.as_headers(), b"{}");
632 assert_eq!(
633 verified,
634 Ok(VerifiedWebhook {
635 id: "msg_1".to_string(),
636 timestamp: DateTime::from_timestamp(NOW, 0).unwrap()
637 })
638 );
639 }
640
641 #[test]
642 fn tampered_body_wrong_secret_and_wrong_id_are_rejected() {
643 let clock = clock();
644 let signed = WebhookSigner::new(secret("a")).sign("msg_1", NOW, b"{}");
645 let verifier = WebhookVerifier::new(secret("a")).with_clock(clock.clone());
646 assert_eq!(
647 verifier.verify(&signed.as_headers(), b"{\"x\":1}"),
648 Err(WebhookError::SignatureMismatch)
649 );
650 let other = WebhookVerifier::new(secret("b")).with_clock(clock.clone());
651 assert_eq!(other.verify(&signed.as_headers(), b"{}"), Err(WebhookError::SignatureMismatch));
652 let mut renamed = signed.clone();
653 renamed.id = "msg_other".to_string();
654 assert_eq!(
655 verifier.verify(&renamed.as_headers(), b"{}"),
656 Err(WebhookError::SignatureMismatch)
657 );
658 }
659
660 #[test]
661 fn expired_and_future_timestamps_are_rejected() {
662 let clock = clock();
663 let verifier = WebhookVerifier::new(secret("a")).with_clock(clock);
664 let signer = WebhookSigner::new(secret("a"));
665 let old = signer.sign("msg_1", NOW - 301, b"{}");
666 assert_eq!(
667 verifier.verify(&old.as_headers(), b"{}"),
668 Err(WebhookError::TimestampExpired { age_seconds: 301, max_age_seconds: 300 })
669 );
670 let future = signer.sign("msg_1", NOW + 301, b"{}");
671 assert_eq!(
672 verifier.verify(&future.as_headers(), b"{}"),
673 Err(WebhookError::TimestampInFuture { skew_seconds: 301, max_skew_seconds: 300 })
674 );
675 let edge = signer.sign("msg_1", NOW - 300, b"{}");
676 assert!(verifier.verify(&edge.as_headers(), b"{}").is_ok());
677 }
678
679 #[test]
680 fn rotation_accepts_either_key_from_either_side() {
681 let clock = clock();
682 let both =
684 WebhookSigner::new(secret("old")).with_secret(secret("new")).sign("m", NOW, b"{}");
685 let old_receiver = WebhookVerifier::new(secret("old")).with_clock(clock.clone());
686 let new_receiver = WebhookVerifier::new(secret("new")).with_clock(clock.clone());
687 assert!(old_receiver.verify(&both.as_headers(), b"{}").is_ok());
688 assert!(new_receiver.verify(&both.as_headers(), b"{}").is_ok());
689 let receiver =
691 WebhookVerifier::new(secret("old")).with_secret(secret("new")).with_clock(clock);
692 for key in ["old", "new"] {
693 let signed = WebhookSigner::new(secret(key)).sign("m", NOW, b"{}");
694 assert!(receiver.verify(&signed.as_headers(), b"{}").is_ok(), "{key}");
695 }
696 let retired = WebhookSigner::new(secret("retired")).sign("m", NOW, b"{}");
697 assert_eq!(
698 receiver.verify(&retired.as_headers(), b"{}"),
699 Err(WebhookError::SignatureMismatch)
700 );
701 }
702
703 #[test]
704 fn malformed_headers_are_rejected() {
705 let verifier = WebhookVerifier::new(secret("a")).with_clock(clock());
706 let headers = WebhookHeaders { id: "m", timestamp: "soon".into(), signature: "v1,AAAA" };
707 assert!(matches!(
708 verifier.verify(&headers, b"{}"),
709 Err(WebhookError::MalformedHeader { header: WEBHOOK_TIMESTAMP_HEADER, .. })
710 ));
711 let headers =
712 WebhookHeaders { id: "m", timestamp: NOW.to_string().into(), signature: "v2,AAAA" };
713 assert!(matches!(
714 verifier.verify(&headers, b"{}"),
715 Err(WebhookError::MalformedHeader { header: WEBHOOK_SIGNATURE_HEADER, .. })
716 ));
717 assert_eq!(
718 WebhookHeaders::from_lookup(|_| None),
719 Err(WebhookError::MissingHeader(WEBHOOK_ID_HEADER))
720 );
721 assert!(WebhookSecret::from_base64("whsec_").is_err());
722 assert!(WebhookSecret::from_base64("not base64!").is_err());
723 }
724
725 #[tokio::test]
726 async fn replay_guard_refuses_a_second_delivery_until_the_window_passes() {
727 let clock = clock();
728 let guard = InMemoryWebhookReplayGuard::new().with_clock(clock.clone());
729 let until = clock.now()
730 + chrono::Duration::from_std(replay_window(DEFAULT_WEBHOOK_TOLERANCE)).unwrap();
731 assert!(guard.first_seen("m", until).await.unwrap());
732 assert!(!guard.first_seen("m", until).await.unwrap());
733 clock.advance(Duration::from_secs(601));
734 assert!(guard.first_seen("m", until).await.unwrap());
735 }
736}