1use std::{
88 fmt,
89 future::{Future, ready},
90 pin::Pin,
91 sync::Arc,
92};
93
94use actix_web::{
95 FromRequest, HttpRequest, ResponseError,
96 dev::Payload,
97 http::{
98 StatusCode,
99 header::{HeaderMap as ActixHeaderMap, HeaderName},
100 },
101 web::Bytes,
102};
103
104use crate::core::adapter_utils::rejection_status;
105use crate::{
106 HeaderMap, Provider, Secret, VerifyError, VerifyOptions, providers::signature_header_names,
107};
108
109#[must_use]
116#[derive(Clone)]
117pub struct WebhookConfig {
118 provider: Provider,
119 secret: Arc<Secret>,
120 options: Arc<VerifyOptions>,
121}
122
123impl fmt::Debug for WebhookConfig {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 f.debug_struct("WebhookConfig")
128 .field("provider", &self.provider)
129 .field("secret", &self.secret)
130 .field("options", &self.options)
131 .finish()
132 }
133}
134
135impl WebhookConfig {
136 pub fn new(provider: Provider, secret: Secret) -> Self {
138 Self::with_options(provider, secret, VerifyOptions::default())
139 }
140
141 pub fn with_options(provider: Provider, secret: Secret, options: VerifyOptions) -> Self {
145 Self {
146 provider,
147 secret: Arc::new(secret),
148 options: Arc::new(options),
149 }
150 }
151}
152
153#[must_use]
159pub struct VerifiedBody(Bytes);
160
161impl VerifiedBody {
162 #[must_use]
164 pub fn as_bytes(&self) -> &[u8] {
165 &self.0
166 }
167
168 pub fn into_inner(self) -> Bytes {
170 self.0
171 }
172}
173
174impl fmt::Debug for VerifiedBody {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 f.debug_struct("VerifiedBody")
179 .field("len", &self.0.len())
180 .finish()
181 }
182}
183
184impl std::ops::Deref for VerifiedBody {
185 type Target = [u8];
186
187 fn deref(&self) -> &[u8] {
188 self.as_bytes()
189 }
190}
191
192#[derive(Debug)]
194enum Rejection {
195 Verify(VerifyError),
197 BodyRead,
200}
201
202#[must_use]
205#[derive(Debug)]
206pub struct WebhookVerificationError(Rejection);
207
208impl fmt::Display for WebhookVerificationError {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 match &self.0 {
211 Rejection::Verify(error) => write!(f, "webhook verification failed: {error}"),
214 Rejection::BodyRead => f.write_str("webhook body could not be read"),
215 }
216 }
217}
218
219impl std::error::Error for WebhookVerificationError {}
220
221impl ResponseError for WebhookVerificationError {
222 fn status_code(&self) -> StatusCode {
223 match &self.0 {
224 Rejection::BodyRead => StatusCode::BAD_REQUEST,
225 Rejection::Verify(error) => StatusCode::from_u16(rejection_status(error))
229 .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
230 }
231 }
232
233 }
237
238fn conflicting_signature_header(
245 headers: &ActixHeaderMap,
246 names: &[&'static str],
247) -> Option<&'static str> {
248 names.iter().copied().find(|name| {
249 let Ok(key) = HeaderName::from_bytes(name.as_bytes()) else {
250 return true;
251 };
252 let mut values = headers.get_all(&key);
253 let Some(first) = values.next() else {
254 return false;
255 };
256 values.any(|value| value != first)
257 })
258}
259
260type ExtractFuture = Pin<Box<dyn Future<Output = Result<VerifiedBody, WebhookVerificationError>>>>;
261
262impl FromRequest for VerifiedBody {
263 type Error = WebhookVerificationError;
264 type Future = ExtractFuture;
265
266 fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
267 let Some(config) = req.app_data::<WebhookConfig>() else {
270 return Box::pin(ready(Err(WebhookVerificationError(Rejection::Verify(
271 VerifyError::MissingContext {
272 reason: "no WebhookConfig registered via app_data",
273 },
274 )))));
275 };
276
277 let names = signature_header_names(&config.provider);
280 if let Some(header) = conflicting_signature_header(req.headers(), &names) {
281 return Box::pin(ready(Err(WebhookVerificationError(Rejection::Verify(
282 VerifyError::MalformedHeader {
283 header,
284 reason: "header present multiple times with different values",
285 },
286 )))));
287 }
288
289 let config = config.clone();
290 let mut payload = payload.take();
291 let req = req.clone();
292
293 Box::pin(async move {
294 let raw_body = match Bytes::from_request(&req, &mut payload).await {
297 Ok(bytes) => bytes,
298 Err(_) => return Err(WebhookVerificationError(Rejection::BodyRead)),
299 };
300
301 match crate::verify(
302 config.provider,
303 req.headers(),
304 raw_body.as_ref(),
305 &config.secret,
306 (*config.options).clone(),
307 ) {
308 Ok(()) => Ok(VerifiedBody(raw_body)),
309 Err(error) => Err(WebhookVerificationError(Rejection::Verify(error))),
310 }
311 })
312 }
313}
314
315impl HeaderMap for ActixHeaderMap {
326 fn get(&self, name: &str) -> Option<&str> {
327 let key = HeaderName::from_bytes(name.as_bytes()).ok()?;
330 let value = ActixHeaderMap::get(self, &key)?;
333 value.to_str().ok()
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340 #[cfg(feature = "paypal")]
343 use crate::VerifyingKeyMaterial;
344 use crate::test_helpers::{FixedClock, clocked_at, epoch};
345 use actix_web::{App, HttpResponse, http, test as aw_test, web};
346
347 const GITHUB_SECRET: &str = "It's a Secret to Everybody";
351 const GITHUB_BODY: &[u8] = b"Hello, World!";
352 const GITHUB_SIGNATURE: &str =
353 "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
354
355 const SLACK_SECRET: &str = "8f742231b10e8888abcd99yyyzzz85a5";
359 const SLACK_TIMESTAMP: u64 = 1_531_420_618;
360 const SLACK_BODY: &[u8] =
361 b"token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&team_domain=testteamnow&channel_id=G8PSS9T3V&channel_name=foobar&user_id=U2CERLKJA&user_name=roadrunner&command=%2Fwebhook-collect&text=&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgcZRskXaIFfN&trigger_id=398738663015.47445629121.803a0bc887a14d10d2c447fce8b6703c";
362 const SLACK_SIGNATURE: &str =
363 "a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503";
364
365 async fn echo_len(body: VerifiedBody) -> HttpResponse {
368 HttpResponse::Ok().body(body.len().to_string())
369 }
370
371 async fn echo_len_slack(_body: VerifiedBody) -> HttpResponse {
372 unreachable!("only called where extraction should succeed")
373 }
374
375 macro_rules! github_app {
379 () => {
380 aw_test::init_service(
381 App::new()
382 .app_data(WebhookConfig::new(
383 Provider::GitHub,
384 Secret::new(GITHUB_SECRET),
385 ))
386 .route("/", web::post().to(echo_len)),
387 )
388 .await
389 };
390 }
391
392 fn github_request(body: &'static [u8]) -> aw_test::TestRequest {
393 aw_test::TestRequest::post()
394 .insert_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
395 .set_payload(Bytes::from_static(body))
396 }
397
398 #[actix_web::test]
401 async fn valid_signature_reaches_handler_with_exact_bytes() {
402 let app = github_app!();
403 let res = aw_test::call_service(&app, github_request(GITHUB_BODY).to_request()).await;
404 assert_eq!(res.status(), StatusCode::OK);
405 assert_eq!(aw_test::read_body(res).await, Bytes::from_static(b"13"));
406 }
407
408 #[actix_web::test]
409 async fn empty_and_unicode_bodies_round_trip_byte_exactly() {
410 const EMPTY_SIG: &str =
414 "sha256=66a0c074deaa0f489ead6537e0d32f9a344b90bbeda705b6ed45ecd3b413fb40";
415 const UNICODE_BODY: &[u8] = "héllo, 🦀 world!".as_bytes();
416 const UNICODE_SIG: &str =
417 "sha256=815772f88bf8950c7457b57856f4b33ca9d07e7ef7a50646b067b4a613f735c4";
418
419 for (body, signature) in [
420 (&b""[..], EMPTY_SIG),
421 (UNICODE_BODY, UNICODE_SIG),
422 (GITHUB_BODY, GITHUB_SIGNATURE),
423 ] {
424 let expected_len = body.len().to_string();
425 let app = github_app!();
426 let req = aw_test::TestRequest::post()
427 .insert_header(("X-Hub-Signature-256", signature))
428 .set_payload(Bytes::copy_from_slice(body))
429 .to_request();
430 let res = aw_test::call_service(&app, req).await;
431 assert_eq!(res.status(), StatusCode::OK);
432 assert_eq!(aw_test::read_body(res).await, Bytes::from(expected_len));
433 }
434 }
435
436 #[actix_web::test]
439 async fn tampered_body_is_unauthorized_and_never_reaches_handler() {
440 let app = github_app!();
441 let res = aw_test::call_service(&app, github_request(b"Hello, World?").to_request()).await;
442 assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
443 }
444
445 #[actix_web::test]
448 async fn missing_signature_header_is_bad_request() {
449 let app = github_app!();
450 let req = aw_test::TestRequest::post()
451 .set_payload(Bytes::from_static(GITHUB_BODY))
452 .to_request();
453 let res = aw_test::call_service(&app, req).await;
454 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
455 }
456
457 #[actix_web::test]
458 async fn conflicting_duplicate_signature_headers_are_rejected() {
459 let app = github_app!();
462 let req = aw_test::TestRequest::post()
463 .append_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
464 .append_header((
465 "x-hub-signature-256",
466 "sha256=0000000000000000000000000000000000000000000000000000000000000000",
467 ))
468 .set_payload(Bytes::from_static(GITHUB_BODY))
469 .to_request();
470 let res = aw_test::call_service(&app, req).await;
471 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
472 }
473
474 #[actix_web::test]
475 async fn identical_duplicate_signature_headers_still_verify() {
476 let app = github_app!();
477 let req = aw_test::TestRequest::post()
478 .append_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
479 .append_header(("x-hub-signature-256", GITHUB_SIGNATURE))
480 .set_payload(Bytes::from_static(GITHUB_BODY))
481 .to_request();
482 let res = aw_test::call_service(&app, req).await;
483 assert_eq!(res.status(), StatusCode::OK);
484 }
485
486 #[actix_web::test]
487 async fn conflicting_duplicate_timestamp_header_is_rejected_for_slack() {
488 let app = aw_test::init_service(
491 App::new()
492 .app_data(WebhookConfig::new(
493 Provider::Slack,
494 Secret::new(SLACK_SECRET),
495 ))
496 .route("/", web::post().to(echo_len_slack)),
497 )
498 .await;
499 let req = aw_test::TestRequest::post()
500 .insert_header(("X-Slack-Signature", format!("v0={SLACK_SIGNATURE}")))
501 .append_header(("X-Slack-Request-Timestamp", SLACK_TIMESTAMP.to_string()))
502 .append_header(("x-slack-request-timestamp", "1700000001"))
503 .set_payload(Bytes::from_static(SLACK_BODY))
504 .to_request();
505 let res = aw_test::call_service(&app, req).await;
506 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
507 }
508
509 #[actix_web::test]
512 async fn stale_timestamp_is_unauthorized_through_adapter() {
513 let late = epoch(SLACK_TIMESTAMP + 600);
515
516 let app = aw_test::init_service(
517 App::new()
518 .app_data(WebhookConfig::with_options(
519 Provider::Slack,
520 Secret::new(SLACK_SECRET),
521 crate::VerifyOptions {
522 clock: Some(Arc::new(FixedClock(late))),
523 ..crate::VerifyOptions::default()
524 },
525 ))
526 .route("/", web::post().to(echo_len_slack)),
527 )
528 .await;
529
530 let req = aw_test::TestRequest::post()
531 .insert_header(("X-Slack-Signature", format!("v0={SLACK_SIGNATURE}")))
532 .insert_header(("X-Slack-Request-Timestamp", SLACK_TIMESTAMP.to_string()))
533 .set_payload(Bytes::from_static(SLACK_BODY))
534 .to_request();
535 let res = aw_test::call_service(&app, req).await;
536 assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
537 }
538
539 #[actix_web::test]
542 async fn custom_scheme_headers_are_dup_checked_too() {
543 const DIGEST: &str = "11316937114e6970aa59bd5326a6f38dd525f4ade64670e402bff41e2f7c4071";
546 let scheme = crate::CustomScheme {
547 hash: crate::HashAlg::Sha256,
548 signature_header: "X-My-Sig",
549 timestamp_header: None,
550 encoding: crate::Encoding::Hex,
551 prefix: Some("sha256="),
552 signed_string: |_headers, body| body.to_vec(),
553 };
554
555 let ambiguous_app = aw_test::init_service(
558 App::new()
559 .app_data(WebhookConfig::new(
560 Provider::Custom(scheme),
561 Secret::new("k"),
562 ))
563 .route("/", web::post().to(echo_len_slack)),
564 )
565 .await;
566 let req = aw_test::TestRequest::post()
567 .append_header(("X-My-Sig", format!("sha256={DIGEST}")))
568 .append_header(("x-my-sig", "sha256=00"))
569 .set_payload(Bytes::from_static(GITHUB_BODY))
570 .to_request();
571 let res = aw_test::call_service(&ambiguous_app, req).await;
572 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
573
574 let good_app = aw_test::init_service(
576 App::new()
577 .app_data(WebhookConfig::new(
578 Provider::Custom(scheme),
579 Secret::new("k"),
580 ))
581 .route("/", web::post().to(echo_len)),
582 )
583 .await;
584 let req = aw_test::TestRequest::post()
585 .insert_header(("X-My-Sig", format!("sha256={DIGEST}")))
586 .set_payload(Bytes::from_static(GITHUB_BODY))
587 .to_request();
588 let res = aw_test::call_service(&good_app, req).await;
589 assert_eq!(res.status(), StatusCode::OK);
590 }
591
592 #[cfg(not(feature = "paypal"))]
595 #[actix_web::test]
596 async fn unsupported_provider_maps_to_internal_server_error() {
597 let app = aw_test::init_service(
598 App::new()
599 .app_data(WebhookConfig::new(Provider::PayPal, Secret::new("unused")))
600 .route("/", web::post().to(echo_len_slack)),
601 )
602 .await;
603 let req = aw_test::TestRequest::post()
604 .set_payload(Bytes::from_static(b"{}"))
605 .to_request();
606 let res = aw_test::call_service(&app, req).await;
607 assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
608 }
609
610 #[cfg(feature = "paypal")]
611 #[actix_web::test]
612 async fn paypal_verifies_through_the_extractor() {
613 let cert = include_bytes!("../tests/data/paypal_test_cert.pem");
614 let config = WebhookConfig::with_options(
618 Provider::PayPal,
619 Secret::new("unused"),
620 clocked_at(1_715_836_763, None)
621 .with_webhook_id("0NH55953DH663215D")
622 .with_verifying_material(VerifyingKeyMaterial::X509Certificate(cert.to_vec())),
623 );
624 let app = aw_test::init_service(
625 App::new()
626 .app_data(config)
627 .route("/", web::post().to(echo_len)),
628 )
629 .await;
630 let body = include_bytes!("../tests/data/paypal_docs_body.json");
631 let req = aw_test::TestRequest::post()
632 .insert_header(("PayPal-Transmission-Id", "db49fb10-1343-11ef-ac58-e32457403f67"))
633 .insert_header(("PayPal-Transmission-Time", "2024-05-16T05:19:23Z"))
634 .insert_header((
635 "PayPal-Transmission-Sig",
636 "aGYe/s6lwrASh2zyTRIAz8Edo705ezMKekirejT08ev3VXdWAkq4JWADiNPUGelx5qrEKxC7mPIHmAwQ5hOT6unhY9n33M/DbXTKGsuITPdXRA7qYVmc2wsIp68BpzB6pC6+5vt/YLQvflsrwrutGa0KyZc5FinuYNN8pTNomv4uiygasWqfnDyKViKQPNZecowag6tY/9pj7+bgBu/joBpYUq0+cQxfGqNnlvywBJ7HCOf4edeTIvM/c1CvvAHGtNTU54kLjWGue640twn6iXPL8tnaABZ8Fr9m0z87v8oY0vBobERV0Yu8thUToKhvQEFF26Rckqy07VVddg1CmA==",
637 ))
638 .insert_header(("PayPal-Cert-Url", "https://example.invalid/cert-url"))
639 .insert_header(("PayPal-Auth-Algo", "SHA256withRSA"))
640 .set_payload(Bytes::from_static(body))
641 .to_request();
642 let res = aw_test::call_service(&app, req).await;
643 assert_eq!(res.status(), StatusCode::OK);
644 }
645
646 #[actix_web::test]
647 async fn missing_config_fails_closed_with_internal_server_error() {
648 let app = aw_test::init_service(App::new().route("/", web::post().to(echo_len))).await;
649 let req = aw_test::TestRequest::post()
650 .insert_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
651 .set_payload(Bytes::from_static(GITHUB_BODY))
652 .to_request();
653 let res = aw_test::call_service(&app, req).await;
654 assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
655 }
656
657 #[test]
660 fn identical_opaque_duplicate_values_are_not_ambiguous_but_fail_verification() {
661 let name = HeaderName::from_static("x-hub-signature-256");
664 let mut headers = ActixHeaderMap::new();
665 let value = http::header::HeaderValue::from_bytes(&[0xFF])
666 .unwrap_or_else(|_| unreachable!("permitted"));
667 headers.append(name.clone(), value.clone());
668 headers.append(name, value);
669 assert!(conflicting_signature_header(&headers, &["X-Hub-Signature-256"]).is_none());
670 }
671
672 #[test]
673 fn unparseable_header_name_fails_closed_as_ambiguous() {
674 let headers = ActixHeaderMap::new();
679 assert_eq!(
680 conflicting_signature_header(&headers, &["x-hub-signature-256 invalid"]),
681 Some("x-hub-signature-256 invalid")
682 );
683 }
684
685 #[test]
686 fn bridge_lookup_is_ascii_case_insensitive_and_fail_closed() {
687 let mut headers = ActixHeaderMap::new();
688 headers.insert(
689 HeaderName::from_static("x-hub-signature-256"),
690 http::header::HeaderValue::from_static(GITHUB_SIGNATURE),
691 );
692 assert_eq!(
693 HeaderMap::get(&headers, "x-hub-signature-256"),
694 Some(GITHUB_SIGNATURE)
695 );
696 assert_eq!(
697 HeaderMap::get(&headers, "X-HUB-SIGNATURE-256"),
698 Some(GITHUB_SIGNATURE)
699 );
700 assert_eq!(HeaderMap::get(&headers, "bad name\n"), None);
701 let mut opaque = ActixHeaderMap::new();
703 opaque.insert(
704 HeaderName::from_static("x-webhook-sig"),
705 http::header::HeaderValue::from_bytes(&[0xFF])
706 .unwrap_or_else(|_| unreachable!("permitted")),
707 );
708 assert_eq!(HeaderMap::get(&opaque, "X-Webhook-Sig"), None);
709 }
710
711 #[test]
712 fn bridge_verifies_github_delivery_end_to_end() {
713 let mut headers = ActixHeaderMap::new();
714 headers.insert(
715 HeaderName::from_static("x-hub-signature-256"),
716 http::header::HeaderValue::from_static(GITHUB_SIGNATURE),
717 );
718 let result = crate::verify(
719 Provider::GitHub,
720 &headers,
721 GITHUB_BODY,
722 &Secret::new(GITHUB_SECRET),
723 Default::default(),
724 );
725 assert_eq!(result, Ok(()));
726
727 let result = crate::verify(
728 Provider::GitHub,
729 &headers,
730 b"Hello, World?",
731 &Secret::new(GITHUB_SECRET),
732 Default::default(),
733 );
734 assert_eq!(result, Err(VerifyError::SignatureMismatch));
735 }
736
737 #[test]
738 fn debug_output_never_contains_secrets_or_bodies() {
739 let config = WebhookConfig::with_options(
740 Provider::GitHub,
741 Secret::new("super-secret-hmac-key"),
742 crate::VerifyOptions::default().with_request_url("https://internal.example/hook"),
743 );
744 let debug = format!("{config:?}");
745 assert!(!debug.contains("super-secret-hmac-key"));
746 assert!(!debug.contains("internal.example"));
747
748 let body = VerifiedBody(Bytes::from_static(b"raw-secret-payload-bytes"));
749 let debug = format!("{body:?}");
750 assert!(!debug.contains("raw-secret-payload-bytes"));
751 assert!(debug.contains("len: 24"));
752 }
753
754 #[test]
755 fn rejection_display_never_contains_secret_material() {
756 let e = WebhookVerificationError(Rejection::Verify(VerifyError::MissingHeader {
757 header: "X-Hub-Signature-256",
758 }));
759 assert_eq!(
760 e.to_string(),
761 "webhook verification failed: missing header `X-Hub-Signature-256`"
762 );
763 let e = WebhookVerificationError(Rejection::BodyRead);
764 assert_eq!(e.to_string(), "webhook body could not be read");
765 assert_eq!(e.status_code(), StatusCode::BAD_REQUEST);
766 }
767}