Skip to main content

rushls_common/hooks/
signing.rs

1//! Standard Webhooks signing over the exact transmitted bytes.
2
3use base64::{Engine, engine::general_purpose::STANDARD};
4use http::{HeaderMap, HeaderValue};
5use ring::hmac;
6
7#[derive(Clone, derive_more::Debug)]
8#[debug("SigningSecret([REDACTED])")]
9pub struct SigningSecret(#[debug(skip)] hmac::Key);
10
11#[derive(Clone, Copy, Debug, thiserror::Error)]
12#[error("a signing secret must be whsec_ followed by base64 encoding of at least 32 random bytes")]
13pub struct InvalidSigningSecret;
14
15impl SigningSecret {
16    /// Decode a Standard Webhooks key. No credential material appears in errors.
17    pub fn parse(value: &str) -> Result<Self, InvalidSigningSecret> {
18        let bytes = STANDARD
19            .decode(value.strip_prefix("whsec_").ok_or(InvalidSigningSecret)?)
20            .map_err(|_| InvalidSigningSecret)?;
21        if bytes.len() < 32 {
22            return Err(InvalidSigningSecret);
23        }
24        Ok(Self(hmac::Key::new(hmac::HMAC_SHA256, &bytes)))
25    }
26
27    pub fn headers(&self, id: &str, timestamp: i64, body: &[u8]) -> HeaderMap {
28        let timestamp = timestamp.to_string();
29        let mut context = hmac::Context::with_key(&self.0);
30        for part in [id.as_bytes(), b".", timestamp.as_bytes(), b".", body] {
31            context.update(part);
32        }
33        let signature = format!("v1,{}", STANDARD.encode(context.sign().as_ref()));
34        let mut headers = HeaderMap::new();
35        headers.insert(
36            "webhook-id",
37            HeaderValue::from_str(id).expect("rendered event IDs are UUIDs"),
38        );
39        headers.insert(
40            "webhook-timestamp",
41            HeaderValue::from_str(&timestamp).expect("integer timestamp"),
42        );
43        headers.insert(
44            "webhook-signature",
45            HeaderValue::from_str(&signature).expect("base64 signature"),
46        );
47        headers
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn signs_exact_bytes_and_redacts_the_key() -> Result<(), Box<dyn std::error::Error>> {
57        let secret = SigningSecret::parse(&format!("whsec_{}", STANDARD.encode([0x0b; 32])))?;
58        let headers = secret.headers("event-1", 1700000000, b"{\"x\":1}");
59        // Independently generated with Python's hmac/hashlib, including separators.
60        assert_eq!(
61            headers["webhook-signature"],
62            "v1,9DvJSHdiZ8rvAljEp90tkqqoZuZGuN9vAzXBdsOP7p0="
63        );
64        assert_ne!(
65            headers,
66            secret.headers("event-1", 1700000000, b"{ \"x\":1}")
67        );
68        assert_ne!(headers, secret.headers("event-2", 1700000000, b"{\"x\":1}"));
69        assert_ne!(headers, secret.headers("event-1", 1700000001, b"{\"x\":1}"));
70        assert_eq!(format!("{secret:?}"), "SigningSecret([REDACTED])");
71        assert!(SigningSecret::parse("whsec_YQ==").is_err());
72        assert!(SigningSecret::parse("secret").is_err());
73        Ok(())
74    }
75}