use std::collections::HashMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use base64::Engine;
use hmac::{Hmac, Mac};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::Sha256;
use crate::client::{RequestOptions, Wellfriend};
use crate::error::{Error, Result};
use crate::generated::events::WebhookEventData;
use crate::Object;
pub const DEFAULT_TOLERANCE: Duration = Duration::from_secs(300);
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct WebhookEvent {
pub id: String,
#[serde(rename = "type")]
pub event_type: String,
#[serde(default)]
pub source: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subject: Option<String>,
#[serde(default)]
pub time: String,
#[serde(default)]
pub specversion: String,
#[serde(skip)]
pub data: WebhookEventData,
#[serde(rename = "data", default)]
pub raw_data: Value,
#[serde(default)]
pub wellfriend: WebhookEventMeta,
#[serde(flatten)]
pub extra: Object,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct WebhookEventMeta {
#[serde(default)]
pub occurred_at: String,
#[serde(default)]
pub resource_revision: Option<i64>,
#[serde(default)]
pub sequence: Option<String>,
#[serde(flatten)]
pub extra: Object,
}
impl WebhookEvent {
pub fn parse(payload: &[u8]) -> Result<Self> {
let mut event: WebhookEvent = serde_json::from_slice(payload).map_err(|error| {
Error::WebhookVerification(format!("the body is not an event: {error}"))
})?;
event.data = WebhookEventData::parse(&event.event_type, event.raw_data.clone());
Ok(event)
}
}
pub trait WebhookHeaders {
fn header(&self, name: &str) -> Option<String>;
}
impl WebhookHeaders for HeaderMap {
fn header(&self, name: &str) -> Option<String> {
self.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
}
}
impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for HashMap<K, V> {
fn header(&self, name: &str) -> Option<String> {
self.iter()
.find(|(key, _)| key.as_ref().eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_ref().to_owned())
}
}
impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for [(K, V)] {
fn header(&self, name: &str) -> Option<String> {
self.iter()
.find(|(key, _)| key.as_ref().eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_ref().to_owned())
}
}
impl<K: AsRef<str>, V: AsRef<str>> WebhookHeaders for Vec<(K, V)> {
fn header(&self, name: &str) -> Option<String> {
self.as_slice().header(name)
}
}
impl<T: WebhookHeaders + ?Sized> WebhookHeaders for &T {
fn header(&self, name: &str) -> Option<String> {
(**self).header(name)
}
}
pub fn verify_webhook(
payload: &[u8],
headers: impl WebhookHeaders,
secret: &str,
) -> Result<WebhookEvent> {
WebhookVerifier::new([secret]).verify(payload, headers)
}
#[derive(Clone)]
pub struct WebhookVerifier {
secrets: Vec<String>,
public_keys: Vec<String>,
tolerance: Duration,
now: Option<SystemTime>,
}
impl std::fmt::Debug for WebhookVerifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WebhookVerifier")
.field("secrets", &self.secrets.len())
.field("tolerance", &self.tolerance)
.finish()
}
}
impl WebhookVerifier {
pub fn new<I, S>(secrets: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
WebhookVerifier {
secrets: secrets.into_iter().map(Into::into).collect(),
public_keys: Vec::new(),
tolerance: DEFAULT_TOLERANCE,
now: None,
}
}
#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
pub fn ed25519<I, S>(public_keys: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
WebhookVerifier {
secrets: Vec::new(),
public_keys: public_keys.into_iter().map(Into::into).collect(),
tolerance: DEFAULT_TOLERANCE,
now: None,
}
}
pub fn tolerance(mut self, tolerance: Duration) -> Self {
self.tolerance = tolerance;
self
}
pub fn at(mut self, now: SystemTime) -> Self {
self.now = Some(now);
self
}
pub fn verify(&self, payload: &[u8], headers: impl WebhookHeaders) -> Result<WebhookEvent> {
let fail = |message: &str| Error::WebhookVerification(message.to_owned());
let id = headers
.header("webhook-id")
.filter(|id| !id.is_empty())
.ok_or_else(|| fail("the webhook-id header is missing"))?;
let timestamp = headers
.header("webhook-timestamp")
.ok_or_else(|| fail("the webhook-timestamp header is missing"))?;
let signatures = headers
.header("webhook-signature")
.ok_or_else(|| fail("the webhook-signature header is missing"))?;
let seconds: i64 = timestamp
.trim()
.parse()
.map_err(|_| fail("the webhook-timestamp header is not a Unix time"))?;
let now = self
.now
.unwrap_or_else(SystemTime::now)
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
if (now - seconds).unsigned_abs() > self.tolerance.as_secs() {
return Err(fail("the timestamp is outside the allowed tolerance"));
}
let keys: Vec<Vec<u8>> = self
.secrets
.iter()
.filter_map(|secret| decode_secret(secret))
.collect();
if keys.is_empty() && self.public_keys.is_empty() {
return Err(fail(
"no valid signing secret was given (expected whsec_...)",
));
}
let candidates: Vec<Vec<u8>> = signatures
.split_whitespace()
.filter_map(|entry| entry.split_once(','))
.filter(|(version, _)| *version == "v1")
.filter_map(|(_, encoded)| {
base64::engine::general_purpose::STANDARD
.decode(encoded)
.ok()
})
.collect();
let signed_prefix = format!("{id}.{seconds}.");
let matched = keys.iter().any(|key| {
let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(key) else {
return false;
};
mac.update(signed_prefix.as_bytes());
mac.update(payload);
let expected = mac.finalize().into_bytes();
candidates
.iter()
.any(|candidate| constant_time_eq(&expected, candidate))
});
if !matched && !self.ed25519_matches(&signatures, signed_prefix.as_bytes(), payload) {
return Err(fail("no signature matches"));
}
WebhookEvent::parse(payload)
}
}
impl WebhookVerifier {
#[cfg(feature = "ed25519")]
fn ed25519_matches(&self, signatures: &str, prefix: &[u8], payload: &[u8]) -> bool {
use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
let engine = base64::engine::general_purpose::STANDARD;
let keys: Vec<VerifyingKey> = self
.public_keys
.iter()
.filter_map(|key| engine.decode(key.trim()).ok())
.filter_map(|bytes| <[u8; 32]>::try_from(bytes.as_slice()).ok())
.filter_map(|bytes| VerifyingKey::from_bytes(&bytes).ok())
.collect();
let mut message = Vec::with_capacity(prefix.len() + payload.len());
message.extend_from_slice(prefix);
message.extend_from_slice(payload);
signatures
.split_whitespace()
.filter_map(|entry| entry.split_once(','))
.filter(|(version, _)| *version == "v1a")
.filter_map(|(_, encoded)| engine.decode(encoded).ok())
.filter_map(|bytes| Signature::from_slice(&bytes).ok())
.any(|signature| {
keys.iter()
.any(|key| key.verify(&message, &signature).is_ok())
})
}
#[cfg(not(feature = "ed25519"))]
fn ed25519_matches(&self, _signatures: &str, _prefix: &[u8], _payload: &[u8]) -> bool {
let _ = &self.public_keys;
false
}
}
fn decode_secret(secret: &str) -> Option<Vec<u8>> {
let trimmed = secret.trim();
let encoded: String = trimmed
.strip_prefix("whsec_")
.unwrap_or(trimmed)
.trim_end_matches('=')
.replace('-', "+")
.replace('_', "/");
let key = base64::engine::general_purpose::STANDARD_NO_PAD
.decode(encoded.as_bytes())
.ok()?;
(key.len() >= 16).then_some(key)
}
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
#[derive(Clone, Debug)]
pub struct Webhooks {
pub(crate) client: Wellfriend,
pub(crate) options: RequestOptions,
}
impl Webhooks {
pub fn with_options(mut self, options: RequestOptions) -> Self {
self.options = options;
self
}
pub fn verify(
&self,
payload: &[u8],
headers: impl WebhookHeaders,
secret: &str,
) -> Result<WebhookEvent> {
verify_webhook(payload, headers, secret)
}
}
impl Wellfriend {
pub fn webhooks(&self) -> Webhooks {
Webhooks {
client: self.clone(),
options: RequestOptions::default(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
const BODY: &str = r#"{"test": 2432232314}"#;
fn headers(signature: &str) -> Vec<(&'static str, String)> {
vec![
("webhook-id", "msg_p5jXN8AQM9LWM0D4loKWxJek".into()),
("webhook-timestamp", "1614265330".into()),
("webhook-signature", signature.into()),
]
}
fn at() -> SystemTime {
UNIX_EPOCH + Duration::from_secs(1_614_265_330)
}
#[test]
fn checks_the_signature_and_the_secret_list() {
let good = headers("v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=");
let error = WebhookVerifier::new([SECRET])
.at(at())
.verify(BODY.as_bytes(), &good)
.unwrap_err();
assert!(error.to_string().contains("not an event"), "{error}");
let wrong = WebhookVerifier::new(["whsec_AAAAAAAAAAAAAAAAAAAAAAAAAAAA"])
.at(at())
.verify(BODY.as_bytes(), &good)
.unwrap_err();
assert!(wrong.to_string().contains("no signature matches"));
let rotated = WebhookVerifier::new(["whsec_AAAAAAAAAAAAAAAAAAAAAAAAAAAA", SECRET])
.at(at())
.verify(BODY.as_bytes(), &good)
.unwrap_err();
assert!(rotated.to_string().contains("not an event"));
}
#[cfg(feature = "ed25519")]
#[test]
fn verifies_ed25519_signatures() {
use ed25519_dalek::{Signer, SigningKey};
let signing = SigningKey::from_bytes(&[9u8; 32]);
let public =
base64::engine::general_purpose::STANDARD.encode(signing.verifying_key().to_bytes());
let signature =
signing.sign(format!("msg_p5jXN8AQM9LWM0D4loKWxJek.1614265330.{BODY}").as_bytes());
let header = format!(
"v1a,{}",
base64::engine::general_purpose::STANDARD.encode(signature.to_bytes())
);
let error = WebhookVerifier::ed25519([public.clone()])
.at(at())
.verify(BODY.as_bytes(), headers(&header))
.unwrap_err();
assert!(error.to_string().contains("not an event"), "{error}");
let other = base64::engine::general_purpose::STANDARD.encode(
SigningKey::from_bytes(&[1u8; 32])
.verifying_key()
.to_bytes(),
);
let error = WebhookVerifier::ed25519([other])
.at(at())
.verify(BODY.as_bytes(), headers(&header))
.unwrap_err();
assert!(error.to_string().contains("no signature matches"));
}
#[test]
fn decodes_both_secret_alphabets() {
assert_eq!(
decode_secret("whsec_+//+fT4/AAECAwT7/wUGBwgJ+gsMDQ4P+//+EBESExQV"),
decode_secret("whsec_-__-fT4_AAECAwT7_wUGBwgJ-gsMDQ4P-__-EBESExQV")
);
assert!(decode_secret("whsec_short").is_none());
}
}