1use 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#[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 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 pub fn with_job_dispatcher(mut self, dispatcher: Arc<dyn JobDispatch>) -> Self {
48 self.job_dispatcher = Some(dispatcher);
49 self
50 }
51}
52
53pub 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 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 if let Some(ref sig_config) = info.signature {
103 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 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 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 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 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 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 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 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 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 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
283fn validate_signature(
285 algorithm: SignatureAlgorithm,
286 body: &[u8],
287 secret: &str,
288 signature: &str,
289) -> bool {
290 let sig_hex = signature
292 .strip_prefix(algorithm.prefix())
293 .unwrap_or(signature);
294
295 let expected = match decode_hex(sig_hex) {
297 Some(b) => b,
298 None => 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
323fn decode_hex(s: &str) -> Option<Vec<u8>> {
324 if !s.len().is_multiple_of(2) {
325 return None;
326 }
327 (0..s.len())
328 .step_by(2)
329 .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
330 .collect()
331}
332
333fn extract_json_path(value: &Value, path: &str) -> Option<String> {
335 let path = path.strip_prefix("$.").unwrap_or(path);
336 let parts: Vec<&str> = path.split('.').collect();
337
338 let mut current = value;
339 for part in parts {
340 current = current.get(part)?;
341 }
342
343 match current {
344 Value::String(s) => Some(s.clone()),
345 Value::Number(n) => Some(n.to_string()),
346 _ => Some(current.to_string()),
347 }
348}
349
350async fn claim_idempotency(
356 pool: &PgPool,
357 webhook_name: &str,
358 key: &str,
359 ttl: std::time::Duration,
360) -> Result<bool, sqlx::Error> {
361 let expires_at =
362 chrono::Utc::now() + chrono::Duration::from_std(ttl).unwrap_or(chrono::Duration::hours(24));
363
364 let result = sqlx::query(
365 r#"
366 INSERT INTO forge_webhook_events (idempotency_key, webhook_name, processed_at, expires_at)
367 VALUES ($1, $2, NOW(), $3)
368 ON CONFLICT (webhook_name, idempotency_key) DO UPDATE
369 SET processed_at = EXCLUDED.processed_at,
370 expires_at = EXCLUDED.expires_at
371 WHERE forge_webhook_events.expires_at < NOW()
372 "#,
373 )
374 .bind(key)
375 .bind(webhook_name)
376 .bind(expires_at)
377 .execute(pool)
378 .await?;
379
380 Ok(result.rows_affected() > 0)
381}
382
383async fn release_idempotency(
385 pool: &PgPool,
386 webhook_name: &str,
387 key: &str,
388) -> Result<(), sqlx::Error> {
389 sqlx::query(
390 r#"
391 DELETE FROM forge_webhook_events
392 WHERE webhook_name = $1 AND idempotency_key = $2
393 "#,
394 )
395 .bind(webhook_name)
396 .bind(key)
397 .execute(pool)
398 .await?;
399
400 Ok(())
401}
402
403#[cfg(test)]
404#[allow(clippy::unwrap_used, clippy::indexing_slicing, clippy::panic)]
405mod tests {
406 use super::*;
407
408 fn encode_hex(bytes: &[u8]) -> String {
409 bytes
410 .iter()
411 .fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
412 use std::fmt::Write;
413 let _ = write!(s, "{b:02x}");
414 s
415 })
416 }
417
418 #[test]
419 fn test_extract_json_path_simple() {
420 let value = json!({"id": "test-123"});
421 assert_eq!(
422 extract_json_path(&value, "$.id"),
423 Some("test-123".to_string())
424 );
425 }
426
427 #[test]
428 fn test_extract_json_path_nested() {
429 let value = json!({"data": {"id": "nested-456"}});
430 assert_eq!(
431 extract_json_path(&value, "$.data.id"),
432 Some("nested-456".to_string())
433 );
434 }
435
436 #[test]
437 fn test_extract_json_path_number() {
438 let value = json!({"count": 42});
439 assert_eq!(extract_json_path(&value, "$.count"), Some("42".to_string()));
440 }
441
442 #[test]
443 fn test_extract_json_path_missing() {
444 let value = json!({"other": "value"});
445 assert_eq!(extract_json_path(&value, "$.id"), None);
446 }
447
448 #[test]
449 fn test_validate_signature_sha256() {
450 use hmac::{Hmac, Mac};
451 use sha2::Sha256;
452
453 let body = b"test payload";
454 let secret = "test_secret";
455
456 let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
457 mac.update(body);
458 let signature = encode_hex(&mac.finalize().into_bytes());
459
460 assert!(validate_signature(
461 SignatureAlgorithm::HmacSha256,
462 body,
463 secret,
464 &signature
465 ));
466
467 let sig_with_prefix = format!("sha256={}", signature);
469 assert!(validate_signature(
470 SignatureAlgorithm::HmacSha256,
471 body,
472 secret,
473 &sig_with_prefix
474 ));
475 }
476
477 #[test]
478 fn test_validate_signature_invalid() {
479 assert!(!validate_signature(
480 SignatureAlgorithm::HmacSha256,
481 b"test",
482 "secret",
483 "invalid_hex"
484 ));
485
486 assert!(!validate_signature(
487 SignatureAlgorithm::HmacSha256,
488 b"test",
489 "secret",
490 "0000000000000000000000000000000000000000000000000000000000000000"
491 ));
492 }
493}