Skip to main content

forge_runtime/webhook/
handler.rs

1//! Axum handler for webhook requests with signature validation.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use axum::{
7    Json,
8    body::Bytes,
9    extract::{Path, State},
10    http::{HeaderMap, StatusCode},
11    response::IntoResponse,
12};
13use forge_core::CircuitBreakerClient;
14use forge_core::function::JobDispatch;
15use forge_core::webhook::{IdempotencySource, SignatureAlgorithm, WebhookContext};
16use hmac::{Hmac, Mac};
17use serde_json::{Value, json};
18use sha1::Sha1;
19use sha2::{Sha256, Sha512};
20use sqlx::PgPool;
21use tracing::{error, info, warn};
22use uuid::Uuid;
23
24use super::registry::WebhookRegistry;
25
26/// State for webhook handler.
27#[derive(Clone)]
28pub struct WebhookState {
29    registry: Arc<WebhookRegistry>,
30    pool: PgPool,
31    http_client: CircuitBreakerClient,
32    job_dispatcher: Option<Arc<dyn JobDispatch>>,
33}
34
35impl WebhookState {
36    /// Create new webhook state.
37    pub fn new(registry: Arc<WebhookRegistry>, pool: PgPool) -> Self {
38        Self {
39            registry,
40            pool,
41            http_client: CircuitBreakerClient::with_defaults(reqwest::Client::new()),
42            job_dispatcher: None,
43        }
44    }
45
46    /// Set job dispatcher.
47    pub fn with_job_dispatcher(mut self, dispatcher: Arc<dyn JobDispatch>) -> Self {
48        self.job_dispatcher = Some(dispatcher);
49        self
50    }
51}
52
53/// Handle webhook requests.
54///
55/// This handler:
56/// 1. Looks up webhook by path
57/// 2. Validates signature if configured
58/// 3. Checks idempotency
59/// 4. Executes handler
60/// 5. Records idempotency key
61pub async fn webhook_handler(
62    State(state): State<Arc<WebhookState>>,
63    Path(path): Path<String>,
64    headers: HeaderMap,
65    body: Bytes,
66) -> impl IntoResponse {
67    let full_path = format!("/webhooks/{}", path);
68    let request_id = Uuid::new_v4().to_string();
69
70    // Look up webhook by path
71    let entry = match state.registry.get_by_path(&full_path) {
72        Some(e) => e,
73        None => {
74            warn!(path = %full_path, "Webhook not found");
75            return (
76                StatusCode::NOT_FOUND,
77                Json(json!({"error": "Webhook not found"})),
78            );
79        }
80    };
81
82    let info = &entry.info;
83    info!(
84        webhook = info.name,
85        path = %full_path,
86        request_id = %request_id,
87        "Webhook request received"
88    );
89
90    if info.signature.is_none() && !info.allow_unsigned {
91        warn!(
92            webhook = info.name,
93            "Unsigned webhook rejected (set allow_unsigned to opt in)"
94        );
95        return (
96            StatusCode::UNAUTHORIZED,
97            Json(json!({"error": "Webhook signature is required"})),
98        );
99    }
100
101    // Validate signature if configured
102    if let Some(ref sig_config) = info.signature {
103        // Get signature from header
104        let signature = match headers
105            .get(sig_config.header_name)
106            .and_then(|v| v.to_str().ok())
107        {
108            Some(s) => s,
109            None => {
110                warn!(webhook = info.name, "Missing signature header");
111                return (
112                    StatusCode::UNAUTHORIZED,
113                    Json(json!({"error": "Missing signature"})),
114                );
115            }
116        };
117
118        // Get secret from environment
119        let secret = match std::env::var(sig_config.secret_env) {
120            Ok(s) => s,
121            Err(_) => {
122                error!(
123                    webhook = info.name,
124                    env = sig_config.secret_env,
125                    "Webhook secret not configured"
126                );
127                return (
128                    StatusCode::INTERNAL_SERVER_ERROR,
129                    Json(json!({"error": "Webhook configuration error"})),
130                );
131            }
132        };
133
134        // Validate signature
135        if !validate_signature(sig_config.algorithm, &body, &secret, signature) {
136            warn!(webhook = info.name, "Invalid signature");
137            return (
138                StatusCode::UNAUTHORIZED,
139                Json(json!({"error": "Invalid signature"})),
140            );
141        }
142    }
143
144    // Extract idempotency key if configured
145    let idempotency_key = if let Some(ref idem_config) = info.idempotency {
146        match &idem_config.source {
147            IdempotencySource::Header(header_name) => headers
148                .get(*header_name)
149                .and_then(|v| v.to_str().ok())
150                .map(|s| s.to_string()),
151            IdempotencySource::Body(json_path) => {
152                // Parse body and extract value using JSON path
153                if let Ok(payload) = serde_json::from_slice::<Value>(&body) {
154                    extract_json_path(&payload, json_path)
155                } else {
156                    None
157                }
158            }
159        }
160    } else {
161        None
162    };
163
164    // Atomically claim idempotency key before execution.
165    let mut idempotency_claimed = false;
166    if let Some(ref key) = idempotency_key
167        && let Some(ref idem_config) = info.idempotency
168    {
169        match claim_idempotency(&state.pool, info.name, key, idem_config.ttl).await {
170            Ok(true) => {
171                idempotency_claimed = true;
172            }
173            Ok(false) => {
174                info!(
175                    webhook = info.name,
176                    idempotency_key = %key,
177                    "Request already processed (idempotent)"
178                );
179                return (StatusCode::OK, Json(json!({"status": "already_processed"})));
180            }
181            Err(e) => {
182                warn!(webhook = info.name, error = %e, "Failed to claim idempotency key");
183            }
184        }
185    }
186
187    // Parse payload
188    let payload: Value = match serde_json::from_slice(&body) {
189        Ok(v) => v,
190        Err(e) => {
191            if idempotency_claimed
192                && let Some(ref key) = idempotency_key
193                && let Err(release_err) = release_idempotency(&state.pool, info.name, key).await
194            {
195                warn!(
196                    webhook = info.name,
197                    error = %release_err,
198                    "Failed to release idempotency key after JSON parse failure"
199                );
200            }
201            warn!(webhook = info.name, error = %e, "Invalid JSON payload");
202            return (
203                StatusCode::BAD_REQUEST,
204                Json(json!({"error": "Invalid JSON"})),
205            );
206        }
207    };
208
209    // Build headers map (lowercase keys)
210    let header_map: HashMap<String, String> = headers
211        .iter()
212        .filter_map(|(k, v)| {
213            v.to_str()
214                .ok()
215                .map(|v| (k.as_str().to_lowercase(), v.to_string()))
216        })
217        .collect();
218
219    // Create context
220    let mut ctx = WebhookContext::new(
221        info.name.to_string(),
222        request_id.clone(),
223        header_map,
224        state.pool.clone(),
225        state.http_client.clone(),
226    )
227    .with_idempotency_key(idempotency_key.clone());
228    ctx.set_http_timeout(info.http_timeout);
229
230    if let Some(ref dispatcher) = state.job_dispatcher {
231        ctx = ctx.with_job_dispatch(dispatcher.clone());
232    }
233
234    // Execute handler with timeout
235    let result = tokio::time::timeout(info.timeout, (entry.handler)(&ctx, payload)).await;
236
237    match result {
238        Ok(Ok(webhook_result)) => {
239            let status =
240                StatusCode::from_u16(webhook_result.status_code()).unwrap_or(StatusCode::OK);
241            (status, Json(webhook_result.body()))
242        }
243        Ok(Err(e)) => {
244            if idempotency_claimed
245                && let Some(ref key) = idempotency_key
246                && let Err(release_err) = release_idempotency(&state.pool, info.name, key).await
247            {
248                warn!(
249                    webhook = info.name,
250                    error = %release_err,
251                    "Failed to release idempotency key after handler error"
252                );
253            }
254            error!(webhook = info.name, error = %e, "Webhook handler error");
255            (
256                StatusCode::INTERNAL_SERVER_ERROR,
257                Json(json!({"error": e.to_string()})),
258            )
259        }
260        Err(_) => {
261            if idempotency_claimed
262                && let Some(ref key) = idempotency_key
263                && let Err(release_err) = release_idempotency(&state.pool, info.name, key).await
264            {
265                warn!(
266                    webhook = info.name,
267                    error = %release_err,
268                    "Failed to release idempotency key after timeout"
269                );
270            }
271            error!(
272                webhook = info.name,
273                timeout = ?info.timeout,
274                "Webhook handler timed out"
275            );
276            (
277                StatusCode::GATEWAY_TIMEOUT,
278                Json(json!({"error": "Request timeout"})),
279            )
280        }
281    }
282}
283
284/// Validate HMAC signature.
285fn validate_signature(
286    algorithm: SignatureAlgorithm,
287    body: &[u8],
288    secret: &str,
289    signature: &str,
290) -> bool {
291    // Strip algorithm prefix if present (e.g., "sha256=")
292    let sig_hex = signature
293        .strip_prefix(algorithm.prefix())
294        .unwrap_or(signature);
295
296    // Decode expected signature from hex
297    let expected = match decode_hex(sig_hex) {
298        Some(b) => b,
299        None => return false,
300    };
301
302    match algorithm {
303        SignatureAlgorithm::HmacSha256 => {
304            let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
305                .expect("HMAC can take key of any size");
306            mac.update(body);
307            mac.verify_slice(&expected).is_ok()
308        }
309        SignatureAlgorithm::HmacSha1 => {
310            let mut mac = Hmac::<Sha1>::new_from_slice(secret.as_bytes())
311                .expect("HMAC can take key of any size");
312            mac.update(body);
313            mac.verify_slice(&expected).is_ok()
314        }
315        SignatureAlgorithm::HmacSha512 => {
316            let mut mac = Hmac::<Sha512>::new_from_slice(secret.as_bytes())
317                .expect("HMAC can take key of any size");
318            mac.update(body);
319            mac.verify_slice(&expected).is_ok()
320        }
321    }
322}
323
324fn decode_hex(s: &str) -> Option<Vec<u8>> {
325    if !s.len().is_multiple_of(2) {
326        return None;
327    }
328    (0..s.len())
329        .step_by(2)
330        .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
331        .collect()
332}
333
334/// Extract value from JSON using a simple path (e.g., "$.id" or "$.data.id").
335fn extract_json_path(value: &Value, path: &str) -> Option<String> {
336    let path = path.strip_prefix("$.").unwrap_or(path);
337    let parts: Vec<&str> = path.split('.').collect();
338
339    let mut current = value;
340    for part in parts {
341        current = current.get(part)?;
342    }
343
344    match current {
345        Value::String(s) => Some(s.clone()),
346        Value::Number(n) => Some(n.to_string()),
347        _ => Some(current.to_string()),
348    }
349}
350
351/// Atomically claim idempotency key before processing.
352///
353/// Returns:
354/// - `Ok(true)` if this request acquired the claim
355/// - `Ok(false)` if key is already active
356async fn claim_idempotency(
357    pool: &PgPool,
358    webhook_name: &str,
359    key: &str,
360    ttl: std::time::Duration,
361) -> Result<bool, sqlx::Error> {
362    let expires_at =
363        chrono::Utc::now() + chrono::Duration::from_std(ttl).unwrap_or(chrono::Duration::hours(24));
364
365    let result = sqlx::query(
366        r#"
367        INSERT INTO forge_webhook_events (idempotency_key, webhook_name, processed_at, expires_at)
368        VALUES ($1, $2, NOW(), $3)
369        ON CONFLICT (webhook_name, idempotency_key) DO UPDATE
370            SET processed_at = EXCLUDED.processed_at,
371                expires_at = EXCLUDED.expires_at
372        WHERE forge_webhook_events.expires_at < NOW()
373        "#,
374    )
375    .bind(key)
376    .bind(webhook_name)
377    .bind(expires_at)
378    .execute(pool)
379    .await?;
380
381    Ok(result.rows_affected() > 0)
382}
383
384/// Release idempotency key after failure so retries can proceed.
385async fn release_idempotency(
386    pool: &PgPool,
387    webhook_name: &str,
388    key: &str,
389) -> Result<(), sqlx::Error> {
390    sqlx::query(
391        r#"
392        DELETE FROM forge_webhook_events
393        WHERE webhook_name = $1 AND idempotency_key = $2
394        "#,
395    )
396    .bind(webhook_name)
397    .bind(key)
398    .execute(pool)
399    .await?;
400
401    Ok(())
402}
403
404#[cfg(test)]
405#[allow(clippy::unwrap_used, clippy::indexing_slicing, clippy::panic)]
406mod tests {
407    use super::*;
408
409    fn encode_hex(bytes: &[u8]) -> String {
410        bytes
411            .iter()
412            .fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
413                use std::fmt::Write;
414                let _ = write!(s, "{b:02x}");
415                s
416            })
417    }
418
419    #[test]
420    fn test_extract_json_path_simple() {
421        let value = json!({"id": "test-123"});
422        assert_eq!(
423            extract_json_path(&value, "$.id"),
424            Some("test-123".to_string())
425        );
426    }
427
428    #[test]
429    fn test_extract_json_path_nested() {
430        let value = json!({"data": {"id": "nested-456"}});
431        assert_eq!(
432            extract_json_path(&value, "$.data.id"),
433            Some("nested-456".to_string())
434        );
435    }
436
437    #[test]
438    fn test_extract_json_path_number() {
439        let value = json!({"count": 42});
440        assert_eq!(extract_json_path(&value, "$.count"), Some("42".to_string()));
441    }
442
443    #[test]
444    fn test_extract_json_path_missing() {
445        let value = json!({"other": "value"});
446        assert_eq!(extract_json_path(&value, "$.id"), None);
447    }
448
449    #[test]
450    fn test_validate_signature_sha256() {
451        use hmac::{Hmac, Mac};
452        use sha2::Sha256;
453
454        let body = b"test payload";
455        let secret = "test_secret";
456
457        let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
458        mac.update(body);
459        let signature = encode_hex(&mac.finalize().into_bytes());
460
461        assert!(validate_signature(
462            SignatureAlgorithm::HmacSha256,
463            body,
464            secret,
465            &signature
466        ));
467
468        // With prefix
469        let sig_with_prefix = format!("sha256={}", signature);
470        assert!(validate_signature(
471            SignatureAlgorithm::HmacSha256,
472            body,
473            secret,
474            &sig_with_prefix
475        ));
476    }
477
478    #[test]
479    fn test_validate_signature_invalid() {
480        assert!(!validate_signature(
481            SignatureAlgorithm::HmacSha256,
482            b"test",
483            "secret",
484            "invalid_hex"
485        ));
486
487        assert!(!validate_signature(
488            SignatureAlgorithm::HmacSha256,
489            b"test",
490            "secret",
491            "0000000000000000000000000000000000000000000000000000000000000000"
492        ));
493    }
494}