Skip to main content

wellfriend/
webhooks.rs

1//! Verifying signed webhook deliveries (Standard Webhooks, HMAC-SHA256).
2
3use std::collections::HashMap;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use base64::Engine;
7use hmac::{Hmac, Mac};
8use reqwest::header::HeaderMap;
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use sha2::Sha256;
12
13use crate::client::{RequestOptions, Wellfriend};
14use crate::error::{Error, Result};
15use crate::generated::events::WebhookEventData;
16use crate::Object;
17
18/// How far a delivery's timestamp may be from now (5 minutes).
19pub const DEFAULT_TOLERANCE: Duration = Duration::from_secs(300);
20
21/// A verified webhook event (CloudEvents 1.0).
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23#[non_exhaustive]
24pub struct WebhookEvent {
25    /// The event id (`evt_...`), also sent as `webhook-id`. Deduplicate on it.
26    pub id: String,
27    /// The event type, for example `com.wellfriend.document-operation.completed.v2`.
28    #[serde(rename = "type")]
29    pub event_type: String,
30    /// The workspace that produced the event (`wellfriend://workspaces/ws_...`).
31    #[serde(default)]
32    pub source: String,
33    /// The id of the resource the event is about.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub subject: Option<String>,
36    /// When the event was recorded (RFC 3339).
37    #[serde(default)]
38    pub time: String,
39    /// Always `1.0`.
40    #[serde(default)]
41    pub specversion: String,
42    /// The payload, typed by event type (`Unknown` for types this SDK version does not know).
43    #[serde(skip)]
44    pub data: WebhookEventData,
45    /// The payload as sent.
46    #[serde(rename = "data", default)]
47    pub raw_data: Value,
48    /// Ordering metadata.
49    #[serde(default)]
50    pub wellfriend: WebhookEventMeta,
51    /// Fields this SDK version does not model.
52    #[serde(flatten)]
53    pub extra: Object,
54}
55
56/// The `wellfriend` extension of every event.
57#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
58pub struct WebhookEventMeta {
59    /// When the change happened (the same instant as `time`).
60    #[serde(default)]
61    pub occurred_at: String,
62    /// The resource revision, when it has one.
63    #[serde(default)]
64    pub resource_revision: Option<i64>,
65    /// A decimal sequence for ordering events about one resource.
66    #[serde(default)]
67    pub sequence: Option<String>,
68    /// Fields this SDK version does not model.
69    #[serde(flatten)]
70    pub extra: Object,
71}
72
73impl WebhookEvent {
74    /// Parses an event body without verifying it. Use [`verify_webhook`] for deliveries.
75    pub fn parse(payload: &[u8]) -> Result<Self> {
76        let mut event: WebhookEvent = serde_json::from_slice(payload).map_err(|error| {
77            Error::WebhookVerification(format!("the body is not an event: {error}"))
78        })?;
79        event.data = WebhookEventData::parse(&event.event_type, event.raw_data.clone());
80        Ok(event)
81    }
82}
83
84/// Request headers, from any HTTP framework.
85pub trait WebhookHeaders {
86    /// The value of a header, by case-insensitive name.
87    fn header(&self, name: &str) -> Option<String>;
88}
89
90impl WebhookHeaders for HeaderMap {
91    fn header(&self, name: &str) -> Option<String> {
92        self.get(name)
93            .and_then(|value| value.to_str().ok())
94            .map(str::to_owned)
95    }
96}
97
98impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for HashMap<K, V> {
99    fn header(&self, name: &str) -> Option<String> {
100        self.iter()
101            .find(|(key, _)| key.as_ref().eq_ignore_ascii_case(name))
102            .map(|(_, value)| value.as_ref().to_owned())
103    }
104}
105
106impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for [(K, V)] {
107    fn header(&self, name: &str) -> Option<String> {
108        self.iter()
109            .find(|(key, _)| key.as_ref().eq_ignore_ascii_case(name))
110            .map(|(_, value)| value.as_ref().to_owned())
111    }
112}
113
114impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for Vec<(K, V)> {
115    fn header(&self, name: &str) -> Option<String> {
116        self.as_slice().header(name)
117    }
118}
119
120impl<T: WebhookHeaders + ?Sized> WebhookHeaders for &T {
121    fn header(&self, name: &str) -> Option<String> {
122        (**self).header(name)
123    }
124}
125
126/// Verifies a webhook delivery and returns the typed event.
127///
128/// `payload` must be the raw request body exactly as received. `secret` is the endpoint's signing
129/// secret (`whsec_...`). The signature (`webhook-signature`, `v1,<base64 HMAC-SHA256>` over
130/// `{webhook-id}.{webhook-timestamp}.{body}`) and a timestamp within 5 minutes are both required.
131/// For several secrets (during rotation) use [`WebhookVerifier`].
132///
133/// ```no_run
134/// # fn handle(body: &[u8], headers: &reqwest::header::HeaderMap) -> wellfriend::Result<()> {
135/// let event = wellfriend::verify_webhook(body, headers, "whsec_...")?;
136/// if let wellfriend::WebhookEventData::DocumentOperationCompletedV2(data) = &event.data {
137///     println!("operation {} finished", data.operation_id);
138/// }
139/// # Ok(())
140/// # }
141/// ```
142pub fn verify_webhook(
143    payload: &[u8],
144    headers: impl WebhookHeaders,
145    secret: &str,
146) -> Result<WebhookEvent> {
147    WebhookVerifier::new([secret]).verify(payload, headers)
148}
149
150/// A webhook verifier with one or more secrets and a configurable tolerance.
151#[derive(Clone)]
152pub struct WebhookVerifier {
153    secrets: Vec<String>,
154    public_keys: Vec<String>,
155    tolerance: Duration,
156    now: Option<SystemTime>,
157}
158
159impl std::fmt::Debug for WebhookVerifier {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        f.debug_struct("WebhookVerifier")
162            .field("secrets", &self.secrets.len())
163            .field("tolerance", &self.tolerance)
164            .finish()
165    }
166}
167
168impl WebhookVerifier {
169    /// A verifier accepting a signature made with any of `secrets`.
170    pub fn new<I, S>(secrets: I) -> Self
171    where
172        I: IntoIterator<Item = S>,
173        S: Into<String>,
174    {
175        WebhookVerifier {
176            secrets: secrets.into_iter().map(Into::into).collect(),
177            public_keys: Vec::new(),
178            tolerance: DEFAULT_TOLERANCE,
179            now: None,
180        }
181    }
182
183    /// A verifier for an endpoint created with the `ED25519` signature scheme: `public_keys` are
184    /// the endpoint's public keys (standard base64 of the raw 32-byte key). Signatures arrive as
185    /// `v1a,<base64 Ed25519 signature>` over the same signed content.
186    #[cfg(feature = "ed25519")]
187    #[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
188    pub fn ed25519<I, S>(public_keys: I) -> Self
189    where
190        I: IntoIterator<Item = S>,
191        S: Into<String>,
192    {
193        WebhookVerifier {
194            secrets: Vec::new(),
195            public_keys: public_keys.into_iter().map(Into::into).collect(),
196            tolerance: DEFAULT_TOLERANCE,
197            now: None,
198        }
199    }
200
201    /// How far the timestamp may be from now (default 5 minutes).
202    pub fn tolerance(mut self, tolerance: Duration) -> Self {
203        self.tolerance = tolerance;
204        self
205    }
206
207    /// Verifies as if the current time were `now` (for tests and replays).
208    pub fn at(mut self, now: SystemTime) -> Self {
209        self.now = Some(now);
210        self
211    }
212
213    /// Verifies a delivery and returns the typed event.
214    pub fn verify(&self, payload: &[u8], headers: impl WebhookHeaders) -> Result<WebhookEvent> {
215        let fail = |message: &str| Error::WebhookVerification(message.to_owned());
216        let id = headers
217            .header("webhook-id")
218            .filter(|id| !id.is_empty())
219            .ok_or_else(|| fail("the webhook-id header is missing"))?;
220        let timestamp = headers
221            .header("webhook-timestamp")
222            .ok_or_else(|| fail("the webhook-timestamp header is missing"))?;
223        let signatures = headers
224            .header("webhook-signature")
225            .ok_or_else(|| fail("the webhook-signature header is missing"))?;
226        let seconds: i64 = timestamp
227            .trim()
228            .parse()
229            .map_err(|_| fail("the webhook-timestamp header is not a Unix time"))?;
230        let now = self
231            .now
232            .unwrap_or_else(SystemTime::now)
233            .duration_since(UNIX_EPOCH)
234            .map(|d| d.as_secs() as i64)
235            .unwrap_or(0);
236        if (now - seconds).unsigned_abs() > self.tolerance.as_secs() {
237            return Err(fail("the timestamp is outside the allowed tolerance"));
238        }
239        let keys: Vec<Vec<u8>> = self
240            .secrets
241            .iter()
242            .filter_map(|secret| decode_secret(secret))
243            .collect();
244        if keys.is_empty() && self.public_keys.is_empty() {
245            return Err(fail(
246                "no valid signing secret was given (expected whsec_...)",
247            ));
248        }
249        let candidates: Vec<Vec<u8>> = signatures
250            .split_whitespace()
251            .filter_map(|entry| entry.split_once(','))
252            .filter(|(version, _)| *version == "v1")
253            .filter_map(|(_, encoded)| {
254                base64::engine::general_purpose::STANDARD
255                    .decode(encoded)
256                    .ok()
257            })
258            .collect();
259        let signed_prefix = format!("{id}.{seconds}.");
260        let matched = keys.iter().any(|key| {
261            let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(key) else {
262                return false;
263            };
264            mac.update(signed_prefix.as_bytes());
265            mac.update(payload);
266            let expected = mac.finalize().into_bytes();
267            candidates
268                .iter()
269                .any(|candidate| constant_time_eq(&expected, candidate))
270        });
271        if !matched && !self.ed25519_matches(&signatures, signed_prefix.as_bytes(), payload) {
272            return Err(fail("no signature matches"));
273        }
274        WebhookEvent::parse(payload)
275    }
276}
277
278impl WebhookVerifier {
279    #[cfg(feature = "ed25519")]
280    fn ed25519_matches(&self, signatures: &str, prefix: &[u8], payload: &[u8]) -> bool {
281        use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
282        let engine = base64::engine::general_purpose::STANDARD;
283        let keys: Vec<VerifyingKey> = self
284            .public_keys
285            .iter()
286            .filter_map(|key| engine.decode(key.trim()).ok())
287            .filter_map(|bytes| <[u8; 32]>::try_from(bytes.as_slice()).ok())
288            .filter_map(|bytes| VerifyingKey::from_bytes(&bytes).ok())
289            .collect();
290        let mut message = Vec::with_capacity(prefix.len() + payload.len());
291        message.extend_from_slice(prefix);
292        message.extend_from_slice(payload);
293        signatures
294            .split_whitespace()
295            .filter_map(|entry| entry.split_once(','))
296            .filter(|(version, _)| *version == "v1a")
297            .filter_map(|(_, encoded)| engine.decode(encoded).ok())
298            .filter_map(|bytes| Signature::from_slice(&bytes).ok())
299            .any(|signature| {
300                keys.iter()
301                    .any(|key| key.verify(&message, &signature).is_ok())
302            })
303    }
304
305    #[cfg(not(feature = "ed25519"))]
306    fn ed25519_matches(&self, _signatures: &str, _prefix: &[u8], _payload: &[u8]) -> bool {
307        let _ = &self.public_keys;
308        false
309    }
310}
311
312/// The HMAC key of a `whsec_` secret: standard base64, or the unpadded base64url of older
313/// endpoints (both decode to the same bytes).
314fn decode_secret(secret: &str) -> Option<Vec<u8>> {
315    let trimmed = secret.trim();
316    let encoded: String = trimmed
317        .strip_prefix("whsec_")
318        .unwrap_or(trimmed)
319        .trim_end_matches('=')
320        .replace('-', "+")
321        .replace('_', "/");
322    let key = base64::engine::general_purpose::STANDARD_NO_PAD
323        .decode(encoded.as_bytes())
324        .ok()?;
325    (key.len() >= 16).then_some(key)
326}
327
328fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
329    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
330}
331
332/// Webhook helpers on the client. Get it with [`Wellfriend::webhooks`].
333#[derive(Clone, Debug)]
334pub struct Webhooks {
335    pub(crate) client: Wellfriend,
336    pub(crate) options: RequestOptions,
337}
338
339impl Webhooks {
340    /// The same handle with these options for every call made through it.
341    pub fn with_options(mut self, options: RequestOptions) -> Self {
342        self.options = options;
343        self
344    }
345
346    /// Verifies a delivery locally; the same as [`verify_webhook`].
347    pub fn verify(
348        &self,
349        payload: &[u8],
350        headers: impl WebhookHeaders,
351        secret: &str,
352    ) -> Result<WebhookEvent> {
353        verify_webhook(payload, headers, secret)
354    }
355}
356
357impl Wellfriend {
358    /// Webhook endpoints, deliveries and local signature verification.
359    pub fn webhooks(&self) -> Webhooks {
360        Webhooks {
361            client: self.clone(),
362            options: RequestOptions::default(),
363        }
364    }
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
372    const BODY: &str = r#"{"test": 2432232314}"#;
373
374    fn headers(signature: &str) -> Vec<(&'static str, String)> {
375        vec![
376            ("webhook-id", "msg_p5jXN8AQM9LWM0D4loKWxJek".into()),
377            ("webhook-timestamp", "1614265330".into()),
378            ("webhook-signature", signature.into()),
379        ]
380    }
381
382    fn at() -> SystemTime {
383        UNIX_EPOCH + Duration::from_secs(1_614_265_330)
384    }
385
386    #[test]
387    fn checks_the_signature_and_the_secret_list() {
388        let good = headers("v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=");
389        // The body is not an event, so a correct signature reaches the parse step.
390        let error = WebhookVerifier::new([SECRET])
391            .at(at())
392            .verify(BODY.as_bytes(), &good)
393            .unwrap_err();
394        assert!(error.to_string().contains("not an event"), "{error}");
395        let wrong = WebhookVerifier::new(["whsec_AAAAAAAAAAAAAAAAAAAAAAAAAAAA"])
396            .at(at())
397            .verify(BODY.as_bytes(), &good)
398            .unwrap_err();
399        assert!(wrong.to_string().contains("no signature matches"));
400        let rotated = WebhookVerifier::new(["whsec_AAAAAAAAAAAAAAAAAAAAAAAAAAAA", SECRET])
401            .at(at())
402            .verify(BODY.as_bytes(), &good)
403            .unwrap_err();
404        assert!(rotated.to_string().contains("not an event"));
405    }
406
407    #[cfg(feature = "ed25519")]
408    #[test]
409    fn verifies_ed25519_signatures() {
410        use ed25519_dalek::{Signer, SigningKey};
411        let signing = SigningKey::from_bytes(&[9u8; 32]);
412        let public =
413            base64::engine::general_purpose::STANDARD.encode(signing.verifying_key().to_bytes());
414        let signature =
415            signing.sign(format!("msg_p5jXN8AQM9LWM0D4loKWxJek.1614265330.{BODY}").as_bytes());
416        let header = format!(
417            "v1a,{}",
418            base64::engine::general_purpose::STANDARD.encode(signature.to_bytes())
419        );
420        let error = WebhookVerifier::ed25519([public.clone()])
421            .at(at())
422            .verify(BODY.as_bytes(), headers(&header))
423            .unwrap_err();
424        assert!(error.to_string().contains("not an event"), "{error}");
425        let other = base64::engine::general_purpose::STANDARD.encode(
426            SigningKey::from_bytes(&[1u8; 32])
427                .verifying_key()
428                .to_bytes(),
429        );
430        let error = WebhookVerifier::ed25519([other])
431            .at(at())
432            .verify(BODY.as_bytes(), headers(&header))
433            .unwrap_err();
434        assert!(error.to_string().contains("no signature matches"));
435    }
436
437    #[test]
438    fn decodes_both_secret_alphabets() {
439        assert_eq!(
440            decode_secret("whsec_+//+fT4/AAECAwT7/wUGBwgJ+gsMDQ4P+//+EBESExQV"),
441            decode_secret("whsec_-__-fT4_AAECAwT7_wUGBwgJ-gsMDQ4P-__-EBESExQV")
442        );
443        assert!(decode_secret("whsec_short").is_none());
444    }
445}