use crate::error::ErrorCode;
use crate::models::WebhookEventPayload;
use crate::{Error, Result};
use hmac::{Hmac, Mac};
use sha2::Sha256;
pub const WEBHOOK_SIGNATURE_HEADER: &str = "x-calmlens-signature";
pub const WEBHOOK_TIMESTAMP_HEADER: &str = "x-calmlens-timestamp";
pub const WEBHOOK_DELIVERY_HEADER: &str = "x-calmlens-delivery";
pub const WEBHOOK_SIGNATURE_TOLERANCE_SECONDS: u64 = 300;
fn webhook_mac(body: &[u8], timestamp: &str, secret: &str) -> Hmac<Sha256> {
let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
.expect("HMAC supports arbitrary key lengths");
mac.update(timestamp.as_bytes());
mac.update(b".");
mac.update(body);
mac
}
pub fn create_webhook_signature_header(
body: impl AsRef<[u8]>,
timestamp: &str,
secret: &str,
) -> String {
let digest = webhook_mac(body.as_ref(), timestamp, secret)
.finalize()
.into_bytes();
let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
format!("v1={hex}")
}
pub fn verify_webhook_signature(
body: impl AsRef<[u8]>,
signature: &str,
timestamp: &str,
secret: &str,
now: u64,
tolerance: u64,
) -> bool {
let stamp = timestamp.trim();
if secret.is_empty()
|| signature.is_empty()
|| stamp.is_empty()
|| !stamp.bytes().all(|v| v.is_ascii_digit())
{
return false;
}
let Ok(time) = stamp.parse::<u64>() else {
return false;
};
if now.abs_diff(time) > tolerance {
return false;
}
let mut matched = false;
for candidate in signature
.split(',')
.map(str::trim)
.filter_map(|v| v.strip_prefix("v1="))
{
if candidate.len() != 64 {
continue;
}
let decoded = (0..64)
.step_by(2)
.map(|i| {
candidate
.get(i..i + 2)
.and_then(|v| u8::from_str_radix(v, 16).ok())
})
.collect::<Option<Vec<_>>>();
if let Some(bytes) = decoded {
matched |= webhook_mac(body.as_ref(), stamp, secret)
.verify_slice(&bytes)
.is_ok();
}
}
matched
}
pub fn parse_webhook_event(body: impl AsRef<[u8]>) -> Result<WebhookEventPayload> {
let payload: WebhookEventPayload = serde_json::from_slice(body.as_ref()).map_err(|cause| {
Error::new(
ErrorCode::InvalidWebhookPayload,
"Webhook body is not a delivery payload",
)
.with_source(cause)
})?;
if payload.id.is_empty() || payload.event_type.as_str().is_empty() {
return Err(Error::new(
ErrorCode::InvalidWebhookPayload,
"Webhook body needs id, type and data",
));
}
Ok(payload)
}
pub fn construct_webhook_event(
body: impl AsRef<[u8]>,
headers: &http::HeaderMap,
secret: &str,
) -> Result<WebhookEventPayload> {
let header = |name: &str| {
headers
.get(name)
.and_then(|value| value.to_str().ok())
.unwrap_or("")
};
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|elapsed| elapsed.as_secs())
.unwrap_or(0);
construct_webhook_event_at(
body,
header(WEBHOOK_SIGNATURE_HEADER),
header(WEBHOOK_TIMESTAMP_HEADER),
secret,
now,
WEBHOOK_SIGNATURE_TOLERANCE_SECONDS,
)
}
pub fn construct_webhook_event_at(
body: impl AsRef<[u8]>,
signature: &str,
timestamp: &str,
secret: &str,
now: u64,
tolerance: u64,
) -> Result<WebhookEventPayload> {
if !verify_webhook_signature(&body, signature, timestamp, secret, now, tolerance) {
return Err(Error::new(
ErrorCode::InvalidWebhookSignature,
"Webhook signature is missing, invalid or outside the tolerance",
));
}
parse_webhook_event(body)
}