mod notification;
mod signature;
use secrecy::SecretString;
pub use notification::{
CustomerPaymentProfilePayload, CustomerProfilePayload, EventType, FraudFilter, Notification,
ParseError, Payload, PaymentProfileSummary, SubscriptionPayload, SubscriptionProfile,
TransactionPayload, parse,
};
pub use signature::{SIGNATURE_HEADER, SignatureError, verify_signature};
pub fn verify_then_parse(
signature_key: &SecretString,
signature_header: &str,
body: &[u8],
) -> Result<Notification, WebhookError> {
verify_signature(signature_key, signature_header, body)?;
Ok(parse(body)?)
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum WebhookError {
#[error(transparent)]
Signature(#[from] SignatureError),
#[error(transparent)]
Parse(#[from] ParseError),
}
#[cfg(test)]
mod tests {
use hmac::{Hmac, KeyInit, Mac};
use secrecy::ExposeSecret;
use sha2::Sha512;
use super::*;
const BODY: &[u8] = br#"{"notificationId":"n-1","eventType":"net.authorize.payment.void.created","eventDate":"2026-11-02T10:00:00Z","webhookId":"w-1","payload":{"entityName":"transaction","id":"60020981676","responseCode":1}}"#;
fn key() -> SecretString {
SecretString::from("signature-key")
}
fn sign(body: &[u8]) -> String {
let mut mac = Hmac::<Sha512>::new_from_slice(key().expose_secret().as_bytes()).unwrap();
mac.update(body);
let digest = mac.finalize().into_bytes();
let hex: String = digest.iter().map(|byte| format!("{byte:02X}")).collect();
format!("sha512={hex}")
}
#[test]
fn parses_a_verified_notification() {
let notification = verify_then_parse(&key(), &sign(BODY), BODY).unwrap();
assert_eq!(notification.event_type, EventType::VoidCreated);
}
#[test]
fn rejects_a_bad_signature_before_parsing() {
let other = sign(b"another body");
assert!(matches!(
verify_then_parse(&key(), &other, BODY),
Err(WebhookError::Signature(SignatureError::Mismatch))
));
}
#[test]
fn reports_a_signed_body_that_is_not_a_notification() {
let body = br#"{"hello":"world"}"#;
assert!(matches!(
verify_then_parse(&key(), &sign(body), body),
Err(WebhookError::Parse(_))
));
}
}