use crate::{
client::{CallResponse, Error, One, PATH_SEGMENT},
transport::types::WebhookSubscriptionView
};
use chrono::{DateTime, Utc};
use hmac::{Hmac, KeyInit, Mac};
use percent_encoding::utf8_percent_encode;
use secrecy::{ExposeSecret, SecretString};
use serde::de::DeserializeOwned;
use serde_json::{Value, from_value, json};
use sha2::Sha256;
use std::{collections::HashMap, error::Error as StdError, future::ready, pin::Pin, time::Duration};
use uuid::Uuid;
type HmacSha256 = Hmac<Sha256>;
pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<(), WebhookError>> + Send>>;
type Handler = Box<dyn Fn(Delivery) -> HandlerFuture + Send + Sync>;
pub trait WebhookHandlerOutput {
#[doc(hidden)]
fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>>;
}
impl WebhookHandlerOutput for () {
fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>> {
Ok(())
}
}
impl<E> WebhookHandlerOutput for Result<(), E>
where
E: StdError + Send + Sync + 'static
{
fn into_webhook_result(self) -> Result<(), Box<dyn StdError + Send + Sync>> {
self.map_err(|error| Box::new(error) as Box<dyn StdError + Send + Sync>)
}
}
const SIGNATURE_PREFIX: &str = "sha256=";
const SUBSCRIPTIONS_BY_KEY_PATH: &str = "/v1/webhooks/subscriptions/by-key/";
const TEST_METADATA_FIELD: &str = "test";
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum WebhookError {
#[error("webhook signature header is missing or malformed")]
MalformedSignature,
#[error("webhook signature verification failed")]
InvalidSignature,
#[error("webhook event is older than the configured {max_age_secs}s maximum age")]
Expired { max_age_secs: u64 },
#[error("failed to parse webhook payload: {0}")]
Parse(#[from] serde_json::Error),
#[error("webhook handler failed: {0}")]
Handler(#[source] Box<dyn StdError + Send + Sync>),
#[error(transparent)]
Api(#[from] Error)
}
#[derive(Clone, Debug)]
pub struct Delivery<P = Value> {
event: String,
id: Uuid,
timestamp: DateTime<Utc>,
payload: P,
metadata: Option<Value>
}
impl<P> Delivery<P> {
pub fn event_type(&self) -> Option<WebhookEventType> {
WebhookEventType::parse(&self.event)
}
pub fn event(&self) -> &str {
&self.event
}
pub fn id(&self) -> Uuid {
self.id
}
pub fn timestamp(&self) -> DateTime<Utc> {
self.timestamp
}
pub fn payload(&self) -> &P {
&self.payload
}
pub fn metadata(&self) -> Option<&Value> {
self.metadata.as_ref()
}
}
impl Delivery {
pub fn connection_key(&self) -> Result<Option<String>, serde_json::Error> {
if self.is_test() {
return Ok(None);
}
match self.event_type() {
Some(event) => event.connection_key_of(&self.payload),
None => Ok(None)
}
}
pub fn is_test(&self) -> bool {
self.metadata
.as_ref()
.and_then(|metadata| metadata.get(TEST_METADATA_FIELD))
.and_then(Value::as_bool)
.unwrap_or(false)
}
fn retype<P: DeserializeOwned>(&self) -> Result<Delivery<P>, serde_json::Error> {
Ok(Delivery {
event: self.event.clone(),
id: self.id,
timestamp: self.timestamp,
payload: from_value(self.payload.clone())?,
metadata: self.metadata.clone()
})
}
}
#[derive(Deserialize)]
struct RawDelivery {
event: String,
event_id: Uuid,
timestamp: DateTime<Utc>,
payload: Value,
metadata: Option<Value>
}
struct Registered {
connection: Option<String>,
run: Handler
}
impl Registered {
fn accepts(&self, delivery: &Delivery) -> Result<bool, WebhookError> {
match &self.connection {
None => Ok(true),
Some(key) => Ok(delivery.connection_key()?.as_deref() == Some(key.as_str()))
}
}
async fn run_if_accepted(&self, delivery: &Delivery) -> Result<(), WebhookError> {
if self.accepts(delivery)? {
(self.run)(delivery.clone()).await?;
}
Ok(())
}
}
pub struct Webhooks {
client: One,
secret: SecretString,
tolerance: Option<Duration>,
handlers: HashMap<WebhookEventType, Vec<Registered>>,
any: Vec<Registered>
}
impl Webhooks {
pub(crate) fn new(client: One, secret: SecretString) -> Self {
Self {
client,
secret,
tolerance: None,
handlers: HashMap::new(),
any: Vec::new()
}
}
pub fn max_event_age(mut self, max_age: Duration) -> Self {
self.tolerance = Some(max_age);
self
}
pub fn connection<F>(mut self, key: impl Into<String>, block: F) -> Self
where
F: FnOnce(ConnectionWebhooks) -> ConnectionWebhooks
{
let scope = block(ConnectionWebhooks {
key: key.into(),
handlers: HashMap::new(),
any: Vec::new()
});
for (event, handlers) in scope.handlers {
self.handlers.entry(event).or_default().extend(handlers);
}
self.any.extend(scope.any);
self
}
pub fn on_any<F, Fut, Output>(mut self, handler: F) -> Self
where
F: Fn(Delivery) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Output> + Send + 'static,
Output: WebhookHandlerOutput + Send + 'static
{
self.any.push(Registered {
connection: None,
run: Box::new(move |delivery| {
let work = handler(delivery);
Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
})
});
self
}
pub(crate) fn register<P, F, Fut, Output>(
mut self,
event: WebhookEventType,
connection: Option<String>,
handler: F
) -> Self
where
P: DeserializeOwned + Send + 'static,
F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Output> + Send + 'static,
Output: WebhookHandlerOutput + Send + 'static
{
self.handlers
.entry(event)
.or_default()
.push(typed_handler(connection, handler));
self
}
pub fn events(&self) -> Vec<WebhookEventType> {
if self.any.iter().any(|handler| handler.connection.is_none()) {
return WebhookEventType::ALL.to_vec();
}
let mut events: Vec<WebhookEventType> = self.handlers.keys().copied().collect();
if !self.any.is_empty() {
events.extend(WebhookEventType::CONNECTION_SCOPED);
}
events.sort();
events.dedup();
events
}
pub fn verify(&self, raw_body: &[u8], signature: &str) -> Result<Delivery, WebhookError> {
Self::verify_with(&self.secret, self.tolerance, raw_body, signature)
}
pub fn verify_with(
secret: &SecretString,
tolerance: Option<Duration>,
raw_body: &[u8],
signature: &str
) -> Result<Delivery, WebhookError> {
let hex_sig = signature
.strip_prefix(SIGNATURE_PREFIX)
.ok_or(WebhookError::MalformedSignature)?;
let expected = hex::decode(hex_sig).map_err(|_| WebhookError::MalformedSignature)?;
let mut mac = HmacSha256::new_from_slice(secret.expose_secret().as_bytes())
.map_err(|_| WebhookError::InvalidSignature)?;
mac.update(raw_body);
mac.verify_slice(&expected)
.map_err(|_| WebhookError::InvalidSignature)?;
let raw: RawDelivery = serde_json::from_slice(raw_body)?;
if let Some(max_age) = tolerance {
let age = Utc::now().signed_duration_since(raw.timestamp).abs();
if age.to_std().is_ok_and(|age| age > max_age) {
return Err(WebhookError::Expired {
max_age_secs: max_age.as_secs()
});
}
}
Ok(Delivery {
event: raw.event,
id: raw.event_id,
timestamp: raw.timestamp,
payload: raw.payload,
metadata: raw.metadata
})
}
pub async fn handle(&self, raw_body: &[u8], signature: &str) -> Result<Delivery, WebhookError> {
let delivery = self.verify(raw_body, signature)?;
let mut failure = None;
if !delivery.is_test()
&& let Some(event) = delivery.event_type()
&& let Some(handlers) = self.handlers.get(&event)
{
for handler in handlers {
if let Err(error) = handler.run_if_accepted(&delivery).await {
failure.get_or_insert(error);
}
}
}
for handler in &self.any {
if let Err(error) = handler.run_if_accepted(&delivery).await {
failure.get_or_insert(error);
}
}
match failure {
Some(error) => Err(error),
None => Ok(delivery)
}
}
pub async fn listen(
&self,
key: impl AsRef<str>,
url: impl AsRef<str>
) -> Result<WebhookSubscriptionView, WebhookError> {
let events: Vec<&str> = self.events().iter().map(|event| event.as_str()).collect();
let response = Self::register_listener(&self.client, key.as_ref(), url.as_ref(), &events, &self.secret).await?;
Ok(response.output()?)
}
pub async fn register_listener(
client: &One,
key: &str,
url: &str,
events: &[&str],
secret: &SecretString
) -> Result<CallResponse<WebhookSubscriptionView>, WebhookError> {
let path = format!("{SUBSCRIPTIONS_BY_KEY_PATH}{}", utf8_percent_encode(key, PATH_SEGMENT));
let body = json!({ "url": url, "events": events, "secret": secret.expose_secret() });
Ok(client.put_json_response(&path, &body).await?)
}
}
pub struct ConnectionWebhooks {
key: String,
handlers: HashMap<WebhookEventType, Vec<Registered>>,
any: Vec<Registered>
}
impl ConnectionWebhooks {
pub fn on_any<F, Fut, Output>(mut self, handler: F) -> Self
where
F: Fn(Delivery) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Output> + Send + 'static,
Output: WebhookHandlerOutput + Send + 'static
{
self.any.push(Registered {
connection: Some(self.key.clone()),
run: Box::new(move |delivery| {
let work = handler(delivery);
Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
})
});
self
}
pub(crate) fn register<P, F, Fut, Output>(mut self, event: WebhookEventType, handler: F) -> Self
where
P: DeserializeOwned + Send + 'static,
F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Output> + Send + 'static,
Output: WebhookHandlerOutput + Send + 'static
{
let connection = Some(self.key.clone());
self.handlers
.entry(event)
.or_default()
.push(typed_handler(connection, handler));
self
}
}
fn typed_handler<P, F, Fut, Output>(connection: Option<String>, handler: F) -> Registered
where
P: DeserializeOwned + Send + 'static,
F: Fn(Delivery<P>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Output> + Send + 'static,
Output: WebhookHandlerOutput + Send + 'static
{
Registered {
connection,
run: Box::new(move |delivery| match delivery.retype::<P>() {
Ok(typed) => {
let work = handler(typed);
Box::pin(async move { work.await.into_webhook_result().map_err(WebhookError::Handler) })
}
Err(error) => Box::pin(ready(Err(WebhookError::Parse(error))))
})
}
}
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/generated/webhooks_generated.rs"));
#[cfg(test)]
mod tests {
use std::{
future::ready,
io::Error as IoError,
sync::{
Arc,
atomic::{AtomicBool, Ordering}
}
};
use chrono::Utc;
use hmac::{KeyInit, Mac};
use secrecy::SecretString;
use serde_json::json;
use uuid::Uuid;
use super::{Delivery, HmacSha256, Registered, WebhookError, Webhooks};
use crate::One;
#[tokio::test]
async fn test_webhooks_handle_propagates_first_handler_failure_after_dispatching_all_handlers() {
let secret = "handler-secret";
let raw_body = serde_json::to_vec(&json!({
"event": "future.event",
"event_id": Uuid::nil(),
"timestamp": Utc::now(),
"payload": {},
"metadata": null
}))
.expect("delivery serializes");
let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts the secret");
mac.update(&raw_body);
let signature = format!("sha256={}", hex::encode(mac.finalize().into_bytes()));
let second_ran = Arc::new(AtomicBool::new(false));
let second_handler = Arc::clone(&second_ran);
let webhooks = Webhooks::new(
One::builder().secret("api-secret").build().expect("client builds"),
SecretString::from(secret.to_string())
)
.on_any(|_| async { Err::<(), _>(IoError::other("first failure")) })
.on_any(move |_| {
let second_handler = Arc::clone(&second_handler);
async move {
second_handler.store(true, Ordering::SeqCst);
}
});
let error = webhooks
.handle(&raw_body, &signature)
.await
.expect_err("handler failure propagates");
assert!(second_ran.load(Ordering::SeqCst));
match error {
WebhookError::Handler(source) => assert_eq!(source.to_string(), "first failure"),
other => panic!("unexpected webhook error: {other}")
}
}
#[test]
fn test_webhooks_scoped_handler_preserves_connection_decode_errors() {
let delivery = Delivery {
event: "connection.created".to_string(),
id: Uuid::nil(),
timestamp: Utc::now(),
payload: json!({ "key": 42 }),
metadata: None
};
let handler = Registered {
connection: Some("primary".to_string()),
run: Box::new(|_| Box::pin(ready(Ok(()))))
};
assert!(matches!(handler.accepts(&delivery), Err(WebhookError::Parse(_))));
}
#[test]
fn test_webhooks_test_delivery_skips_connection_payload_decode() {
let delivery = Delivery {
event: "connection.created".to_string(),
id: Uuid::nil(),
timestamp: Utc::now(),
payload: json!({ "test": true }),
metadata: Some(json!({ "test": true }))
};
assert_eq!(delivery.connection_key().expect("test delivery is accepted"), None);
}
}