Skip to main content

yaiko_core/
webhook.rs

1//! Signed webhook event primitives and delivery preparation helpers.
2
3use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
4use hmac::{Hmac, Mac};
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use sha2::Sha256;
8use std::collections::HashMap;
9use std::sync::Arc;
10use std::time::{Duration, SystemTime, UNIX_EPOCH};
11use tokio::sync::Mutex;
12
13type HmacSha256 = Hmac<Sha256>;
14
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
16pub struct WebhookEvent {
17    pub id: String,
18    pub event_type: String,
19    pub created_at: u64,
20    pub payload: Value,
21}
22
23impl WebhookEvent {
24    pub fn new(id: impl Into<String>, event_type: impl Into<String>, payload: Value) -> Self {
25        Self {
26            id: id.into(),
27            event_type: event_type.into(),
28            created_at: now_unix(),
29            payload,
30        }
31    }
32
33    pub fn body(&self) -> Result<Vec<u8>, serde_json::Error> {
34        serde_json::to_vec(self)
35    }
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct PreparedWebhook {
40    pub url: String,
41    pub body: Vec<u8>,
42    pub signature: String,
43    pub event_id: String,
44}
45
46#[derive(Clone)]
47pub struct WebhookVerifier {
48    secret: Arc<Vec<u8>>,
49    tolerance: Duration,
50    seen: Arc<Mutex<HashMap<String, u64>>>,
51}
52
53impl WebhookVerifier {
54    pub fn new(secret: impl AsRef<[u8]>, tolerance: Duration) -> Self {
55        Self {
56            secret: Arc::new(secret.as_ref().to_vec()),
57            tolerance,
58            seen: Arc::new(Mutex::new(HashMap::new())),
59        }
60    }
61
62    pub fn signature(&self, timestamp: u64, body: &[u8]) -> Result<String, &'static str> {
63        let mut mac =
64            HmacSha256::new_from_slice(self.secret.as_slice()).map_err(|_| "invalid secret")?;
65        mac.update(format!("{}.", timestamp).as_bytes());
66        mac.update(body);
67        Ok(format!(
68            "t={},v1={}",
69            timestamp,
70            URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes())
71        ))
72    }
73
74    pub async fn verify(&self, header: &str, body: &[u8], now: u64) -> Result<u64, WebhookError> {
75        let (timestamp, provided) = parse_signature(header)?;
76        let tolerance = self.tolerance.as_secs();
77        if now.abs_diff(timestamp) > tolerance {
78            return Err(WebhookError::Expired);
79        }
80        let expected = self
81            .signature(timestamp, body)
82            .map_err(|_| WebhookError::InvalidSecret)?;
83        let expected = expected
84            .split_once("v1=")
85            .map(|(_, value)| value)
86            .unwrap_or_default();
87        if !constant_time_eq(expected.as_bytes(), provided.as_bytes()) {
88            return Err(WebhookError::InvalidSignature);
89        }
90        let replay_key = format!("{}:{}", timestamp, provided);
91        let mut seen = self.seen.lock().await;
92        seen.retain(|_, seen_at| now.saturating_sub(*seen_at) <= tolerance);
93        if seen.insert(replay_key, now).is_some() {
94            return Err(WebhookError::Replay);
95        }
96        Ok(timestamp)
97    }
98
99    pub async fn prepare(
100        &self,
101        url: impl Into<String>,
102        event: &WebhookEvent,
103        timestamp: u64,
104    ) -> Result<PreparedWebhook, &'static str> {
105        let body = event.body().map_err(|_| "event serialization failed")?;
106        let signature = self.signature(timestamp, &body)?;
107        Ok(PreparedWebhook {
108            url: url.into(),
109            body,
110            signature,
111            event_id: event.id.clone(),
112        })
113    }
114}
115
116#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
117pub enum WebhookError {
118    #[error("malformed webhook signature")]
119    MalformedSignature,
120    #[error("webhook signature expired")]
121    Expired,
122    #[error("invalid webhook secret")]
123    InvalidSecret,
124    #[error("invalid webhook signature")]
125    InvalidSignature,
126    #[error("webhook signature replay detected")]
127    Replay,
128}
129
130fn parse_signature(header: &str) -> Result<(u64, &str), WebhookError> {
131    let mut timestamp = None;
132    let mut signature = None;
133    for part in header.split(',') {
134        let Some((key, value)) = part.trim().split_once('=') else {
135            continue;
136        };
137        match key {
138            "t" => timestamp = value.parse::<u64>().ok(),
139            "v1" if !value.is_empty() => signature = Some(value),
140            _ => {}
141        }
142    }
143    match (timestamp, signature) {
144        (Some(timestamp), Some(signature)) => Ok((timestamp, signature)),
145        _ => Err(WebhookError::MalformedSignature),
146    }
147}
148
149fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
150    left.len() == right.len()
151        && left
152            .iter()
153            .zip(right)
154            .fold(0u8, |acc, (a, b)| acc | (a ^ b))
155            == 0
156}
157
158fn now_unix() -> u64 {
159    SystemTime::now()
160        .duration_since(UNIX_EPOCH)
161        .unwrap_or_default()
162        .as_secs()
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use serde_json::json;
169
170    #[tokio::test]
171    async fn signs_verifies_and_rejects_replays() {
172        let verifier = WebhookVerifier::new("secret", Duration::from_secs(60));
173        let event = WebhookEvent::new("evt-1", "video.ready", json!({"clip": 7}));
174        let body = event.body().unwrap();
175        let header = verifier.signature(100, &body).unwrap();
176        assert_eq!(verifier.verify(&header, &body, 100).await, Ok(100));
177        assert_eq!(
178            verifier.verify(&header, &body, 100).await,
179            Err(WebhookError::Replay)
180        );
181    }
182
183    #[tokio::test]
184    async fn rejects_tampering_and_stale_timestamps() {
185        let verifier = WebhookVerifier::new("secret", Duration::from_secs(60));
186        let body = br#"{"ok":true}"#;
187        let header = verifier.signature(100, body).unwrap();
188        assert_eq!(
189            verifier.verify(&header, br#"{"ok":false}"#, 100).await,
190            Err(WebhookError::InvalidSignature)
191        );
192        assert_eq!(
193            verifier.verify(&header, body, 161).await,
194            Err(WebhookError::Expired)
195        );
196    }
197
198    #[tokio::test]
199    async fn prepares_signed_event_delivery() {
200        let verifier = WebhookVerifier::new("secret", Duration::from_secs(60));
201        let event = WebhookEvent::new("evt-2", "caption.created", json!({"id": 9}));
202        let prepared = verifier
203            .prepare("https://example.test/hooks", &event, 100)
204            .await
205            .unwrap();
206        assert_eq!(prepared.url, "https://example.test/hooks");
207        assert_eq!(prepared.event_id, "evt-2");
208        assert!(prepared.signature.starts_with("t=100,v1="));
209    }
210}