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.inner().clone(),
226    )
227    .with_idempotency_key(idempotency_key.clone());
228
229    if let Some(ref dispatcher) = state.job_dispatcher {
230        ctx = ctx.with_job_dispatch(dispatcher.clone());
231    }
232
233    // Execute handler with timeout
234    let result = tokio::time::timeout(info.timeout, (entry.handler)(&ctx, payload)).await;
235
236    match result {
237        Ok(Ok(webhook_result)) => {
238            let status =
239                StatusCode::from_u16(webhook_result.status_code()).unwrap_or(StatusCode::OK);
240            (status, Json(webhook_result.body()))
241        }
242        Ok(Err(e)) => {
243            if idempotency_claimed
244                && let Some(ref key) = idempotency_key
245                && let Err(release_err) = release_idempotency(&state.pool, info.name, key).await
246            {
247                warn!(
248                    webhook = info.name,
249                    error = %release_err,
250                    "Failed to release idempotency key after handler error"
251                );
252            }
253            error!(webhook = info.name, error = %e, "Webhook handler error");
254            (
255                StatusCode::INTERNAL_SERVER_ERROR,
256                Json(json!({"error": e.to_string()})),
257            )
258        }
259        Err(_) => {
260            if idempotency_claimed
261                && let Some(ref key) = idempotency_key
262                && let Err(release_err) = release_idempotency(&state.pool, info.name, key).await
263            {
264                warn!(
265                    webhook = info.name,
266                    error = %release_err,
267                    "Failed to release idempotency key after timeout"
268                );
269            }
270            error!(
271                webhook = info.name,
272                timeout = ?info.timeout,
273                "Webhook handler timed out"
274            );
275            (
276                StatusCode::GATEWAY_TIMEOUT,
277                Json(json!({"error": "Request timeout"})),
278            )
279        }
280    }
281}
282
283/// Validate HMAC signature.
284fn validate_signature(
285    algorithm: SignatureAlgorithm,
286    body: &[u8],
287    secret: &str,
288    signature: &str,
289) -> bool {
290    // Strip algorithm prefix if present (e.g., "sha256=")
291    let sig_hex = signature
292        .strip_prefix(algorithm.prefix())
293        .unwrap_or(signature);
294
295    // Decode expected signature from hex
296    let expected = match hex::decode(sig_hex) {
297        Ok(b) => b,
298        Err(_) => return false,
299    };
300
301    match algorithm {
302        SignatureAlgorithm::HmacSha256 => {
303            let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
304                .expect("HMAC can take key of any size");
305            mac.update(body);
306            mac.verify_slice(&expected).is_ok()
307        }
308        SignatureAlgorithm::HmacSha1 => {
309            let mut mac = Hmac::<Sha1>::new_from_slice(secret.as_bytes())
310                .expect("HMAC can take key of any size");
311            mac.update(body);
312            mac.verify_slice(&expected).is_ok()
313        }
314        SignatureAlgorithm::HmacSha512 => {
315            let mut mac = Hmac::<Sha512>::new_from_slice(secret.as_bytes())
316                .expect("HMAC can take key of any size");
317            mac.update(body);
318            mac.verify_slice(&expected).is_ok()
319        }
320    }
321}
322
323/// Extract value from JSON using a simple path (e.g., "$.id" or "$.data.id").
324fn extract_json_path(value: &Value, path: &str) -> Option<String> {
325    let path = path.strip_prefix("$.").unwrap_or(path);
326    let parts: Vec<&str> = path.split('.').collect();
327
328    let mut current = value;
329    for part in parts {
330        current = current.get(part)?;
331    }
332
333    match current {
334        Value::String(s) => Some(s.clone()),
335        Value::Number(n) => Some(n.to_string()),
336        _ => Some(current.to_string()),
337    }
338}
339
340/// Atomically claim idempotency key before processing.
341///
342/// Returns:
343/// - `Ok(true)` if this request acquired the claim
344/// - `Ok(false)` if key is already active
345async fn claim_idempotency(
346    pool: &PgPool,
347    webhook_name: &str,
348    key: &str,
349    ttl: std::time::Duration,
350) -> Result<bool, sqlx::Error> {
351    let expires_at =
352        chrono::Utc::now() + chrono::Duration::from_std(ttl).unwrap_or(chrono::Duration::hours(24));
353
354    let result = sqlx::query(
355        r#"
356        INSERT INTO forge_webhook_events (idempotency_key, webhook_name, processed_at, expires_at)
357        VALUES ($1, $2, NOW(), $3)
358        ON CONFLICT (webhook_name, idempotency_key) DO UPDATE
359            SET processed_at = EXCLUDED.processed_at,
360                expires_at = EXCLUDED.expires_at
361        WHERE forge_webhook_events.expires_at < NOW()
362        "#,
363    )
364    .bind(key)
365    .bind(webhook_name)
366    .bind(expires_at)
367    .execute(pool)
368    .await?;
369
370    Ok(result.rows_affected() > 0)
371}
372
373/// Release idempotency key after failure so retries can proceed.
374async fn release_idempotency(
375    pool: &PgPool,
376    webhook_name: &str,
377    key: &str,
378) -> Result<(), sqlx::Error> {
379    sqlx::query(
380        r#"
381        DELETE FROM forge_webhook_events
382        WHERE webhook_name = $1 AND idempotency_key = $2
383        "#,
384    )
385    .bind(webhook_name)
386    .bind(key)
387    .execute(pool)
388    .await?;
389
390    Ok(())
391}
392
393#[cfg(test)]
394#[allow(clippy::unwrap_used, clippy::indexing_slicing, clippy::panic)]
395mod tests {
396    use super::*;
397
398    #[test]
399    fn test_extract_json_path_simple() {
400        let value = json!({"id": "test-123"});
401        assert_eq!(
402            extract_json_path(&value, "$.id"),
403            Some("test-123".to_string())
404        );
405    }
406
407    #[test]
408    fn test_extract_json_path_nested() {
409        let value = json!({"data": {"id": "nested-456"}});
410        assert_eq!(
411            extract_json_path(&value, "$.data.id"),
412            Some("nested-456".to_string())
413        );
414    }
415
416    #[test]
417    fn test_extract_json_path_number() {
418        let value = json!({"count": 42});
419        assert_eq!(extract_json_path(&value, "$.count"), Some("42".to_string()));
420    }
421
422    #[test]
423    fn test_extract_json_path_missing() {
424        let value = json!({"other": "value"});
425        assert_eq!(extract_json_path(&value, "$.id"), None);
426    }
427
428    #[test]
429    fn test_validate_signature_sha256() {
430        use hmac::{Hmac, Mac};
431        use sha2::Sha256;
432
433        let body = b"test payload";
434        let secret = "test_secret";
435
436        let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
437        mac.update(body);
438        let signature = hex::encode(mac.finalize().into_bytes());
439
440        assert!(validate_signature(
441            SignatureAlgorithm::HmacSha256,
442            body,
443            secret,
444            &signature
445        ));
446
447        // With prefix
448        let sig_with_prefix = format!("sha256={}", signature);
449        assert!(validate_signature(
450            SignatureAlgorithm::HmacSha256,
451            body,
452            secret,
453            &sig_with_prefix
454        ));
455    }
456
457    #[test]
458    fn test_validate_signature_invalid() {
459        assert!(!validate_signature(
460            SignatureAlgorithm::HmacSha256,
461            b"test",
462            "secret",
463            "invalid_hex"
464        ));
465
466        assert!(!validate_signature(
467            SignatureAlgorithm::HmacSha256,
468            b"test",
469            "secret",
470            "0000000000000000000000000000000000000000000000000000000000000000"
471        ));
472    }
473}