use std::{
fmt,
future::{Future, ready},
pin::Pin,
sync::Arc,
};
use actix_web::{
FromRequest, HttpRequest, ResponseError,
dev::Payload,
http::{
StatusCode,
header::{HeaderMap as ActixHeaderMap, HeaderName},
},
web::Bytes,
};
use crate::core::adapter_utils::rejection_status;
use crate::{
HeaderMap, Provider, Secret, VerifyError, VerifyOptions, providers::signature_header_names,
};
#[must_use]
#[derive(Clone)]
pub struct WebhookConfig {
provider: Provider,
secret: Arc<Secret>,
options: Arc<VerifyOptions>,
}
impl fmt::Debug for WebhookConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WebhookConfig")
.field("provider", &self.provider)
.field("secret", &self.secret)
.field("options", &self.options)
.finish()
}
}
impl WebhookConfig {
pub fn new(provider: Provider, secret: Secret) -> Self {
Self::with_options(provider, secret, VerifyOptions::default())
}
pub fn with_options(provider: Provider, secret: Secret, options: VerifyOptions) -> Self {
Self {
provider,
secret: Arc::new(secret),
options: Arc::new(options),
}
}
}
#[must_use]
pub struct VerifiedBody(Bytes);
impl VerifiedBody {
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
pub fn into_inner(self) -> Bytes {
self.0
}
}
impl fmt::Debug for VerifiedBody {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VerifiedBody")
.field("len", &self.0.len())
.finish()
}
}
impl std::ops::Deref for VerifiedBody {
type Target = [u8];
fn deref(&self) -> &[u8] {
self.as_bytes()
}
}
#[derive(Debug)]
enum Rejection {
Verify(VerifyError),
BodyRead,
}
#[must_use]
#[derive(Debug)]
pub struct WebhookVerificationError(Rejection);
impl fmt::Display for WebhookVerificationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
Rejection::Verify(error) => write!(f, "webhook verification failed: {error}"),
Rejection::BodyRead => f.write_str("webhook body could not be read"),
}
}
}
impl std::error::Error for WebhookVerificationError {}
impl ResponseError for WebhookVerificationError {
fn status_code(&self) -> StatusCode {
match &self.0 {
Rejection::BodyRead => StatusCode::BAD_REQUEST,
Rejection::Verify(error) => StatusCode::from_u16(rejection_status(error))
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
}
}
}
fn conflicting_signature_header(
headers: &ActixHeaderMap,
names: &[&'static str],
) -> Option<&'static str> {
names.iter().copied().find(|name| {
let Ok(key) = HeaderName::from_bytes(name.as_bytes()) else {
return true;
};
let mut values = headers.get_all(&key);
let Some(first) = values.next() else {
return false;
};
values.any(|value| value != first)
})
}
type ExtractFuture = Pin<Box<dyn Future<Output = Result<VerifiedBody, WebhookVerificationError>>>>;
impl FromRequest for VerifiedBody {
type Error = WebhookVerificationError;
type Future = ExtractFuture;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let Some(config) = req.app_data::<WebhookConfig>() else {
return Box::pin(ready(Err(WebhookVerificationError(Rejection::Verify(
VerifyError::MissingContext {
reason: "no WebhookConfig registered via app_data",
},
)))));
};
let names = signature_header_names(&config.provider);
if let Some(header) = conflicting_signature_header(req.headers(), &names) {
return Box::pin(ready(Err(WebhookVerificationError(Rejection::Verify(
VerifyError::MalformedHeader {
header,
reason: "header present multiple times with different values",
},
)))));
}
let config = config.clone();
let mut payload = payload.take();
let req = req.clone();
Box::pin(async move {
let raw_body = match Bytes::from_request(&req, &mut payload).await {
Ok(bytes) => bytes,
Err(_) => return Err(WebhookVerificationError(Rejection::BodyRead)),
};
match crate::verify(
config.provider,
req.headers(),
raw_body.as_ref(),
&config.secret,
(*config.options).clone(),
) {
Ok(()) => Ok(VerifiedBody(raw_body)),
Err(error) => Err(WebhookVerificationError(Rejection::Verify(error))),
}
})
}
}
impl HeaderMap for ActixHeaderMap {
fn get(&self, name: &str) -> Option<&str> {
let key = HeaderName::from_bytes(name.as_bytes()).ok()?;
let value = ActixHeaderMap::get(self, &key)?;
value.to_str().ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "paypal")]
use crate::VerifyingKeyMaterial;
use crate::test_helpers::{FixedClock, clocked_at, epoch};
use actix_web::{App, HttpResponse, http, test as aw_test, web};
const GITHUB_SECRET: &str = "It's a Secret to Everybody";
const GITHUB_BODY: &[u8] = b"Hello, World!";
const GITHUB_SIGNATURE: &str =
"sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
const SLACK_SECRET: &str = "8f742231b10e8888abcd99yyyzzz85a5";
const SLACK_TIMESTAMP: u64 = 1_531_420_618;
const SLACK_BODY: &[u8] =
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";
const SLACK_SIGNATURE: &str =
"a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503";
async fn echo_len(body: VerifiedBody) -> HttpResponse {
HttpResponse::Ok().body(body.len().to_string())
}
async fn echo_len_slack(_body: VerifiedBody) -> HttpResponse {
unreachable!("only called where extraction should succeed")
}
macro_rules! github_app {
() => {
aw_test::init_service(
App::new()
.app_data(WebhookConfig::new(
Provider::GitHub,
Secret::new(GITHUB_SECRET),
))
.route("/", web::post().to(echo_len)),
)
.await
};
}
fn github_request(body: &'static [u8]) -> aw_test::TestRequest {
aw_test::TestRequest::post()
.insert_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
.set_payload(Bytes::from_static(body))
}
#[actix_web::test]
async fn valid_signature_reaches_handler_with_exact_bytes() {
let app = github_app!();
let res = aw_test::call_service(&app, github_request(GITHUB_BODY).to_request()).await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(aw_test::read_body(res).await, Bytes::from_static(b"13"));
}
#[actix_web::test]
async fn empty_and_unicode_bodies_round_trip_byte_exactly() {
const EMPTY_SIG: &str =
"sha256=66a0c074deaa0f489ead6537e0d32f9a344b90bbeda705b6ed45ecd3b413fb40";
const UNICODE_BODY: &[u8] = "héllo, 🦀 world!".as_bytes();
const UNICODE_SIG: &str =
"sha256=815772f88bf8950c7457b57856f4b33ca9d07e7ef7a50646b067b4a613f735c4";
for (body, signature) in [
(&b""[..], EMPTY_SIG),
(UNICODE_BODY, UNICODE_SIG),
(GITHUB_BODY, GITHUB_SIGNATURE),
] {
let expected_len = body.len().to_string();
let app = github_app!();
let req = aw_test::TestRequest::post()
.insert_header(("X-Hub-Signature-256", signature))
.set_payload(Bytes::copy_from_slice(body))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(aw_test::read_body(res).await, Bytes::from(expected_len));
}
}
#[actix_web::test]
async fn tampered_body_is_unauthorized_and_never_reaches_handler() {
let app = github_app!();
let res = aw_test::call_service(&app, github_request(b"Hello, World?").to_request()).await;
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[actix_web::test]
async fn missing_signature_header_is_bad_request() {
let app = github_app!();
let req = aw_test::TestRequest::post()
.set_payload(Bytes::from_static(GITHUB_BODY))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
#[actix_web::test]
async fn conflicting_duplicate_signature_headers_are_rejected() {
let app = github_app!();
let req = aw_test::TestRequest::post()
.append_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
.append_header((
"x-hub-signature-256",
"sha256=0000000000000000000000000000000000000000000000000000000000000000",
))
.set_payload(Bytes::from_static(GITHUB_BODY))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
#[actix_web::test]
async fn identical_duplicate_signature_headers_still_verify() {
let app = github_app!();
let req = aw_test::TestRequest::post()
.append_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
.append_header(("x-hub-signature-256", GITHUB_SIGNATURE))
.set_payload(Bytes::from_static(GITHUB_BODY))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
}
#[actix_web::test]
async fn conflicting_duplicate_timestamp_header_is_rejected_for_slack() {
let app = aw_test::init_service(
App::new()
.app_data(WebhookConfig::new(
Provider::Slack,
Secret::new(SLACK_SECRET),
))
.route("/", web::post().to(echo_len_slack)),
)
.await;
let req = aw_test::TestRequest::post()
.insert_header(("X-Slack-Signature", format!("v0={SLACK_SIGNATURE}")))
.append_header(("X-Slack-Request-Timestamp", SLACK_TIMESTAMP.to_string()))
.append_header(("x-slack-request-timestamp", "1700000001"))
.set_payload(Bytes::from_static(SLACK_BODY))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
#[actix_web::test]
async fn stale_timestamp_is_unauthorized_through_adapter() {
let late = epoch(SLACK_TIMESTAMP + 600);
let app = aw_test::init_service(
App::new()
.app_data(WebhookConfig::with_options(
Provider::Slack,
Secret::new(SLACK_SECRET),
crate::VerifyOptions {
clock: Some(Arc::new(FixedClock(late))),
..crate::VerifyOptions::default()
},
))
.route("/", web::post().to(echo_len_slack)),
)
.await;
let req = aw_test::TestRequest::post()
.insert_header(("X-Slack-Signature", format!("v0={SLACK_SIGNATURE}")))
.insert_header(("X-Slack-Request-Timestamp", SLACK_TIMESTAMP.to_string()))
.set_payload(Bytes::from_static(SLACK_BODY))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[actix_web::test]
async fn custom_scheme_headers_are_dup_checked_too() {
const DIGEST: &str = "11316937114e6970aa59bd5326a6f38dd525f4ade64670e402bff41e2f7c4071";
let scheme = crate::CustomScheme {
hash: crate::HashAlg::Sha256,
signature_header: "X-My-Sig",
timestamp_header: None,
encoding: crate::Encoding::Hex,
prefix: Some("sha256="),
signed_string: |_headers, body| body.to_vec(),
};
let ambiguous_app = aw_test::init_service(
App::new()
.app_data(WebhookConfig::new(
Provider::Custom(scheme),
Secret::new("k"),
))
.route("/", web::post().to(echo_len_slack)),
)
.await;
let req = aw_test::TestRequest::post()
.append_header(("X-My-Sig", format!("sha256={DIGEST}")))
.append_header(("x-my-sig", "sha256=00"))
.set_payload(Bytes::from_static(GITHUB_BODY))
.to_request();
let res = aw_test::call_service(&ambiguous_app, req).await;
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
let good_app = aw_test::init_service(
App::new()
.app_data(WebhookConfig::new(
Provider::Custom(scheme),
Secret::new("k"),
))
.route("/", web::post().to(echo_len)),
)
.await;
let req = aw_test::TestRequest::post()
.insert_header(("X-My-Sig", format!("sha256={DIGEST}")))
.set_payload(Bytes::from_static(GITHUB_BODY))
.to_request();
let res = aw_test::call_service(&good_app, req).await;
assert_eq!(res.status(), StatusCode::OK);
}
#[cfg(not(feature = "paypal"))]
#[actix_web::test]
async fn unsupported_provider_maps_to_internal_server_error() {
let app = aw_test::init_service(
App::new()
.app_data(WebhookConfig::new(Provider::PayPal, Secret::new("unused")))
.route("/", web::post().to(echo_len_slack)),
)
.await;
let req = aw_test::TestRequest::post()
.set_payload(Bytes::from_static(b"{}"))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[cfg(feature = "paypal")]
#[actix_web::test]
async fn paypal_verifies_through_the_extractor() {
let cert = include_bytes!("../tests/data/paypal_test_cert.pem");
let config = WebhookConfig::with_options(
Provider::PayPal,
Secret::new("unused"),
clocked_at(1_715_836_763, None)
.with_webhook_id("0NH55953DH663215D")
.with_verifying_material(VerifyingKeyMaterial::X509Certificate(cert.to_vec())),
);
let app = aw_test::init_service(
App::new()
.app_data(config)
.route("/", web::post().to(echo_len)),
)
.await;
let body = include_bytes!("../tests/data/paypal_docs_body.json");
let req = aw_test::TestRequest::post()
.insert_header(("PayPal-Transmission-Id", "db49fb10-1343-11ef-ac58-e32457403f67"))
.insert_header(("PayPal-Transmission-Time", "2024-05-16T05:19:23Z"))
.insert_header((
"PayPal-Transmission-Sig",
"aGYe/s6lwrASh2zyTRIAz8Edo705ezMKekirejT08ev3VXdWAkq4JWADiNPUGelx5qrEKxC7mPIHmAwQ5hOT6unhY9n33M/DbXTKGsuITPdXRA7qYVmc2wsIp68BpzB6pC6+5vt/YLQvflsrwrutGa0KyZc5FinuYNN8pTNomv4uiygasWqfnDyKViKQPNZecowag6tY/9pj7+bgBu/joBpYUq0+cQxfGqNnlvywBJ7HCOf4edeTIvM/c1CvvAHGtNTU54kLjWGue640twn6iXPL8tnaABZ8Fr9m0z87v8oY0vBobERV0Yu8thUToKhvQEFF26Rckqy07VVddg1CmA==",
))
.insert_header(("PayPal-Cert-Url", "https://example.invalid/cert-url"))
.insert_header(("PayPal-Auth-Algo", "SHA256withRSA"))
.set_payload(Bytes::from_static(body))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::OK);
}
#[actix_web::test]
async fn missing_config_fails_closed_with_internal_server_error() {
let app = aw_test::init_service(App::new().route("/", web::post().to(echo_len))).await;
let req = aw_test::TestRequest::post()
.insert_header(("X-Hub-Signature-256", GITHUB_SIGNATURE))
.set_payload(Bytes::from_static(GITHUB_BODY))
.to_request();
let res = aw_test::call_service(&app, req).await;
assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn identical_opaque_duplicate_values_are_not_ambiguous_but_fail_verification() {
let name = HeaderName::from_static("x-hub-signature-256");
let mut headers = ActixHeaderMap::new();
let value = http::header::HeaderValue::from_bytes(&[0xFF])
.unwrap_or_else(|_| unreachable!("permitted"));
headers.append(name.clone(), value.clone());
headers.append(name, value);
assert!(conflicting_signature_header(&headers, &["X-Hub-Signature-256"]).is_none());
}
#[test]
fn unparseable_header_name_fails_closed_as_ambiguous() {
let headers = ActixHeaderMap::new();
assert_eq!(
conflicting_signature_header(&headers, &["x-hub-signature-256 invalid"]),
Some("x-hub-signature-256 invalid")
);
}
#[test]
fn bridge_lookup_is_ascii_case_insensitive_and_fail_closed() {
let mut headers = ActixHeaderMap::new();
headers.insert(
HeaderName::from_static("x-hub-signature-256"),
http::header::HeaderValue::from_static(GITHUB_SIGNATURE),
);
assert_eq!(
HeaderMap::get(&headers, "x-hub-signature-256"),
Some(GITHUB_SIGNATURE)
);
assert_eq!(
HeaderMap::get(&headers, "X-HUB-SIGNATURE-256"),
Some(GITHUB_SIGNATURE)
);
assert_eq!(HeaderMap::get(&headers, "bad name\n"), None);
let mut opaque = ActixHeaderMap::new();
opaque.insert(
HeaderName::from_static("x-webhook-sig"),
http::header::HeaderValue::from_bytes(&[0xFF])
.unwrap_or_else(|_| unreachable!("permitted")),
);
assert_eq!(HeaderMap::get(&opaque, "X-Webhook-Sig"), None);
}
#[test]
fn bridge_verifies_github_delivery_end_to_end() {
let mut headers = ActixHeaderMap::new();
headers.insert(
HeaderName::from_static("x-hub-signature-256"),
http::header::HeaderValue::from_static(GITHUB_SIGNATURE),
);
let result = crate::verify(
Provider::GitHub,
&headers,
GITHUB_BODY,
&Secret::new(GITHUB_SECRET),
Default::default(),
);
assert_eq!(result, Ok(()));
let result = crate::verify(
Provider::GitHub,
&headers,
b"Hello, World?",
&Secret::new(GITHUB_SECRET),
Default::default(),
);
assert_eq!(result, Err(VerifyError::SignatureMismatch));
}
#[test]
fn debug_output_never_contains_secrets_or_bodies() {
let config = WebhookConfig::with_options(
Provider::GitHub,
Secret::new("super-secret-hmac-key"),
crate::VerifyOptions::default().with_request_url("https://internal.example/hook"),
);
let debug = format!("{config:?}");
assert!(!debug.contains("super-secret-hmac-key"));
assert!(!debug.contains("internal.example"));
let body = VerifiedBody(Bytes::from_static(b"raw-secret-payload-bytes"));
let debug = format!("{body:?}");
assert!(!debug.contains("raw-secret-payload-bytes"));
assert!(debug.contains("len: 24"));
}
#[test]
fn rejection_display_never_contains_secret_material() {
let e = WebhookVerificationError(Rejection::Verify(VerifyError::MissingHeader {
header: "X-Hub-Signature-256",
}));
assert_eq!(
e.to_string(),
"webhook verification failed: missing header `X-Hub-Signature-256`"
);
let e = WebhookVerificationError(Rejection::BodyRead);
assert_eq!(e.to_string(), "webhook body could not be read");
assert_eq!(e.status_code(), StatusCode::BAD_REQUEST);
}
}