use base64::{engine::general_purpose::STANDARD, Engine as _};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::{
fmt,
time::{SystemTime, UNIX_EPOCH},
};
const TOLERANCE_SECONDS: i64 = 5 * 60;
const SECRET_PREFIX: &str = "whsec_";
const HEADERS: [[&str; 2]; 3] = [
["webhook-id", "svix-id"],
["webhook-timestamp", "svix-timestamp"],
["webhook-signature", "svix-signature"],
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebhookError {
InvalidSecret,
MissingHeaders,
InvalidTimestamp,
TimestampTooOld,
TimestampTooNew,
NoMatchingSignature,
}
impl fmt::Display for WebhookError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InvalidSecret => "webhook secret is empty or not valid base64",
Self::MissingHeaders => "missing webhook signature headers",
Self::InvalidTimestamp => "invalid webhook timestamp header",
Self::TimestampTooOld => "webhook timestamp is too old",
Self::TimestampTooNew => "webhook timestamp is too far in the future",
Self::NoMatchingSignature => "no matching webhook signature",
})
}
}
impl std::error::Error for WebhookError {}
pub struct Webhook {
key: Vec<u8>,
}
impl Webhook {
pub fn new(secret: &str) -> Result<Self, WebhookError> {
let encoded = secret.strip_prefix(SECRET_PREFIX).unwrap_or(secret);
let key = STANDARD
.decode(encoded)
.map_err(|_| WebhookError::InvalidSecret)?;
Self::from_bytes(key)
}
pub fn from_bytes(key: Vec<u8>) -> Result<Self, WebhookError> {
if key.is_empty() {
return Err(WebhookError::InvalidSecret);
}
Ok(Self { key })
}
pub fn verify(&self, payload: &[u8], headers: &http::HeaderMap) -> Result<(), WebhookError> {
let [id, timestamp, signatures] = HEADERS.map(|names| header(headers, names));
if id.is_empty() || timestamp.is_empty() || signatures.is_empty() {
return Err(WebhookError::MissingHeaders);
}
let seconds: i64 = timestamp
.parse()
.map_err(|_| WebhookError::InvalidTimestamp)?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX));
if seconds < now - TOLERANCE_SECONDS {
return Err(WebhookError::TimestampTooOld);
}
if seconds > now + TOLERANCE_SECONDS {
return Err(WebhookError::TimestampTooNew);
}
let matches = signatures
.split_whitespace()
.filter_map(|part| part.strip_prefix("v1,"))
.filter_map(|signature| STANDARD.decode(signature).ok())
.any(|signature| {
self.mac(&id, seconds, payload)
.verify_slice(&signature)
.is_ok()
});
matches
.then_some(())
.ok_or(WebhookError::NoMatchingSignature)
}
#[must_use]
pub fn sign(&self, msg_id: &str, timestamp: i64, payload: &[u8]) -> String {
let signature = self.mac(msg_id, timestamp, payload).finalize().into_bytes();
format!("v1,{}", STANDARD.encode(signature))
}
fn mac(&self, msg_id: &str, timestamp: i64, payload: &[u8]) -> Hmac<Sha256> {
let mut mac = Hmac::<Sha256>::new_from_slice(&self.key).expect("HMAC accepts any key size");
mac.update(format!("{msg_id}.{timestamp}.").as_bytes());
mac.update(payload);
mac
}
}
fn header(headers: &http::HeaderMap, names: [&str; 2]) -> String {
names
.iter()
.map(|name| {
headers
.get_all(*name)
.iter()
.filter_map(|value| value.to_str().ok())
.collect::<Vec<_>>()
.join(" ")
})
.find(|value| !value.is_empty())
.unwrap_or_default()
}