Skip to main content

adk_core/
webhook.rs

1//! [Standard Webhooks](https://www.standardwebhooks.com/) signing and verification.
2//!
3//! Every inbound wake-up endpoint and every outbound delivery in ADK-Rust uses this one
4//! implementation (feature `webhooks`):
5//!
6//! | Header | Value |
7//! |--------|-------|
8//! | `webhook-id` | The message identifier; identical on every retry of one message |
9//! | `webhook-timestamp` | Unix seconds when this attempt was signed |
10//! | `webhook-signature` | Space-separated `v1,<base64>` signatures; any one may match |
11//!
12//! Each signature is HMAC-SHA256, keyed with the secret's bytes, over
13//! `{webhook-id}.{webhook-timestamp}.{raw body}`.
14//!
15//! | Guarantee | Mechanism |
16//! |-----------|-----------|
17//! | Authenticity | [`WebhookVerifier`] recomputes the HMAC and compares in constant time |
18//! | Freshness | The timestamp must be within the tolerance (default five minutes) of the local clock, in either direction |
19//! | Key rotation | The verifier holds several secrets and the header carries several signatures; one match from any pair is enough |
20//! | Replay protection | A replay outside the tolerance fails the timestamp check; inside it, [`WebhookReplayGuard`] remembers the `webhook-id` for twice the tolerance. The run-store ingress uses the `webhook-id` as the run's idempotency key instead |
21//!
22//! # Example
23//!
24//! ```rust
25//! use adk_core::webhook::{WebhookHeaders, WebhookSecret, WebhookSigner, WebhookVerifier};
26//!
27//! let secret = WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw")?;
28//! let signer = WebhookSigner::new(secret.clone());
29//! let body = br#"{"event":"invoice.paid"}"#;
30//! let signed = signer.sign_now("msg_1", body);
31//!
32//! let verifier = WebhookVerifier::new(secret);
33//! let verified = verifier.verify(&signed.as_headers(), body)?;
34//! assert_eq!(verified.id, "msg_1");
35//! # Ok::<(), adk_core::webhook::WebhookError>(())
36//! ```
37
38use 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
52/// The `webhook-id` header name.
53pub const WEBHOOK_ID_HEADER: &str = "webhook-id";
54/// The `webhook-timestamp` header name.
55pub const WEBHOOK_TIMESTAMP_HEADER: &str = "webhook-timestamp";
56/// The `webhook-signature` header name.
57pub const WEBHOOK_SIGNATURE_HEADER: &str = "webhook-signature";
58/// Default accepted distance between `webhook-timestamp` and the local clock.
59pub const DEFAULT_WEBHOOK_TOLERANCE: Duration = Duration::from_secs(300);
60
61/// Why a webhook secret, signature, or delivery was rejected.
62///
63/// The reason is for logs. An HTTP endpoint answers every variant with a bare `401`, so
64/// a caller cannot probe which part of a credential was wrong.
65#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
66#[non_exhaustive]
67pub enum WebhookError {
68    /// The secret is empty or not valid base64.
69    #[error(
70        "invalid webhook secret: {0}; pass the base64 secret, optionally prefixed with `whsec_`"
71    )]
72    InvalidSecret(String),
73    /// A required header is absent or not valid UTF-8.
74    #[error("missing webhook header `{0}`; forward the delivery's headers unchanged")]
75    MissingHeader(&'static str),
76    /// A header is present but malformed.
77    #[error("malformed `{header}` header: {reason}")]
78    MalformedHeader {
79        /// The header name.
80        header: &'static str,
81        /// What is wrong with it.
82        reason: String,
83    },
84    /// No `v1` signature matches any configured secret.
85    #[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    /// The delivery was signed longer ago than the tolerance.
91    #[error("webhook delivery is {age_seconds}s old (max {max_age_seconds}s)")]
92    TimestampExpired {
93        /// Age of the delivery in seconds.
94        age_seconds: u64,
95        /// Accepted age in seconds.
96        max_age_seconds: u64,
97    },
98    /// The delivery timestamp is further in the future than the tolerance.
99    #[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        /// How far ahead of the local clock the timestamp is, in seconds.
105        skew_seconds: u64,
106        /// Accepted skew in seconds.
107        max_skew_seconds: u64,
108    },
109    /// A delivery with this `webhook-id` was already accepted.
110    #[error("webhook `{0}` was already received; a replay is ignored")]
111    Replayed(String),
112}
113
114impl WebhookError {
115    /// A stable code for logs and metrics, such as `webhook.signature_mismatch`.
116    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/// A webhook signing secret.
145///
146/// `Debug` redacts the key.
147///
148/// # Example
149///
150/// ```rust
151/// use adk_core::webhook::WebhookSecret;
152///
153/// let secret = WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw")?;
154/// assert_eq!(secret.to_whsec(), "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw");
155/// assert!(format!("{secret:?}").contains("REDACTED"));
156/// # Ok::<(), adk_core::webhook::WebhookError>(())
157/// ```
158#[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    /// Decodes a base64 secret, optionally prefixed with `whsec_`.
171    ///
172    /// # Errors
173    ///
174    /// Returns [`WebhookError::InvalidSecret`] when the secret is not base64 or decodes
175    /// to no bytes.
176    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    /// Uses `key` as the HMAC key as is.
185    ///
186    /// # Errors
187    ///
188    /// Returns [`WebhookError::InvalidSecret`] when `key` is empty.
189    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    /// The secret in its `whsec_<base64>` form, as receivers configure it.
198    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        // HMAC accepts keys of any length, and `from_bytes` refuses an empty one.
204        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    /// The `v1,<base64>` signature of one message.
214    ///
215    /// # Example
216    ///
217    /// ```rust
218    /// use adk_core::webhook::WebhookSecret;
219    ///
220    /// // The Standard Webhooks reference test vector.
221    /// let secret = WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw")?;
222    /// let signature = secret.signature("msg_p5jXN8AQM9LWM0D4loKWxJek", 1614265330, br#"{"test": 2432232314}"#);
223    /// assert_eq!(signature, "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=");
224    /// # Ok::<(), adk_core::webhook::WebhookError>(())
225    /// ```
226    pub fn signature(&self, id: &str, timestamp: i64, body: &[u8]) -> String {
227        let digest = self.mac(id, &timestamp.to_string(), body).finalize().into_bytes();
228        format!("v1,{}", base64::engine::general_purpose::STANDARD.encode(digest))
229    }
230}
231
232/// The three headers of one signed delivery attempt.
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub struct SignedWebhook {
235    /// The `webhook-id` value.
236    pub id: String,
237    /// The `webhook-timestamp` value, Unix seconds.
238    pub timestamp: i64,
239    /// The `webhook-signature` value.
240    pub signature: String,
241}
242
243impl SignedWebhook {
244    /// Borrows the values as [`WebhookHeaders`], with the timestamp rendered as text.
245    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    /// The headers as `(name, value)` pairs, ready for an HTTP client.
254    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/// Signs outbound deliveries.
264///
265/// During a key rotation, [`with_secret`](Self::with_secret) adds the next secret and
266/// every delivery carries one signature per secret, so receivers on either key accept it.
267///
268/// # Example
269///
270/// ```rust
271/// use adk_core::webhook::{WebhookSecret, WebhookSigner};
272///
273/// let old = WebhookSecret::from_bytes(b"old-secret-old-secret-old-secret".to_vec())?;
274/// let new = WebhookSecret::from_bytes(b"new-secret-new-secret-new-secret".to_vec())?;
275/// let signed = WebhookSigner::new(old).with_secret(new).sign("msg_1", 1_760_000_000, b"{}");
276/// assert_eq!(signed.signature.split(' ').count(), 2);
277/// # Ok::<(), adk_core::webhook::WebhookError>(())
278/// ```
279#[derive(Debug, Clone)]
280pub struct WebhookSigner {
281    secrets: Vec<WebhookSecret>,
282    clock: Arc<dyn Clock>,
283}
284
285impl WebhookSigner {
286    /// Creates a signer with one secret that reads the system clock.
287    pub fn new(secret: WebhookSecret) -> Self {
288        Self { secrets: vec![secret], clock: Arc::new(SystemClock) }
289    }
290
291    /// Adds another secret; each delivery carries a signature per secret.
292    pub fn with_secret(mut self, secret: WebhookSecret) -> Self {
293        self.secrets.push(secret);
294        self
295    }
296
297    /// Sets the clock [`sign_now`](Self::sign_now) reads.
298    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
299        self.clock = clock;
300        self
301    }
302
303    /// Signs `body` as message `id` at `timestamp` (Unix seconds).
304    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    /// Signs `body` as message `id` at the current time.
315    pub fn sign_now(&self, id: &str, body: &[u8]) -> SignedWebhook {
316        self.sign(id, self.clock.now().timestamp(), body)
317    }
318}
319
320/// The Standard Webhooks headers of an inbound delivery.
321///
322/// # Example
323///
324/// ```rust
325/// use adk_core::webhook::WebhookHeaders;
326/// use std::collections::HashMap;
327///
328/// let headers: HashMap<&str, &str> = [
329///     ("webhook-id", "msg_1"),
330///     ("webhook-timestamp", "1760000000"),
331///     ("webhook-signature", "v1,c2ln"),
332/// ]
333/// .into();
334/// let parsed = WebhookHeaders::from_lookup(|name| headers.get(name).copied())?;
335/// assert_eq!(parsed.id, "msg_1");
336/// # Ok::<(), adk_core::webhook::WebhookError>(())
337/// ```
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct WebhookHeaders<'a> {
340    /// The `webhook-id` header.
341    pub id: &'a str,
342    /// The `webhook-timestamp` header, as received.
343    pub timestamp: std::borrow::Cow<'a, str>,
344    /// The `webhook-signature` header.
345    pub signature: &'a str,
346}
347
348impl<'a> WebhookHeaders<'a> {
349    /// Reads the three headers through `lookup`, which returns a header's value by
350    /// lowercase name.
351    ///
352    /// # Errors
353    ///
354    /// Returns [`WebhookError::MissingHeader`] when a header is absent, and
355    /// [`WebhookError::MalformedHeader`] when the `webhook-id` is empty.
356    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/// A delivery whose signature and timestamp checked out.
376#[derive(Debug, Clone, PartialEq, Eq)]
377pub struct VerifiedWebhook {
378    /// The `webhook-id`: identical across retries of one message.
379    pub id: String,
380    /// When the sender signed this attempt.
381    pub timestamp: DateTime<Utc>,
382}
383
384/// Verifies inbound Standard Webhooks deliveries.
385///
386/// Holds one or more secrets: add the next secret with
387/// [`with_secret`](Self::with_secret) before the sender rotates, and remove the old one
388/// after.
389///
390/// # Example
391///
392/// ```rust
393/// use adk_core::webhook::{WebhookError, WebhookHeaders, WebhookSecret, WebhookVerifier};
394///
395/// let verifier = WebhookVerifier::new(WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw")?);
396/// let headers = WebhookHeaders { id: "msg_1", timestamp: "0".into(), signature: "v1,AAAA" };
397/// // Signed in 1970: far outside the five-minute tolerance.
398/// assert!(matches!(verifier.verify(&headers, b"{}"), Err(WebhookError::TimestampExpired { .. })));
399/// # Ok::<(), WebhookError>(())
400/// ```
401#[derive(Debug, Clone)]
402pub struct WebhookVerifier {
403    secrets: Vec<WebhookSecret>,
404    tolerance: Duration,
405    clock: Arc<dyn Clock>,
406}
407
408impl WebhookVerifier {
409    /// Creates a verifier with one secret, the default tolerance, and the system clock.
410    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    /// Accepts signatures made with `secret` as well.
419    pub fn with_secret(mut self, secret: WebhookSecret) -> Self {
420        self.secrets.push(secret);
421        self
422    }
423
424    /// Sets the accepted distance between `webhook-timestamp` and the local clock.
425    pub fn with_tolerance(mut self, tolerance: Duration) -> Self {
426        self.tolerance = tolerance;
427        self
428    }
429
430    /// Sets the clock the timestamp is compared against.
431    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
432        self.clock = clock;
433        self
434    }
435
436    /// The accepted timestamp distance.
437    pub fn tolerance(&self) -> Duration {
438        self.tolerance
439    }
440
441    /// Checks the timestamp, then the signature, of a delivery.
442    ///
443    /// `body` must be the raw request body: re-serialized JSON changes the bytes and
444    /// fails verification.
445    ///
446    /// # Errors
447    ///
448    /// Returns a [`WebhookError`] when the timestamp is malformed or outside the
449    /// tolerance, or no signature matches a configured secret.
450    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            // `verify_slice` compares in constant time.
489            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/// Remembers accepted `webhook-id`s so a replay inside the timestamp tolerance is refused.
505///
506/// A replay outside the tolerance already fails [`WebhookVerifier::verify`], so an id
507/// needs to be kept for twice the tolerance only. Use a shared backend when several
508/// replicas receive the same endpoint's deliveries.
509#[async_trait]
510pub trait WebhookReplayGuard: Send + Sync {
511    /// Records `id` until `keep_until` and returns `true` when it was not already recorded.
512    ///
513    /// # Errors
514    ///
515    /// Returns an error when the backing store cannot be reached; callers refuse the
516    /// delivery so the sender retries.
517    async fn first_seen(&self, id: &str, keep_until: DateTime<Utc>) -> crate::Result<bool>;
518}
519
520/// Process-local [`WebhookReplayGuard`].
521///
522/// # Example
523///
524/// ```rust
525/// use adk_core::webhook::{InMemoryWebhookReplayGuard, WebhookReplayGuard};
526///
527/// # futures::executor::block_on(async {
528/// let guard = InMemoryWebhookReplayGuard::new();
529/// let until = chrono::Utc::now() + chrono::Duration::minutes(10);
530/// assert!(guard.first_seen("msg_1", until).await?);
531/// assert!(!guard.first_seen("msg_1", until).await?);
532/// # Ok::<(), adk_core::AdkError>(())
533/// # }).unwrap();
534/// ```
535#[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    /// Creates an empty guard that reads the system clock.
549    pub fn new() -> Self {
550        Self { seen: std::sync::Mutex::new(HashMap::new()), clock: Arc::new(SystemClock) }
551    }
552
553    /// Sets the clock that decides when a recorded id expires.
554    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
555        self.clock = clock;
556        self
557    }
558
559    /// Records `id` until `keep_until`; the synchronous form of
560    /// [`WebhookReplayGuard::first_seen`].
561    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
580/// How long a [`WebhookReplayGuard`] must keep an id accepted under `tolerance`.
581///
582/// # Example
583///
584/// ```rust
585/// use std::time::Duration;
586///
587/// assert_eq!(adk_core::webhook::replay_window(Duration::from_secs(300)), Duration::from_secs(600));
588/// ```
589pub 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        // The sender signs with both keys; a receiver still on the old key accepts it.
683        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        // The receiver holds both keys; a sender on either key is accepted.
690        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}