ocre/webhooks.rs
1//! Webhooks: signatures for calls in both directions, and processing each
2//! event once.
3//!
4//! A payment provider, a GPU service or a mail service calls the app back
5//! with a signed POST. The handler checks the signature over the raw body,
6//! then runs the effect inside [`once`], which records the event in the
7//! `webhook_events` table (`ocre g webhook` creates it) and skips a
8//! delivery it has already processed: providers retry until they get a 2xx,
9//! so the same event often arrives twice.
10//!
11//! ```no_run
12//! use axum::{body::Bytes, extract::State, http::HeaderMap};
13//! use ocre::{Ctx, Result, webhooks};
14//!
15//! # #[allow(dead_code)]
16//!
17//! async fn receive(State(ctx): State<Ctx>, headers: HeaderMap, body: Bytes) -> Result<&'static str> {
18//! let secret = ctx.secret("PAYMENTS_WEBHOOK_SECRET").await?;
19//! let signature = headers.get("x-signature").and_then(|v| v.to_str().ok()).unwrap_or_default();
20//! webhooks::verify(secret.as_bytes(), &body, signature)?;
21//! let event: serde_json::Value =
22//! serde_json::from_slice(&body).map_err(|_| ocre::Error::bad_request("invalid JSON"))?;
23//! let id = event["id"].as_str().unwrap_or_default().to_owned();
24//! let db = ctx.db()?;
25//! webhooks::once(&db, "payments", &id, &body, || async {
26//! // ... mark the order paid: runs once per event id
27//! Ok(())
28//! })
29//! .await?;
30//! Ok("ok")
31//! }
32//! ```
33//!
34//! [`sign`] is the other direction: the app signs what it sends (a job
35//! submitted to an external service), and the service checks it the same way.
36//!
37//! # Sending webhooks to your users
38//!
39//! When users register their own endpoint URL (an API's "notify me" setting),
40//! [`deliver`] POSTs each event as a [Standard Webhooks](https://www.standardwebhooks.com)
41//! delivery: JSON body, `webhook-id`, `webhook-timestamp` and
42//! `webhook-signature` headers signed with the endpoint's secret
43//! ([`new_secret`] makes one), a 10-second timeout and no redirects. In
44//! release builds it first refuses URLs that are not `http(s)` or whose host
45//! is or resolves to a private, loopback or link-local address
46//! ([`check_public_url`], also for validating the URL when it is saved), so
47//! a user cannot make the app call its own network (SSRF). Retries belong
48//! to a job: run `deliver` from one and let the queue retry it.
49//!
50//! ```no_run
51//! use ocre::{Ctx, Error, Result, webhooks};
52//! use serde_json::json;
53//!
54//! // src/jobs/deliver_webhook.rs: the queue retries it on an error.
55//! async fn perform(ctx: &Ctx, endpoint_url: &str, secret: &str, event_id: &str) -> Result<()> {
56//! let event = json!({"type": "video.completed", "data": {"video_id": 7}});
57//! let response = webhooks::deliver(endpoint_url, secret, event_id, &event).await?;
58//! if !response.is_success() {
59//! return Err(Error::internal(format!("{endpoint_url} answered {}", response.status)));
60//! }
61//! Ok(())
62//! }
63//! ```
64
65use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
66
67use base64::Engine as _;
68use hmac::{Hmac, Mac};
69use sha2::Sha256;
70
71use crate::{Error, Result, http};
72
73pub use crate::runtime::webhooks::{Answer, Delivery, STALE_AFTER, check_public_url, deliver, once, post_signed};
74
75/// How long [`deliver`] waits for the endpoint's answer: 10 seconds.
76pub const DELIVERY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
77
78/// A new Standard Webhooks secret for an endpoint: `whsec_` and 32 random bytes in base64.
79///
80/// Show it to the user once, store it (encrypted, see
81/// [`encryption`](crate::encryption)), and pass it to [`deliver`].
82///
83/// # Examples
84///
85/// ```
86/// let secret = ocre::webhooks::new_secret();
87/// assert!(secret.starts_with("whsec_") && secret.len() == 6 + 44);
88/// assert!(ocre::webhooks::sign_standard(&secret, "msg_1", 0, b"{}").is_ok());
89/// ```
90pub fn new_secret() -> String {
91 format!("whsec_{}", base64::engine::general_purpose::STANDARD.encode(crate::token::random_bytes::<32>()))
92}
93
94/// Whether `ip` is an address a webhook must never reach: private, loopback, link-local, shared (CGNAT), unspecified, multicast, broadcast or reserved.
95///
96/// IPv4-mapped IPv6 addresses (`::ffff:10.0.0.1`) are checked as IPv4.
97///
98/// # Examples
99///
100/// ```
101/// use ocre::webhooks::private_ip;
102///
103/// assert!(private_ip("169.254.169.254".parse().unwrap()), "cloud metadata");
104/// assert!(private_ip("::ffff:127.0.0.1".parse().unwrap()));
105/// assert!(private_ip("fd00::1".parse().unwrap()));
106/// assert!(!private_ip("93.184.216.34".parse().unwrap()));
107/// assert!(!private_ip("2606:4700::1111".parse().unwrap()));
108/// ```
109pub fn private_ip(ip: IpAddr) -> bool {
110 match ip {
111 IpAddr::V4(ip) => private_ipv4(ip),
112 IpAddr::V6(ip) => match ip.to_ipv4_mapped() {
113 Some(ip) => private_ipv4(ip),
114 None => private_ipv6(ip),
115 },
116 }
117}
118
119fn private_ipv4(ip: Ipv4Addr) -> bool {
120 let [a, b, _, _] = ip.octets();
121 ip.is_private()
122 || ip.is_loopback()
123 || ip.is_link_local()
124 || ip.is_unspecified()
125 || ip.is_broadcast()
126 || ip.is_multicast()
127 || ip.is_documentation()
128 || a == 0
129 || a >= 240
130 || (a == 100 && (64..=127).contains(&b))
131 || (a == 198 && (18..=19).contains(&b))
132 || (a == 192 && b == 0 && ip.octets()[2] == 0)
133}
134
135fn private_ipv6(ip: Ipv6Addr) -> bool {
136 let first = ip.segments()[0];
137 ip.is_loopback()
138 || ip.is_unspecified()
139 || ip.is_multicast()
140 || (first & 0xfe00) == 0xfc00 // unique local fc00::/7
141 || (first & 0xffc0) == 0xfe80 // link-local fe80::/10
142 || (first == 0x2001 && ip.segments()[1] == 0x0db8) // documentation
143 || (first == 0x0064 && ip.segments()[1] == 0xff9b) // NAT64 to IPv4
144}
145
146/// The host of a webhook URL: an IP address to check as is, or a name to resolve.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub(crate) enum UrlHost {
149 Ip(IpAddr),
150 Name(String),
151}
152
153/// The host of `url`, or a 400 naming the problem: not `http(s)`, credentials in the URL.
154pub(crate) fn url_host(url: &str) -> Result<UrlHost> {
155 let refuse = |reason: &str| Error::bad_request(format!("The webhook URL {reason}"));
156 let parsed = worker::Url::parse(url.trim()).map_err(|_| refuse("is not a valid URL"))?;
157 if !matches!(parsed.scheme(), "http" | "https") {
158 return Err(refuse("must start with https:// or http://"));
159 }
160 if !parsed.username().is_empty() || parsed.password().is_some() {
161 return Err(refuse("must not contain a user name or password"));
162 }
163 match parsed.host().expect("the URL parser refuses http(s) URLs without a host") {
164 worker::url::Host::Ipv4(ip) => Ok(UrlHost::Ip(IpAddr::V4(ip))),
165 worker::url::Host::Ipv6(ip) => Ok(UrlHost::Ip(IpAddr::V6(ip))),
166 worker::url::Host::Domain(name) if name.eq_ignore_ascii_case("localhost") || name.ends_with(".localhost") => {
167 Ok(UrlHost::Ip(IpAddr::V4(Ipv4Addr::LOCALHOST)))
168 }
169 worker::url::Host::Domain(name) => Ok(UrlHost::Name(name.trim_end_matches('.').to_ascii_lowercase())),
170 }
171}
172
173/// The `A` (type 1) and `AAAA` (type 28) addresses of a DNS-over-HTTPS JSON answer (RFC 8484's JSON form, as Cloudflare's resolver answers).
174pub(crate) fn dns_addresses(answer: &serde_json::Value) -> Vec<IpAddr> {
175 answer["Answer"]
176 .as_array()
177 .into_iter()
178 .flatten()
179 .filter(|record| matches!(record["type"].as_i64(), Some(1 | 28)))
180 .filter_map(|record| record["data"].as_str()?.parse().ok())
181 .collect()
182}
183
184/// Why the resolved `addresses` of `host` make it unfit for a webhook, if they do.
185pub(crate) fn refused_addresses(host: &str, addresses: &[IpAddr]) -> Option<Error> {
186 if addresses.is_empty() {
187 return Some(Error::bad_request(format!("The webhook URL's host {host} was not found")));
188 }
189 addresses
190 .iter()
191 .any(|ip| private_ip(*ip))
192 .then(|| Error::bad_request(format!("The webhook URL's host {host} is a private address")))
193}
194
195/// The signed POST of a Standard Webhooks delivery of `body` to `url`.
196pub(crate) fn delivery_request(url: &str, secret: &str, id: &str, body: Vec<u8>, now: i64) -> Result<http::Request> {
197 let signature = sign_standard(secret, id, now, &body)?;
198 Ok(http::Request::post(url.trim())
199 .header("user-agent", "Ocre-Webhooks/1")
200 .header("webhook-id", id)
201 .header("webhook-timestamp", &now.to_string())
202 .header("webhook-signature", &signature)
203 .body(body, "application/json")
204 .timeout(DELIVERY_TIMEOUT)
205 .follow_redirects(false))
206}
207
208/// The `webhook_events` table [`once`] records deliveries in, created by
209/// the migration of `ocre g webhook`.
210pub const TABLE_SQL: &str = "CREATE TABLE webhook_events (
211 id INTEGER PRIMARY KEY,
212 source TEXT NOT NULL,
213 event_id TEXT NOT NULL,
214 payload TEXT NOT NULL,
215 status TEXT NOT NULL,
216 attempts INTEGER NOT NULL DEFAULT 1,
217 error TEXT,
218 received_at INTEGER NOT NULL,
219 processed_at INTEGER,
220 UNIQUE (source, event_id)
221);
222";
223
224/// HMAC-SHA256 of `message` with `secret`, as lowercase hex: the signature
225/// to send in a header (`X-Signature`) of an outgoing call.
226///
227/// # Examples
228///
229/// ```
230/// let signature = ocre::webhooks::sign(b"secret", b"{\"id\":1}");
231/// assert_eq!(signature.len(), 64);
232/// assert!(ocre::webhooks::verify(b"secret", b"{\"id\":1}", &signature).is_ok());
233/// ```
234pub fn sign(secret: &[u8], message: &[u8]) -> String {
235 let mut mac = mac(secret);
236 mac.update(message);
237 let bytes = mac.finalize().into_bytes();
238 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
239}
240
241/// Checks that `signature` is the HMAC-SHA256 of `message` with `secret`,
242/// in constant time. The signature may be hex (any case, optionally
243/// prefixed `sha256=` as GitHub sends it) or base64 (standard or URL-safe,
244/// padded or not), the common encodings of webhook providers. Sign the raw
245/// request body: parsed and re-serialized JSON may differ by a space.
246///
247/// # Errors
248///
249/// [`Error::Unauthorized`] when the signature is missing, malformed or
250/// does not match.
251///
252/// # Examples
253///
254/// ```
255/// use base64::Engine as _;
256/// use ocre::webhooks::{sign, verify};
257///
258/// let hex = sign(b"secret", b"body");
259/// assert!(verify(b"secret", b"body", &format!("sha256={hex}")).is_ok());
260/// assert!(verify(b"other", b"body", &hex).is_err());
261/// ```
262pub fn verify(secret: &[u8], message: &[u8], signature: &str) -> Result<()> {
263 let signature = signature.trim();
264 let signature = signature.strip_prefix("sha256=").unwrap_or(signature);
265 let expected = decode_hex(signature).or_else(|| decode_base64(signature)).ok_or(Error::Unauthorized)?;
266 let mut mac = mac(secret);
267 mac.update(message);
268 mac.verify_slice(&expected).map_err(|_| Error::Unauthorized)
269}
270
271/// Checks a [Standard Webhooks](https://www.standardwebhooks.com) delivery
272/// (Svix, Resend, and other providers): `webhook-signature` holds one or
273/// more space-separated `v1,<base64>` signatures of `{id}.{timestamp}.{body}`
274/// keyed with the base64 part of the `whsec_...` secret, and the
275/// `webhook-timestamp` must be within `tolerance` seconds of `now` (replays
276/// of an old delivery are refused). Returns the `webhook-id`, the event id
277/// to give [`once`].
278///
279/// # Errors
280///
281/// [`Error::Unauthorized`] when a header is missing, the timestamp is out
282/// of tolerance, or no signature matches; [`Error::Internal`] when the
283/// secret is not `whsec_` followed by base64.
284///
285/// # Examples
286///
287/// ```
288/// use axum::http::HeaderMap;
289/// use base64::Engine as _;
290/// use ocre::webhooks::{sign, verify_standard};
291///
292/// let key = b"0123456789abcdef";
293/// let secret = format!("whsec_{}", base64::engine::general_purpose::STANDARD.encode(key));
294/// let signature = sign(key, b"msg_1.1700000000.{}");
295/// let bytes: Vec<u8> = (0..32).map(|i| u8::from_str_radix(&signature[i * 2..i * 2 + 2], 16).unwrap()).collect();
296/// let mut headers = HeaderMap::new();
297/// headers.insert("webhook-id", "msg_1".parse().unwrap());
298/// headers.insert("webhook-timestamp", "1700000000".parse().unwrap());
299/// let value = format!("v1,{}", base64::engine::general_purpose::STANDARD.encode(bytes));
300/// headers.insert("webhook-signature", value.parse().unwrap());
301/// assert_eq!(verify_standard(&secret, &headers, b"{}", 300, 1_700_000_100).unwrap(), "msg_1");
302/// assert!(verify_standard(&secret, &headers, b"{}", 300, 1_700_001_000).is_err(), "too old");
303/// ```
304pub fn verify_standard(
305 secret: &str,
306 headers: &axum::http::HeaderMap,
307 body: &[u8],
308 tolerance: i64,
309 now: i64,
310) -> Result<String> {
311 let key = standard_key(secret)?;
312 let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok()).ok_or(Error::Unauthorized);
313 let id = header("webhook-id")?;
314 let timestamp = header("webhook-timestamp")?;
315 let sent_at: i64 = timestamp.parse().map_err(|_| Error::Unauthorized)?;
316 if (now - sent_at).abs() > tolerance {
317 return Err(Error::Unauthorized);
318 }
319 let message = [id.as_bytes(), b".", timestamp.as_bytes(), b".", body].concat();
320 let signed = header("webhook-signature")?
321 .split_whitespace()
322 .filter_map(|entry| entry.strip_prefix("v1,"))
323 .any(|signature| verify(&key, &message, signature).is_ok());
324 if signed { Ok(id.to_owned()) } else { Err(Error::Unauthorized) }
325}
326
327fn mac(secret: &[u8]) -> Hmac<Sha256> {
328 Hmac::<Sha256>::new_from_slice(secret).expect("HMAC takes keys of any length")
329}
330
331fn decode_hex(text: &str) -> Option<Vec<u8>> {
332 if !text.len().is_multiple_of(2) || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
333 return None;
334 }
335 (0..text.len()).step_by(2).map(|i| u8::from_str_radix(&text[i..i + 2], 16).ok()).collect()
336}
337
338/// The `webhook-signature` header value (`v1,<base64>`) of a [Standard
339/// Webhooks](https://www.standardwebhooks.com) delivery of `body` with this
340/// `id` and `timestamp` (Unix seconds): what [`verify_standard`] checks.
341/// For an app that sends Standard Webhooks, and for tests of one that
342/// receives them.
343///
344/// # Errors
345///
346/// [`Error::Internal`] when the secret is not `whsec_` followed by base64.
347///
348/// # Examples
349///
350/// ```
351/// use axum::http::HeaderMap;
352/// use ocre::webhooks::{sign_standard, verify_standard};
353///
354/// let secret = "whsec_c2VjcmV0";
355/// let mut headers = HeaderMap::new();
356/// headers.insert("webhook-id", "msg_1".parse().unwrap());
357/// headers.insert("webhook-timestamp", "1700000000".parse().unwrap());
358/// let signature = sign_standard(secret, "msg_1", 1_700_000_000, b"{}").unwrap();
359/// headers.insert("webhook-signature", signature.parse().unwrap());
360/// assert!(verify_standard(secret, &headers, b"{}", 300, 1_700_000_000).is_ok());
361/// ```
362pub fn sign_standard(secret: &str, id: &str, timestamp: i64, body: &[u8]) -> Result<String> {
363 let key = standard_key(secret)?;
364 let mut mac = mac(&key);
365 mac.update(&[id.as_bytes(), b".", timestamp.to_string().as_bytes(), b".", body].concat());
366 Ok(format!("v1,{}", base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes())))
367}
368
369/// The HMAC key of a `whsec_<base64>` secret.
370fn standard_key(secret: &str) -> Result<Vec<u8>> {
371 secret
372 .strip_prefix("whsec_")
373 .and_then(decode_base64)
374 .ok_or_else(|| Error::internal("webhooks: a Standard Webhooks secret is `whsec_` followed by base64"))
375}
376
377fn decode_base64(text: &str) -> Option<Vec<u8>> {
378 use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
379 [STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD].iter().find_map(|engine| engine.decode(text).ok())
380}
381
382#[cfg(test)]
383#[path = "../tests/webhooks.rs"]
384mod tests;