use std::time::{SystemTime, UNIX_EPOCH};
use base64::alphabet;
use base64::engine::{general_purpose, DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
use base64::Engine as _;
use hmac::{Hmac, Mac};
use sha2::Sha256;
const SECRET_PREFIX: &str = "whsec_";
const SIGNATURE_VERSION: &str = "v1";
pub const DEFAULT_TOLERANCE_SECONDS: i64 = 300;
const LENIENT_BASE64: GeneralPurpose = GeneralPurpose::new(
&alphabet::STANDARD,
GeneralPurposeConfig::new()
.with_decode_allow_trailing_bits(true)
.with_decode_padding_mode(DecodePaddingMode::Indifferent),
);
#[derive(Clone, Debug)]
pub struct VerifyOptions {
pub tolerance_seconds: i64,
pub now: Option<i64>,
}
impl Default for VerifyOptions {
fn default() -> Self {
Self {
tolerance_seconds: DEFAULT_TOLERANCE_SECONDS,
now: None,
}
}
}
pub trait IntoUnixSeconds {
fn into_unix_seconds(self) -> Option<i64>;
}
impl IntoUnixSeconds for i64 {
fn into_unix_seconds(self) -> Option<i64> {
Some(self)
}
}
impl IntoUnixSeconds for u64 {
fn into_unix_seconds(self) -> Option<i64> {
i64::try_from(self).ok()
}
}
impl IntoUnixSeconds for f64 {
fn into_unix_seconds(self) -> Option<i64> {
self.is_finite().then(|| self.floor() as i64)
}
}
impl IntoUnixSeconds for &str {
fn into_unix_seconds(self) -> Option<i64> {
let trimmed = self.trim();
trimmed
.parse::<i64>()
.ok()
.or_else(|| trimmed.parse::<f64>().ok().and_then(f64::into_unix_seconds))
}
}
impl IntoUnixSeconds for &String {
fn into_unix_seconds(self) -> Option<i64> {
self.as_str().into_unix_seconds()
}
}
pub fn sign_webhook(
secret: &str,
msg_id: &str,
timestamp: impl IntoUnixSeconds,
payload: &str,
) -> String {
let seconds = timestamp.into_unix_seconds().unwrap_or(0);
format!(
"{SIGNATURE_VERSION},{}",
compute_signature(secret, msg_id, seconds, payload)
)
}
pub fn verify_webhook_signature(
secret: &str,
msg_id: &str,
timestamp: impl IntoUnixSeconds,
payload: &str,
signature_header: &str,
) -> bool {
verify_webhook_signature_with(
secret,
msg_id,
timestamp,
payload,
signature_header,
&VerifyOptions::default(),
)
}
pub fn verify_webhook_signature_with(
secret: &str,
msg_id: &str,
timestamp: impl IntoUnixSeconds,
payload: &str,
signature_header: &str,
options: &VerifyOptions,
) -> bool {
let Some(seconds) = timestamp.into_unix_seconds() else {
return false;
};
let now = options.now.unwrap_or_else(unix_now);
if now.saturating_sub(seconds).saturating_abs() > options.tolerance_seconds {
return false;
}
let signed_content = signed_content(msg_id, seconds, payload);
let key = decode_signing_key(secret);
signature_header.split(' ').any(|token| {
let Some((version, signature)) = token.split_once(',') else {
return false;
};
if version != SIGNATURE_VERSION {
return false;
}
let Ok(expected) = LENIENT_BASE64.decode(signature.trim()) else {
return false;
};
let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(&key) else {
return false;
};
mac.update(signed_content.as_bytes());
mac.verify_slice(&expected).is_ok()
})
}
fn signed_content(msg_id: &str, timestamp: i64, payload: &str) -> String {
format!("{msg_id}.{timestamp}.{payload}")
}
fn compute_signature(secret: &str, msg_id: &str, timestamp: i64, payload: &str) -> String {
let key = decode_signing_key(secret);
let mut mac = Hmac::<Sha256>::new_from_slice(&key).expect("HMAC accepts a key of any length");
mac.update(signed_content(msg_id, timestamp, payload).as_bytes());
general_purpose::STANDARD.encode(mac.finalize().into_bytes())
}
fn decode_signing_key(secret: &str) -> Vec<u8> {
let raw = secret.strip_prefix(SECRET_PREFIX).unwrap_or(secret).trim();
let normalized: String = raw
.chars()
.filter(|c| !c.is_whitespace() && *c != '=')
.map(|c| match c {
'-' => '+',
'_' => '/',
other => other,
})
.collect();
LENIENT_BASE64
.decode(&normalized)
.unwrap_or_else(|_| raw.as_bytes().to_vec())
}
fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs() as i64)
.unwrap_or(0)
}