Skip to main content

timvw_rust_runtime/
webhooks.rs

1//! Webhooks signed as [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md),
2//! as OpenAI sends them: [`StandardWebhooksLayer`] signs what a [`Client`](crate::Client) sends, and [`verify`] checks
3//! what a receiver gets.
4//!
5//! A delivery is a `POST` with three headers:
6//!
7//! - `webhook-id`: the message's id, the same on every retry, which the receiver uses to drop a duplicate;
8//! - `webhook-timestamp`: when it was signed, in Unix seconds;
9//! - `webhook-signature`: `v1,<base64>`, the HMAC-SHA256 of `<id>.<timestamp>.<body>` with the secret, once per
10//!   secret, separated by spaces (so a secret can be rotated).
11//!
12//! The secret is `whsec_` followed by base64, as OpenAI's dashboard and Standard Webhooks libraries give it.
13//!
14//! ```no_run
15//! # #[cfg(feature = "reqwest")]
16//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
17//! use timvw_rust_runtime::webhooks::{StandardWebhooksLayer, WebhookSecret};
18//! use timvw_rust_runtime::{Body, Client};
19//!
20//! let secret = WebhookSecret::new(&std::env::var("WEBHOOK_SECRET")?)?;
21//! // added last, the layer signs once and the retries inside it send the same headers again
22//! let client = Client::default().layer(StandardWebhooksLayer::new(secret));
23//! let response = client
24//!     .request(http::Method::POST, "http://127.0.0.1:8090/hooks")
25//!     .header(http::header::CONTENT_TYPE, "application/json")
26//!     .body(Body::from(r#"{"type":"response.completed"}"#))
27//!     .send()
28//!     .await?;
29//! # Ok(())
30//! # }
31//! ```
32//!
33//! Where the layer sits matters: [`Client::layer`](crate::Client::layer) puts it outside the client's stack, so it
34//! signs once and a retry sends the same `webhook-id`, timestamp and signature. A layer of another scheme is written
35//! the same way; this one is the scheme the runtime ships.
36//!
37//! The receiving side checks the headers against the raw body, before decoding it:
38//!
39//! ```
40//! use std::time::Duration;
41//! use timvw_rust_runtime::webhooks::{verify, WebhookSecret};
42//!
43//! # fn receive(headers: &http::HeaderMap, body: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
44//! let secret = WebhookSecret::new(&std::env::var("WEBHOOK_SECRET")?)?;
45//! verify(headers, body, &[secret], Duration::from_secs(5 * 60))?;
46//! let event: serde_json::Value = serde_json::from_slice(body)?;
47//! # Ok(())
48//! # }
49//! ```
50
51use std::fmt;
52use std::future::{ready, Ready};
53use std::sync::atomic::{AtomicU64, Ordering};
54use std::sync::Arc;
55use std::task::{Context, Poll};
56use std::time::Duration;
57
58use base64::Engine as _;
59use futures_util::future::{Either, MapErr};
60use futures_util::TryFutureExt as _;
61use hmac::{KeyInit, Mac};
62use http::header::HeaderName;
63use http::{HeaderMap, HeaderValue};
64use tower::{Layer, Service};
65
66use crate::{Body, BoxError};
67
68#[cfg(not(target_family = "wasm"))]
69use std::time::{SystemTime, UNIX_EPOCH};
70#[cfg(target_family = "wasm")]
71use web_time::{SystemTime, UNIX_EPOCH};
72
73type HmacSha256 = hmac::Hmac<sha2::Sha256>;
74
75/// `webhook-id`
76pub const WEBHOOK_ID: HeaderName = HeaderName::from_static("webhook-id");
77/// `webhook-timestamp`
78pub const WEBHOOK_TIMESTAMP: HeaderName = HeaderName::from_static("webhook-timestamp");
79/// `webhook-signature`
80pub const WEBHOOK_SIGNATURE: HeaderName = HeaderName::from_static("webhook-signature");
81
82const PREFIX: &str = "whsec_";
83
84/// A webhook signing secret: the key of the HMAC. Its `Debug` does not show it.
85#[derive(Clone, PartialEq, Eq)]
86pub struct WebhookSecret(Arc<[u8]>);
87
88impl WebhookSecret {
89    /// The secret as Standard Webhooks writes it, `whsec_<base64>`; without the prefix, the base64 alone.
90    pub fn new(secret: &str) -> Result<Self, WebhookError> {
91        let encoded = secret.trim();
92        let encoded = encoded.strip_prefix(PREFIX).unwrap_or(encoded);
93        let key = base64::engine::general_purpose::STANDARD
94            .decode(encoded)
95            .map_err(|_| WebhookError::InvalidSecret)?;
96        if key.is_empty() {
97            return Err(WebhookError::InvalidSecret);
98        }
99        Ok(Self(key.into()))
100    }
101
102    /// A secret of these key bytes.
103    pub fn from_bytes(key: impl Into<Vec<u8>>) -> Self {
104        Self(key.into().into())
105    }
106
107    /// `v1,<base64>`: the signature of `<id>.<timestamp>.<body>`.
108    fn sign(&self, id: &str, timestamp: u64, body: &[u8]) -> String {
109        let mac = self.mac(id, timestamp, body);
110        format!(
111            "v1,{}",
112            base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes())
113        )
114    }
115
116    fn mac(&self, id: &str, timestamp: u64, body: &[u8]) -> HmacSha256 {
117        let mut mac = HmacSha256::new_from_slice(&self.0).expect("HMAC takes a key of any length");
118        mac.update(id.as_bytes());
119        mac.update(b".");
120        mac.update(timestamp.to_string().as_bytes());
121        mac.update(b".");
122        mac.update(body);
123        mac
124    }
125}
126
127impl fmt::Debug for WebhookSecret {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.write_str("WebhookSecret([redacted])")
130    }
131}
132
133/// Why a webhook cannot be signed or does not verify.
134#[derive(Clone, Debug, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum WebhookError {
137    /// The secret is not `whsec_` followed by base64.
138    InvalidSecret,
139    /// The request lacks this header, or it is not text.
140    MissingHeader(HeaderName),
141    /// `webhook-timestamp` is not a number of seconds.
142    InvalidTimestamp,
143    /// `webhook-timestamp` is further from now than the tolerance: an old message replayed, or a clock that is off.
144    TimestampOutOfTolerance,
145    /// No `v1` signature matches a secret.
146    NoMatchingSignature,
147    /// The body streams, so its bytes are not known before it is sent: it cannot be signed.
148    StreamingBody,
149}
150
151impl fmt::Display for WebhookError {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        match self {
154            WebhookError::InvalidSecret => {
155                f.write_str("the webhook secret is not whsec_ followed by base64")
156            }
157            WebhookError::MissingHeader(name) => write!(f, "the webhook has no {name} header"),
158            WebhookError::InvalidTimestamp => {
159                f.write_str("the webhook-timestamp is not a number of seconds")
160            }
161            WebhookError::TimestampOutOfTolerance => {
162                f.write_str("the webhook-timestamp is too far from now")
163            }
164            WebhookError::NoMatchingSignature => f.write_str("no webhook signature matches"),
165            WebhookError::StreamingBody => {
166                f.write_str("a webhook whose body streams cannot be signed")
167            }
168        }
169    }
170}
171
172impl std::error::Error for WebhookError {}
173
174/// Signs every request with one or more secrets, as Standard Webhooks; see the [module](self).
175///
176/// A request that already has a `webhook-id` or `webhook-timestamp` keeps it; any other gets a new id
177/// (`msg_<hex>`) and the current time. The signature is always written, one per secret.
178#[derive(Clone, Debug)]
179pub struct StandardWebhooksLayer {
180    secrets: Arc<[WebhookSecret]>,
181}
182
183impl StandardWebhooksLayer {
184    /// Signs with `secret`.
185    pub fn new(secret: WebhookSecret) -> Self {
186        Self {
187            secrets: Arc::from(vec![secret]),
188        }
189    }
190
191    /// Signs with every one of `secrets` (a secret being rotated, and its successor).
192    pub fn with_secrets(secrets: impl IntoIterator<Item = WebhookSecret>) -> Self {
193        Self {
194            secrets: secrets.into_iter().collect::<Vec<_>>().into(),
195        }
196    }
197}
198
199impl<S> Layer<S> for StandardWebhooksLayer {
200    type Service = StandardWebhooks<S>;
201
202    fn layer(&self, inner: S) -> Self::Service {
203        StandardWebhooks {
204            inner,
205            secrets: self.secrets.clone(),
206        }
207    }
208}
209
210/// The service of a [`StandardWebhooksLayer`].
211#[derive(Clone, Debug)]
212pub struct StandardWebhooks<S> {
213    inner: S,
214    secrets: Arc<[WebhookSecret]>,
215}
216
217impl<S> Service<http::Request<Body>> for StandardWebhooks<S>
218where
219    S: Service<http::Request<Body>>,
220    S::Error: Into<BoxError>,
221{
222    type Response = S::Response;
223    type Error = BoxError;
224    #[allow(clippy::type_complexity)]
225    type Future =
226        Either<Ready<Result<S::Response, BoxError>>, MapErr<S::Future, fn(S::Error) -> BoxError>>;
227
228    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
229        self.inner.poll_ready(cx).map_err(Into::into)
230    }
231
232    fn call(&mut self, mut request: http::Request<Body>) -> Self::Future {
233        if let Err(error) = sign(&mut request, &self.secrets, unix_now()) {
234            return Either::Left(ready(Err(Box::new(error))));
235        }
236        Either::Right(
237            self.inner
238                .call(request)
239                .map_err(into_box_error::<S::Error> as fn(_) -> _),
240        )
241    }
242}
243
244fn into_box_error<E: Into<BoxError>>(error: E) -> BoxError {
245    error.into()
246}
247
248/// Writes the headers of a signed webhook onto `request`, signed at `now` unless it has a timestamp.
249fn sign(
250    request: &mut http::Request<Body>,
251    secrets: &[WebhookSecret],
252    now: u64,
253) -> Result<(), WebhookError> {
254    let body = request
255        .body()
256        .as_bytes()
257        .ok_or(WebhookError::StreamingBody)?
258        .to_vec();
259    let headers = request.headers_mut();
260    let id = match text(headers, &WEBHOOK_ID) {
261        Some(id) => id.to_owned(),
262        None => {
263            let id = new_id();
264            headers.insert(
265                WEBHOOK_ID,
266                HeaderValue::from_str(&id).expect("an id of ASCII letters and digits"),
267            );
268            id
269        }
270    };
271    let timestamp = match text(headers, &WEBHOOK_TIMESTAMP) {
272        Some(timestamp) => timestamp
273            .parse()
274            .map_err(|_| WebhookError::InvalidTimestamp)?,
275        None => {
276            headers.insert(WEBHOOK_TIMESTAMP, HeaderValue::from(now));
277            now
278        }
279    };
280    let signatures: Vec<String> = secrets
281        .iter()
282        .map(|secret| secret.sign(&id, timestamp, &body))
283        .collect();
284    headers.insert(
285        WEBHOOK_SIGNATURE,
286        HeaderValue::from_str(&signatures.join(" ")).expect("signatures of ASCII base64"),
287    );
288    Ok(())
289}
290
291/// Checks a webhook a receiver got: one of its `v1` signatures matches one of `secrets` (compared in constant time),
292/// over the raw `body`, and its timestamp is within `tolerance` of now. Decode the body after it passes.
293pub fn verify(
294    headers: &HeaderMap,
295    body: &[u8],
296    secrets: &[WebhookSecret],
297    tolerance: Duration,
298) -> Result<(), WebhookError> {
299    verify_at(headers, body, secrets, tolerance, unix_now())
300}
301
302fn verify_at(
303    headers: &HeaderMap,
304    body: &[u8],
305    secrets: &[WebhookSecret],
306    tolerance: Duration,
307    now: u64,
308) -> Result<(), WebhookError> {
309    let id = text(headers, &WEBHOOK_ID).ok_or(WebhookError::MissingHeader(WEBHOOK_ID))?;
310    let timestamp: u64 = text(headers, &WEBHOOK_TIMESTAMP)
311        .ok_or(WebhookError::MissingHeader(WEBHOOK_TIMESTAMP))?
312        .parse()
313        .map_err(|_| WebhookError::InvalidTimestamp)?;
314    let signatures =
315        text(headers, &WEBHOOK_SIGNATURE).ok_or(WebhookError::MissingHeader(WEBHOOK_SIGNATURE))?;
316    if now.abs_diff(timestamp) > tolerance.as_secs() {
317        return Err(WebhookError::TimestampOutOfTolerance);
318    }
319    for signature in signatures.split(' ') {
320        let Some(encoded) = signature.strip_prefix("v1,") else {
321            continue;
322        };
323        let Ok(signature) = base64::engine::general_purpose::STANDARD.decode(encoded) else {
324            continue;
325        };
326        if secrets.iter().any(|secret| {
327            secret
328                .mac(id, timestamp, body)
329                .verify_slice(&signature)
330                .is_ok()
331        }) {
332            return Ok(());
333        }
334    }
335    Err(WebhookError::NoMatchingSignature)
336}
337
338fn text<'a>(headers: &'a HeaderMap, name: &HeaderName) -> Option<&'a str> {
339    headers.get(name)?.to_str().ok()
340}
341
342fn unix_now() -> u64 {
343    SystemTime::now()
344        .duration_since(UNIX_EPOCH)
345        .map_or(0, |since| since.as_secs())
346}
347
348/// `msg_` and 32 hex digits from the time, a counter and the process's hash seed: unique, not secret.
349fn new_id() -> String {
350    static COUNTER: AtomicU64 = AtomicU64::new(0);
351    let nanos = SystemTime::now()
352        .duration_since(UNIX_EPOCH)
353        .map_or(0, |since| since.as_nanos() as u64);
354    let count = COUNTER.fetch_add(1, Ordering::Relaxed);
355    let seed = {
356        use std::hash::{BuildHasher, Hasher};
357        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
358        hasher.write_u64(nanos ^ count);
359        hasher.finish()
360    };
361    format!("msg_{:016x}{:016x}", nanos ^ count.rotate_left(48), seed)
362}
363
364#[cfg(all(test, not(target_family = "wasm")))]
365mod tests {
366    use super::*;
367    use tower::ServiceExt;
368
369    // Standard Webhooks' test vector
370    // (https://github.com/standard-webhooks/standard-webhooks/blob/main/libraries/javascript/src/index.test.ts).
371    // Standard Webhooks' public test secret, written in pieces so that secret scanners do not take it for a real one
372    const SECRET: &str = concat!("whsec", "_", "MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw");
373    const ID: &str = "msg_p5jXN8AQM9LWM0D4loKWxJek";
374    const TIMESTAMP: u64 = 1614265330;
375    const BODY: &str = r#"{"test": 2432232314}"#;
376    const SIGNATURE: &str = "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=";
377
378    fn secret() -> WebhookSecret {
379        WebhookSecret::new(SECRET).unwrap()
380    }
381
382    fn headers(id: &str, timestamp: u64, signature: &str) -> HeaderMap {
383        let mut headers = HeaderMap::new();
384        headers.insert(WEBHOOK_ID, HeaderValue::from_str(id).unwrap());
385        headers.insert(WEBHOOK_TIMESTAMP, HeaderValue::from(timestamp));
386        headers.insert(WEBHOOK_SIGNATURE, HeaderValue::from_str(signature).unwrap());
387        headers
388    }
389
390    #[test]
391    fn the_signature_is_standard_webhooks_v1() {
392        assert_eq!(secret().sign(ID, TIMESTAMP, BODY.as_bytes()), SIGNATURE);
393    }
394
395    #[test]
396    fn a_signed_webhook_verifies_within_the_tolerance() {
397        let tolerance = Duration::from_secs(300);
398        let headers = headers(ID, TIMESTAMP, SIGNATURE);
399        assert_eq!(
400            verify_at(
401                &headers,
402                BODY.as_bytes(),
403                &[secret()],
404                tolerance,
405                TIMESTAMP + 300
406            ),
407            Ok(())
408        );
409        assert_eq!(
410            verify_at(
411                &headers,
412                BODY.as_bytes(),
413                &[secret()],
414                tolerance,
415                TIMESTAMP + 301
416            ),
417            Err(WebhookError::TimestampOutOfTolerance)
418        );
419        assert_eq!(
420            verify_at(
421                &headers,
422                BODY.as_bytes(),
423                &[secret()],
424                tolerance,
425                TIMESTAMP - 301
426            ),
427            Err(WebhookError::TimestampOutOfTolerance)
428        );
429    }
430
431    #[test]
432    fn a_changed_body_id_or_secret_does_not_verify() {
433        let tolerance = Duration::from_secs(300);
434        let check = |headers: &HeaderMap, body: &str, secrets: &[WebhookSecret]| {
435            verify_at(headers, body.as_bytes(), secrets, tolerance, TIMESTAMP)
436        };
437        let signed = headers(ID, TIMESTAMP, SIGNATURE);
438        assert_eq!(
439            check(&signed, r#"{"test": 2432232315}"#, &[secret()]),
440            Err(WebhookError::NoMatchingSignature)
441        );
442        assert_eq!(
443            check(
444                &headers("msg_other", TIMESTAMP, SIGNATURE),
445                BODY,
446                &[secret()]
447            ),
448            Err(WebhookError::NoMatchingSignature)
449        );
450        let other = WebhookSecret::from_bytes(b"another key".to_vec());
451        assert_eq!(
452            check(&signed, BODY, std::slice::from_ref(&other)),
453            Err(WebhookError::NoMatchingSignature)
454        );
455        // rotation: any secret, any signature
456        assert_eq!(check(&signed, BODY, &[other, secret()]), Ok(()));
457        let two = headers(ID, TIMESTAMP, &format!("v1,bm90IGl0 v2a,xyz {SIGNATURE}"));
458        assert_eq!(check(&two, BODY, &[secret()]), Ok(()));
459    }
460
461    #[test]
462    fn missing_or_invalid_headers_are_named() {
463        let tolerance = Duration::from_secs(300);
464        let mut headers = headers(ID, TIMESTAMP, SIGNATURE);
465        headers.insert(WEBHOOK_TIMESTAMP, HeaderValue::from_static("soon"));
466        assert_eq!(
467            verify_at(&headers, BODY.as_bytes(), &[secret()], tolerance, TIMESTAMP),
468            Err(WebhookError::InvalidTimestamp)
469        );
470        headers.insert(WEBHOOK_TIMESTAMP, HeaderValue::from(TIMESTAMP));
471        headers.remove(WEBHOOK_SIGNATURE);
472        assert_eq!(
473            verify_at(&headers, BODY.as_bytes(), &[secret()], tolerance, TIMESTAMP),
474            Err(WebhookError::MissingHeader(WEBHOOK_SIGNATURE))
475        );
476        headers.remove(WEBHOOK_ID);
477        assert_eq!(
478            verify_at(&headers, BODY.as_bytes(), &[secret()], tolerance, TIMESTAMP),
479            Err(WebhookError::MissingHeader(WEBHOOK_ID))
480        );
481    }
482
483    #[test]
484    fn a_secret_is_whsec_and_base64_and_does_not_show() {
485        assert_eq!(
486            WebhookSecret::new("whsec_not base64!"),
487            Err(WebhookError::InvalidSecret)
488        );
489        assert_eq!(
490            WebhookSecret::new("whsec_"),
491            Err(WebhookError::InvalidSecret)
492        );
493        // without the prefix, the base64 alone
494        assert_eq!(
495            WebhookSecret::new("MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw").unwrap(),
496            secret()
497        );
498        assert_eq!(format!("{:?}", secret()), "WebhookSecret([redacted])");
499    }
500
501    #[tokio::test]
502    async fn the_layer_signs_what_it_sends_and_keeps_a_given_id() {
503        let echo =
504            tower::service_fn(
505                |request: http::Request<Body>| async move { Ok::<_, BoxError>(request) },
506            );
507        let layer = StandardWebhooksLayer::new(secret());
508        let mut request = http::Request::new(Body::from(BODY));
509        request
510            .headers_mut()
511            .insert(WEBHOOK_ID, HeaderValue::from_static(ID));
512        let sent = layer.layer(echo).oneshot(request).await.unwrap();
513        assert_eq!(sent.headers()[WEBHOOK_ID], ID);
514        let timestamp: u64 = sent.headers()[WEBHOOK_TIMESTAMP]
515            .to_str()
516            .unwrap()
517            .parse()
518            .unwrap();
519        assert!(timestamp.abs_diff(unix_now()) <= 1);
520        // what the receiver checks
521        verify(
522            sent.headers(),
523            BODY.as_bytes(),
524            &[secret()],
525            Duration::from_secs(5),
526        )
527        .unwrap();
528    }
529
530    #[tokio::test]
531    async fn the_layer_gives_each_message_its_own_id_and_signs_with_every_secret() {
532        let echo =
533            tower::service_fn(
534                |request: http::Request<Body>| async move { Ok::<_, BoxError>(request) },
535            );
536        let next = WebhookSecret::from_bytes(b"the next key".to_vec());
537        let service = StandardWebhooksLayer::with_secrets([secret(), next.clone()]).layer(echo);
538        let first = service
539            .clone()
540            .oneshot(http::Request::new(Body::from(BODY)))
541            .await
542            .unwrap();
543        let second = service
544            .oneshot(http::Request::new(Body::from(BODY)))
545            .await
546            .unwrap();
547        let id = first.headers()[WEBHOOK_ID].to_str().unwrap();
548        assert!(id.starts_with("msg_") && id.len() == 36, "{id}");
549        assert_ne!(first.headers()[WEBHOOK_ID], second.headers()[WEBHOOK_ID]);
550        let signatures = first.headers()[WEBHOOK_SIGNATURE].to_str().unwrap();
551        assert_eq!(signatures.split(' ').count(), 2);
552        // either secret alone verifies
553        verify(
554            first.headers(),
555            BODY.as_bytes(),
556            &[next],
557            Duration::from_secs(5),
558        )
559        .unwrap();
560    }
561
562    #[tokio::test]
563    async fn a_body_that_streams_is_not_sent_unsigned() {
564        let never = tower::service_fn(|_: http::Request<Body>| async move {
565            panic!("a request that cannot be signed is not sent");
566            #[allow(unreachable_code)]
567            Ok::<(), BoxError>(())
568        });
569        let stream =
570            futures_util::stream::iter([Ok::<_, std::io::Error>(bytes::Bytes::from_static(b"{}"))]);
571        let request = http::Request::new(Body::wrap_stream(stream));
572        let error = StandardWebhooksLayer::new(secret())
573            .layer(never)
574            .oneshot(request)
575            .await
576            .unwrap_err();
577        assert_eq!(
578            error.downcast_ref::<WebhookError>(),
579            Some(&WebhookError::StreamingBody)
580        );
581    }
582}