Skip to main content

renox_core/webhook/
signing.rs

1//! Signing and verifying webhook requests in the
2//! [Standard Webhooks](https://www.standardwebhooks.com) format, so receivers
3//! can use any of the existing libraries for it.
4//!
5//! A request carries three headers: `webhook-id` (unique per message, the
6//! same on every retry), `webhook-timestamp` (Unix seconds) and
7//! `webhook-signature`, a space-separated list of `v1,<base64>` values where
8//! each is `HMAC-SHA256(key, "{id}.{timestamp}.{body}")`. The secret is
9//! written `whsec_<base64>`; the HMAC key is the decoded part.
10//!
11//! ```
12//! use std::time::Duration;
13//! use renox::webhook::signing;
14//!
15//! // The test vector from the Standard Webhooks specification.
16//! let secret = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
17//! let id = "msg_p5jXN8AQM9LWM0D4loKWxJek";
18//! let body = br#"{"test": 2432232314}"#;
19//!
20//! let signature = signing::sign(secret, id, 1614265330, body)?;
21//! assert_eq!(signature, "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=");
22//!
23//! // Long after the timestamp: refused by the tolerance window.
24//! assert!(!signing::verify(secret, id, "1614265330", &signature, body, Duration::from_secs(300)));
25//! # Ok::<(), renox::Error>(())
26//! ```
27
28use std::time::Duration;
29
30use base64::Engine;
31use base64::engine::general_purpose::STANDARD;
32use hmac::{Hmac, KeyInit, Mac};
33use sha2::Sha256;
34
35use crate::{Error, Result};
36
37/// The prefix of a signing secret.
38pub const SECRET_PREFIX: &str = "whsec_";
39
40/// Generates a new secret, `whsec_` followed by 24 random bytes in base64
41/// (the spec allows 24 to 64 bytes).
42pub fn generate_secret() -> String {
43    let mut bytes = [0u8; 24];
44    rand::fill(&mut bytes);
45    format!("{SECRET_PREFIX}{}", STANDARD.encode(bytes))
46}
47
48/// Decodes a `whsec_<base64>` secret (the prefix is optional) into the HMAC
49/// key.
50///
51/// # Errors
52/// When the rest isn't valid base64.
53pub fn decode_secret(secret: &str) -> Result<Vec<u8>> {
54    let encoded = secret.strip_prefix(SECRET_PREFIX).unwrap_or(secret);
55    STANDARD.decode(encoded.trim()).map_err(|_| {
56        Error::from(anyhow::anyhow!(
57            "the webhook secret is not valid base64 (expected `whsec_<base64>`)"
58        ))
59    })
60}
61
62fn mac(key: &[u8], id: &str, timestamp: &str, body: &[u8]) -> Hmac<Sha256> {
63    let mut mac =
64        <Hmac<Sha256> as KeyInit>::new_from_slice(key).expect("HMAC accepts keys of any length");
65    mac.update(id.as_bytes());
66    mac.update(b".");
67    mac.update(timestamp.as_bytes());
68    mac.update(b".");
69    mac.update(body);
70    mac
71}
72
73/// The `webhook-signature` value (`v1,<base64>`) for a message.
74///
75/// # Errors
76/// When `secret` isn't valid base64.
77pub fn sign(secret: &str, id: &str, timestamp: i64, body: &[u8]) -> Result<String> {
78    let key = decode_secret(secret)?;
79    let digest = mac(&key, id, &timestamp.to_string(), body)
80        .finalize()
81        .into_bytes();
82    Ok(format!("v1,{}", STANDARD.encode(digest)))
83}
84
85/// Checks a request's headers against `secret`: the timestamp must be within
86/// `tolerance` of now (so a captured request can't be replayed later), and
87/// one of the `v1` signatures in `signature_header` must match. Comparison
88/// takes the same time wherever it differs. Signatures of other versions are
89/// ignored; an invalid secret or header gives `false`.
90pub fn verify(
91    secret: &str,
92    id: &str,
93    timestamp_header: &str,
94    signature_header: &str,
95    body: &[u8],
96    tolerance: Duration,
97) -> bool {
98    let timestamp_header = timestamp_header.trim();
99    let Ok(timestamp) = timestamp_header.parse::<i64>() else {
100        return false;
101    };
102    if (crate::clock::unix_secs() - timestamp).unsigned_abs() > tolerance.as_secs() {
103        return false;
104    }
105    let Ok(key) = decode_secret(secret) else {
106        return false;
107    };
108    let expected = mac(&key, id, timestamp_header, body)
109        .finalize()
110        .into_bytes();
111    signature_header
112        .split(' ')
113        .filter_map(|part| part.strip_prefix("v1,"))
114        .filter_map(|b64| STANDARD.decode(b64).ok())
115        .fold(false, |ok, sig| {
116            let equal = sig.len() == expected.len()
117                && sig
118                    .iter()
119                    .zip(expected.iter())
120                    .fold(0u8, |acc, (x, y)| acc | (x ^ y))
121                    == 0;
122            ok | equal
123        })
124}
125
126/// A request signed by a known sender (`Request::sign` on their side,
127/// `App::signing_key` on yours), with its JSON body as `T`.
128///
129/// The extractor looks the `webhook-key-id` up among the registered keys,
130/// checks the signature over the raw body, refuses a timestamp more than
131/// `WEBHOOK_TOLERANCE_SECS` (300) away from now, and refuses a `webhook-id`
132/// it has seen already (kept in the cache for the window). Every failure is a
133/// `401` with the same generic message.
134///
135/// ```no_run
136/// use renox::prelude::*;
137///
138/// #[derive(serde::Deserialize)]
139/// struct Ping {
140///     note: String,
141/// }
142///
143/// async fn receive(SignedRequest(ping): SignedRequest<Ping>) -> String {
144///     ping.note
145/// }
146/// ```
147pub struct SignedRequest<T>(pub T);
148
149/// The same answer for every failure, so a sender learns nothing about why.
150fn unauthorized() -> axum::response::Response {
151    use axum::response::IntoResponse;
152    (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized").into_response()
153}
154
155impl<T> axum::extract::FromRequest<crate::AppState> for SignedRequest<T>
156where
157    T: serde::de::DeserializeOwned + Send,
158{
159    type Rejection = axum::response::Response;
160
161    async fn from_request(
162        req: axum::extract::Request,
163        state: &crate::AppState,
164    ) -> std::result::Result<Self, Self::Rejection> {
165        let headers = {
166            let header = |name: &str| {
167                req.headers()
168                    .get(name)
169                    .and_then(|v| v.to_str().ok())
170                    .map(str::to_owned)
171            };
172            (
173                header("webhook-key-id"),
174                header("webhook-id"),
175                header("webhook-timestamp"),
176                header("webhook-signature"),
177            )
178        };
179        let (Some(key_id), Some(id), Some(timestamp), Some(signature)) = headers else {
180            return Err(unauthorized());
181        };
182        let Some(secret) = state.signing_keys.get(&key_id) else {
183            return Err(unauthorized());
184        };
185        // Buffered under the app's body limit, which a too-large body trips.
186        let body = axum::body::Bytes::from_request(req, state)
187            .await
188            .map_err(|_| unauthorized())?;
189        let tolerance = Duration::from_secs(state.config.webhook_tolerance_secs);
190        if !verify(secret, &id, &timestamp, &signature, &body, tolerance) {
191            return Err(unauthorized());
192        }
193        // Only a correctly signed id is remembered, so a stranger can't use
194        // up ids. A timestamp may be `tolerance` ahead or behind: keep twice.
195        let fresh = state
196            .cache
197            .add(
198                &format!("webhook-replay:{key_id}:{id}"),
199                &true,
200                Some(tolerance * 2),
201            )
202            .await
203            .map_err(|_| unauthorized())?;
204        if !fresh {
205            return Err(unauthorized());
206        }
207        let value = serde_json::from_slice(&body).map_err(|_| unauthorized())?;
208        Ok(Self(value))
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
217    const ID: &str = "msg_p5jXN8AQM9LWM0D4loKWxJek";
218    const BODY: &[u8] = br#"{"test": 2432232314}"#;
219    const VECTOR: &str = "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=";
220    const WINDOW: Duration = Duration::from_secs(300);
221
222    #[test]
223    fn matches_the_specification_test_vector() {
224        assert_eq!(sign(SECRET, ID, 1614265330, BODY).unwrap(), VECTOR);
225    }
226
227    #[test]
228    fn verifies_within_the_window_and_rejects_tampering() {
229        let now = crate::clock::unix_secs();
230        let signature = sign(SECRET, ID, now, BODY).unwrap();
231        let ts = now.to_string();
232        assert!(verify(SECRET, ID, &ts, &signature, BODY, WINDOW));
233        assert!(!verify(SECRET, ID, &ts, &signature, b"{}", WINDOW));
234        assert!(!verify(SECRET, "msg_other", &ts, &signature, BODY, WINDOW));
235        assert!(!verify(
236            &generate_secret(),
237            ID,
238            &ts,
239            &signature,
240            BODY,
241            WINDOW
242        ));
243        assert!(!verify(
244            SECRET,
245            ID,
246            "not a number",
247            &signature,
248            BODY,
249            WINDOW
250        ));
251    }
252
253    #[test]
254    fn rejects_old_and_future_timestamps() {
255        let now = crate::clock::unix_secs();
256        for ts in [now - 301, now + 301] {
257            let signature = sign(SECRET, ID, ts, BODY).unwrap();
258            assert!(!verify(
259                SECRET,
260                ID,
261                &ts.to_string(),
262                &signature,
263                BODY,
264                WINDOW
265            ));
266        }
267    }
268
269    #[test]
270    fn accepts_any_of_several_signatures_and_skips_other_versions() {
271        let now = crate::clock::unix_secs();
272        let good = sign(SECRET, ID, now, BODY).unwrap();
273        let other = sign(&generate_secret(), ID, now, BODY).unwrap();
274        let ts = now.to_string();
275        let header = format!("{other} {good}");
276        assert!(verify(SECRET, ID, &ts, &header, BODY, WINDOW));
277        let header = format!("v2,abc {good}");
278        assert!(verify(SECRET, ID, &ts, &header, BODY, WINDOW));
279        assert!(!verify(SECRET, ID, &ts, "v1,!!! v2,abc", BODY, WINDOW));
280        assert!(!verify(SECRET, ID, &ts, "", BODY, WINDOW));
281    }
282
283    #[test]
284    fn generated_secrets_decode_and_differ() {
285        let a = generate_secret();
286        assert!(a.starts_with(SECRET_PREFIX));
287        assert_eq!(decode_secret(&a).unwrap().len(), 24);
288        assert_ne!(a, generate_secret());
289        assert!(decode_secret("whsec_***").is_err());
290    }
291}