1use std::collections::{BTreeMap, HashMap};
8use std::hash::BuildHasher;
9use std::sync::Arc;
10use std::time::{Duration, SystemTime, UNIX_EPOCH};
11
12use hmac::{Hmac, KeyInit, Mac};
13use serde::Deserialize;
14use serde_json::Value;
15use serde_json::value::RawValue;
16use sha2::Sha256;
17
18use crate::error::{Error, Result, WebhookVerificationReason as Reason};
19use crate::models::{Article, decode_article, decode_value};
20use crate::time::{parse_opt, parse_rfc3339_nanos};
21use crate::vocab::WebhookEventName;
22
23pub const DEFAULT_TOLERANCE: Duration = Duration::from_secs(300);
25
26const SIGNATURE_HEADER: &str = "x-webhook-signature";
27const TIMESTAMP_HEADER: &str = "x-webhook-timestamp";
28const SIGNATURE_PREFIX: &str = "sha256=";
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32#[non_exhaustive]
33pub struct WebhookVerifyOptions {
34 pub tolerance: Duration,
36 pub now: Option<SystemTime>,
38}
39
40impl Default for WebhookVerifyOptions {
41 fn default() -> Self {
42 WebhookVerifyOptions {
43 tolerance: DEFAULT_TOLERANCE,
44 now: None,
45 }
46 }
47}
48
49impl WebhookVerifyOptions {
50 pub fn new() -> Self {
52 Self::default()
53 }
54
55 pub fn tolerance(mut self, value: Duration) -> Self {
57 self.tolerance = value;
58 self
59 }
60
61 pub fn now(mut self, value: SystemTime) -> Self {
63 self.now = Some(value);
64 self
65 }
66}
67
68pub trait WebhookHeaders {
74 fn header_values(&self, name: &str) -> Vec<Option<String>>;
77}
78
79fn name_matches(key: &str, name: &str) -> bool {
80 if key.eq_ignore_ascii_case(name) {
81 return true;
82 }
83 let Some(rest) = key
84 .get(..5)
85 .filter(|p| p.eq_ignore_ascii_case("http_"))
86 .map(|_| &key[5..])
87 else {
88 return false;
89 };
90 rest.len() == name.len()
91 && rest
92 .bytes()
93 .zip(name.bytes())
94 .all(|(a, b)| a.to_ascii_lowercase() == if b == b'-' { b'_' } else { b })
95}
96
97fn pairs_values<'a, K, V>(
98 pairs: impl Iterator<Item = (&'a K, &'a V)>,
99 name: &str,
100) -> Vec<Option<String>>
101where
102 K: AsRef<str> + 'a + ?Sized,
103 V: AsRef<str> + 'a + ?Sized,
104{
105 pairs
106 .filter(|(k, _)| name_matches(k.as_ref(), name))
107 .map(|(_, v)| Some(v.as_ref().to_owned()))
108 .collect()
109}
110
111impl WebhookHeaders for http::HeaderMap {
112 fn header_values(&self, name: &str) -> Vec<Option<String>> {
113 self.iter()
114 .filter(|(k, _)| name_matches(k.as_str(), name))
115 .map(|(_, v)| v.to_str().ok().map(str::to_owned))
116 .collect()
117 }
118}
119
120impl<K: AsRef<str>, V: AsRef<str>, S: BuildHasher> WebhookHeaders for HashMap<K, V, S> {
121 fn header_values(&self, name: &str) -> Vec<Option<String>> {
122 pairs_values(self.iter(), name)
123 }
124}
125
126impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for BTreeMap<K, V> {
127 fn header_values(&self, name: &str) -> Vec<Option<String>> {
128 pairs_values(self.iter(), name)
129 }
130}
131
132impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for [(K, V)] {
133 fn header_values(&self, name: &str) -> Vec<Option<String>> {
134 pairs_values(self.iter().map(|(k, v)| (k, v)), name)
135 }
136}
137
138impl<K: AsRef<str>, V: AsRef<str>, const N: usize> WebhookHeaders for [(K, V); N] {
139 fn header_values(&self, name: &str) -> Vec<Option<String>> {
140 self.as_slice().header_values(name)
141 }
142}
143
144impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for Vec<(K, V)> {
145 fn header_values(&self, name: &str) -> Vec<Option<String>> {
146 self.as_slice().header_values(name)
147 }
148}
149
150impl<T: WebhookHeaders + ?Sized> WebhookHeaders for &T {
151 fn header_values(&self, name: &str) -> Vec<Option<String>> {
152 (**self).header_values(name)
153 }
154}
155
156#[derive(Debug, Clone, PartialEq)]
158#[non_exhaustive]
159pub struct WebhookEvent {
160 pub event_id: String,
162 pub event: WebhookEventName,
164 pub occurred_at: String,
166 pub payload_version: u32,
168 pub subscription_id: String,
170 pub changed_fields: Option<Vec<String>>,
172 pub data: Article,
174 raw: Arc<str>,
175}
176
177impl WebhookEvent {
178 pub fn is_test(&self) -> bool {
180 self.event_id.starts_with("evt_test")
181 }
182
183 pub fn occurred_at_time(&self) -> Option<SystemTime> {
185 parse_opt(Some(&self.occurred_at))
186 }
187
188 pub fn raw_json(&self) -> &str {
190 &self.raw
191 }
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
198#[non_exhaustive]
199pub struct WrongPayloadVersion {
200 pub detected_version: u32,
202 pub payload_version: Option<String>,
204 pub payload_version_present: bool,
206 pub raw: String,
208 pub link: Option<String>,
210}
211
212impl WrongPayloadVersion {
213 pub fn raw_json(&self) -> &str {
215 &self.raw
216 }
217}
218
219#[derive(Debug, Clone, PartialEq)]
221#[non_exhaustive]
222#[allow(clippy::large_enum_variant)]
223pub enum WebhookPayload {
224 Event(WebhookEvent),
226 WrongPayloadVersion(WrongPayloadVersion),
228}
229
230fn single_header(
231 headers: &(impl WebhookHeaders + ?Sized),
232 name: &str,
233 label: &str,
234) -> Result<Option<String>> {
235 let values = headers.header_values(name);
236 match values.as_slice() {
237 [] => Ok(None),
238 [None] => Err(Error::webhook(
239 Reason::NonAsciiHeader,
240 format!("the {label} header contains characters outside printable ASCII"),
241 )),
242 [Some(v)] if v.contains(',') => Err(Error::webhook(
243 Reason::DuplicateHeader,
244 format!("the {label} header appears more than once"),
245 )),
246 [Some(v)] => Ok(Some(v.clone())),
247 _ => Err(Error::webhook(
248 Reason::DuplicateHeader,
249 format!("the {label} header appears more than once"),
250 )),
251 }
252}
253
254fn printable_ascii(value: &str) -> bool {
255 value.bytes().all(|b| (0x20..=0x7e).contains(&b))
256}
257
258pub fn verify_signature(
263 raw_body: impl AsRef<[u8]>,
264 signature: &str,
265 timestamp: &str,
266 secret: &str,
267 options: &WebhookVerifyOptions,
268) -> Result<()> {
269 verify(
270 raw_body.as_ref(),
271 Some(signature),
272 Some(timestamp),
273 secret,
274 options,
275 )
276}
277
278fn verify(
279 body: &[u8],
280 signature: Option<&str>,
281 timestamp: Option<&str>,
282 secret: &str,
283 options: &WebhookVerifyOptions,
284) -> Result<()> {
285 if secret.is_empty() {
286 return Err(Error::webhook(
287 Reason::InvalidSecret,
288 "the webhook secret must not be empty",
289 ));
290 }
291 let signature = match signature {
292 Some(s) if !s.is_empty() => s,
293 _ => {
294 return Err(Error::webhook(
295 Reason::MissingSignature,
296 "the X-Webhook-Signature header is missing",
297 ));
298 }
299 };
300 let timestamp = match timestamp {
301 Some(t) if !t.is_empty() => t,
302 _ => {
303 return Err(Error::webhook(
304 Reason::MissingTimestamp,
305 "the X-Webhook-Timestamp header is missing",
306 ));
307 }
308 };
309 if !printable_ascii(signature) || !printable_ascii(timestamp) {
310 return Err(Error::webhook(
311 Reason::NonAsciiHeader,
312 "a webhook header contains characters outside printable ASCII",
313 ));
314 }
315 let Some(given) = signature.strip_prefix(SIGNATURE_PREFIX) else {
316 return Err(Error::webhook(
317 Reason::UnsupportedSignatureScheme,
318 "the X-Webhook-Signature header must start with \"sha256=\"",
319 ));
320 };
321 let Some(signed_at) = parse_rfc3339_nanos(timestamp) else {
322 return Err(Error::webhook(
323 Reason::UnparseableTimestamp,
324 "the X-Webhook-Timestamp header is not an RFC 3339 timestamp",
325 ));
326 };
327 let mismatch = || {
328 Error::webhook(
329 Reason::SignatureMismatch,
330 "the webhook signature does not match",
331 )
332 };
333 let given = hex::decode(given).map_err(|_| mismatch())?;
334 let mut mac =
335 <Hmac<Sha256> as KeyInit>::new_from_slice(secret.as_bytes()).map_err(|_| mismatch())?;
336 mac.update(timestamp.as_bytes());
337 mac.update(b".");
338 mac.update(body);
339 mac.verify_slice(&given).map_err(|_| mismatch())?;
341
342 let now = options.now.unwrap_or_else(SystemTime::now);
343 let now_nanos: i128 = match now.duration_since(UNIX_EPOCH) {
344 Ok(d) => i128::try_from(d.as_nanos()).unwrap_or(i128::MAX),
345 Err(e) => -i128::try_from(e.duration().as_nanos()).unwrap_or(i128::MAX),
346 };
347 let tolerance = i128::try_from(options.tolerance.as_nanos()).unwrap_or(i128::MAX);
348 if (now_nanos - signed_at).abs() > tolerance {
349 return Err(Error::webhook(
350 Reason::TimestampOutsideTolerance,
351 "the webhook timestamp is outside the allowed tolerance",
352 ));
353 }
354 Ok(())
355}
356
357#[derive(Deserialize)]
358#[serde(rename_all = "camelCase")]
359struct Envelope {
360 event_id: String,
361 event: WebhookEventName,
362 occurred_at: String,
363 subscription_id: String,
364 #[serde(default)]
365 changed_fields: Option<Vec<String>>,
366 data: Box<RawValue>,
367}
368
369fn read_event(body: &[u8]) -> Result<WebhookPayload> {
370 let text = std::str::from_utf8(body).map_err(|e| {
371 Error::decode(
372 "the verified webhook body is not UTF-8",
373 None,
374 None,
375 Some(Box::new(e)),
376 )
377 })?;
378 let json: Value = serde_json::from_str(text).map_err(|e| {
379 Error::decode(
380 "the verified webhook body is not JSON",
381 None,
382 None,
383 Some(Box::new(e)),
384 )
385 })?;
386 let Value::Object(obj) = &json else {
387 return Err(Error::decode(
388 "the verified webhook body is not a JSON object",
389 None,
390 Some(text.to_owned()),
391 None,
392 ));
393 };
394 let version = obj.get("payloadVersion");
395 let is_v3 = matches!(version, Some(Value::Number(n)) if n.as_f64() == Some(3.0));
396 if !is_v3 {
397 let link = obj
398 .get("link")
399 .and_then(Value::as_str)
400 .or_else(|| {
401 obj.get("data")
402 .and_then(|d| d.get("link"))
403 .and_then(Value::as_str)
404 })
405 .map(str::to_owned);
406 return Ok(WebhookPayload::WrongPayloadVersion(WrongPayloadVersion {
407 detected_version: 2,
408 payload_version: version.map(Value::to_string),
409 payload_version_present: version.is_some(),
410 raw: text.to_owned(),
411 link,
412 }));
413 }
414 let env: Envelope = decode_value(text, "")?;
415 let data = decode_article(&env.data, "data")?;
416 Ok(WebhookPayload::Event(WebhookEvent {
417 event_id: env.event_id,
418 event: env.event,
419 occurred_at: env.occurred_at,
420 payload_version: 3,
421 subscription_id: env.subscription_id,
422 changed_fields: env.changed_fields,
423 data,
424 raw: Arc::from(text),
425 }))
426}
427
428pub fn construct_event<H: WebhookHeaders + ?Sized>(
450 raw_body: impl AsRef<[u8]>,
451 headers: &H,
452 secret: &str,
453 options: &WebhookVerifyOptions,
454) -> Result<WebhookPayload> {
455 let signature = single_header(headers, SIGNATURE_HEADER, "X-Webhook-Signature")?;
456 let timestamp = single_header(headers, TIMESTAMP_HEADER, "X-Webhook-Timestamp")?;
457 construct_event_from_values(
458 raw_body,
459 signature.as_deref(),
460 timestamp.as_deref(),
461 secret,
462 options,
463 )
464}
465
466pub fn construct_event_from_values(
469 raw_body: impl AsRef<[u8]>,
470 signature: Option<&str>,
471 timestamp: Option<&str>,
472 secret: &str,
473 options: &WebhookVerifyOptions,
474) -> Result<WebhookPayload> {
475 let body = raw_body.as_ref();
476 verify(body, signature, timestamp, secret, options)?;
477 read_event(body)
478}