1use 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
37pub const SECRET_PREFIX: &str = "whsec_";
39
40pub fn generate_secret() -> String {
43 let mut bytes = [0u8; 24];
44 rand::fill(&mut bytes);
45 format!("{SECRET_PREFIX}{}", STANDARD.encode(bytes))
46}
47
48pub 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
73pub fn sign(secret: &str, id: &str, timestamp: i64, body: &[u8]) -> Result<String> {
78 let key = decode_secret(secret)?;
79 let digest = mac(&key, id, ×tamp.to_string(), body)
80 .finalize()
81 .into_bytes();
82 Ok(format!("v1,{}", STANDARD.encode(digest)))
83}
84
85pub 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
126pub struct SignedRequest<T>(pub T);
148
149fn 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 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, ×tamp, &signature, &body, tolerance) {
191 return Err(unauthorized());
192 }
193 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}