use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
pub struct Signer;
impl Signer {
pub const HEADER: &'static str = "Webhook-Signature";
#[must_use]
pub fn sign(body: &str, secret: &str, timestamp: i64) -> String {
format!("t={timestamp},v1={}", hash(body, secret, timestamp))
}
#[must_use]
pub fn verify(
body: &str,
header: Option<&str>,
secret: &str,
tolerance: i64,
now: i64,
) -> bool {
let mut timestamp = None;
let mut signatures = Vec::new();
for part in header.unwrap_or_default().split(',') {
let (key, value) = part.trim().split_once('=').unwrap_or((part.trim(), ""));
if key == "t" && !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
timestamp = value.parse::<i64>().ok();
} else if key == "v1" && !value.is_empty() {
signatures.push(value);
}
}
let Some(timestamp) = timestamp.filter(|timestamp| (now - timestamp).abs() <= tolerance)
else {
return false;
};
let expected = hash(body, secret, timestamp);
signatures
.iter()
.any(|signature| constant_time_eq(expected.as_bytes(), signature.as_bytes()))
}
}
fn hash(body: &str, secret: &str, timestamp: i64) -> String {
let mut mac =
Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("HMAC takes keys of any length");
mac.update(format!("{timestamp}.{body}").as_bytes());
mac.finalize()
.into_bytes()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0, |diff, (x, y)| diff | (x ^ y)) == 0
}
#[must_use]
pub fn is_public(address: IpAddr) -> bool {
match address {
IpAddr::V4(address) => is_public_v4(address),
IpAddr::V6(address) => is_public_v6(address),
}
}
fn is_public_v4(address: Ipv4Addr) -> bool {
let [a, b, c, _] = address.octets();
let special = a == 0
|| a == 10
|| (a == 100 && (64..=127).contains(&b))
|| a == 127
|| (a == 169 && b == 254)
|| (a == 172 && (16..=31).contains(&b))
|| (a == 192 && b == 0 && (c == 0 || c == 2))
|| (a == 192 && b == 168)
|| (a == 198 && (b == 18 || b == 19))
|| (a == 198 && b == 51 && c == 100)
|| (a == 203 && b == 0 && c == 113)
|| a >= 240;
!special
}
fn is_public_v6(address: Ipv6Addr) -> bool {
let segments = address.segments();
if segments[0] == 0x64 && segments[1] == 0xff9b {
let [.., a, b, c, d] = address.octets();
return segments[2..6] == [0; 4] && is_public_v4(Ipv4Addr::new(a, b, c, d));
}
let special = address.is_unspecified()
|| address.is_loopback()
|| segments[..6] == [0, 0, 0, 0, 0, 0xffff]
|| segments[..4] == [0x100, 0, 0, 0]
|| (segments[0] == 0x2001 && segments[1] <= 0x1ff)
|| (segments[0] == 0x2001 && segments[1] == 0xdb8)
|| segments[0] == 0x2002
|| segments[0] & 0xfe00 == 0xfc00
|| segments[0] & 0xffc0 == 0xfe80;
!special
}
#[cfg(feature = "database")]
pub use self::store::*;
#[cfg(feature = "database")]
mod store {
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::time::Instant;
use laravel::db::{self, col, values};
use laravel::http::client;
use laravel::http::client::reqwest;
use laravel::prelude::ToSpan;
use laravel::queue::{Attempt, Queueable, job};
use serde_json::{Map, Value};
use crate::query::Row;
use crate::{State, glob, time, versioning};
pub const SECRET_PREFIX: &str = "whsec_";
pub const PENDING: &str = "pending";
pub const DELIVERED: &str = "delivered";
pub const FAILED: &str = "failed";
#[derive(Debug, Clone)]
pub struct Event {
kind: String,
document: Value,
owner: Option<(String, i64)>,
}
impl Event {
#[must_use]
pub fn new(kind: impl Into<String>, document: Value) -> Self {
Self {
kind: kind.into(),
document,
owner: None,
}
}
#[must_use]
pub fn owner(mut self, kind: impl Into<String>, id: i64) -> Self {
self.owner = Some((kind.into(), id));
self
}
pub async fn dispatch(self) -> laravel::Result<Vec<i64>> {
let mut query = db::table("webhook_endpoints")
.select(["id", "events"])
.filter(col("active").eq(true));
if let Some((kind, id)) = &self.owner {
query = query
.filter(col("owner_type").eq(kind.clone()))
.filter(col("owner_id").eq(*id));
}
let rows: Vec<Row> = query.get().await?;
let endpoints: Vec<i64> = rows
.into_iter()
.filter(|row| subscribes_to(&row.0, &self.kind))
.filter_map(|row| row.0.get("id").and_then(Value::as_i64))
.collect();
if endpoints.is_empty() {
return Ok(Vec::new());
}
let mut payload = Map::new();
let event_id = format!("evt_{}", ulid::Ulid::new().to_string().to_lowercase());
payload.insert("id".into(), Value::String(event_id.clone()));
payload.insert("type".into(), Value::String(self.kind.clone()));
payload.insert("created_at".into(), Value::String(time::atom(time::now())));
for member in ["data", "included"] {
if let Some(value) = self.document.get(member).filter(|value| !value.is_null()) {
payload.insert(member.into(), value.clone());
}
}
let payload = Value::Object(payload).to_string();
let settings = settings();
let mut deliveries = Vec::new();
for endpoint in endpoints {
let now = laravel::now().timestamp();
let id = db::table("webhook_deliveries")
.insert_get_id(
values! {
webhook_endpoint_id: endpoint,
event_id: event_id.clone(),
event_type: self.kind.clone(),
payload: payload.clone(),
status: PENDING,
attempts: 0_i64,
created_at: now,
updated_at: now,
},
"id",
)
.await?;
let mut job = DeliverWebhook { delivery_id: id }.dispatch();
if let Some(connection) = &settings.connection {
job = job.on_connection(connection);
}
if let Some(queue) = &settings.queue {
job = job.on_queue(queue);
}
job.await?;
deliveries.push(id);
}
Ok(deliveries)
}
}
fn subscribes_to(endpoint: &Map<String, Value>, kind: &str) -> bool {
endpoint
.get("events")
.and_then(Value::as_str)
.and_then(|events| serde_json::from_str::<Vec<String>>(events).ok())
.unwrap_or_default()
.iter()
.any(|pattern| glob(pattern, kind))
}
#[derive(Debug, Clone)]
pub(crate) struct Settings {
pub(crate) connection: Option<String>,
pub(crate) queue: Option<String>,
pub(crate) timeout: u64,
pub(crate) backoff: Vec<u64>,
pub(crate) disable_after: Option<i64>,
pub(crate) allow_private_addresses: bool,
}
impl Default for Settings {
fn default() -> Self {
Self {
connection: None,
queue: None,
timeout: 10,
backoff: vec![60, 300, 1800, 3600, 10_800, 21_600, 43_200],
disable_after: Some(5),
allow_private_addresses: false,
}
}
}
fn state() -> Option<&'static State> {
crate::STATE.get().map(AsRef::as_ref)
}
fn settings() -> Settings {
state()
.map(|state| state.config.webhooks.clone())
.unwrap_or_default()
}
pub async fn register(
url: &str,
events: &[&str],
version: Option<&str>,
description: Option<&str>,
) -> laravel::Result<i64> {
let version = version.map(str::to_owned).or_else(|| {
state()
.and_then(|state| state.registry.as_ref())
.map(|registry| registry.latest.to_string())
});
let secret = new_secret();
let now = laravel::now().timestamp();
db::table("webhook_endpoints")
.insert_get_id(
values! {
url: url,
description: description.map(str::to_owned),
secret: laravel::crypt::encrypt_string(&secret)?,
events: serde_json::to_string(events).unwrap_or_default(),
version: version,
active: true,
consecutive_failures: 0_i64,
created_at: now,
updated_at: now,
},
"id",
)
.await
}
fn new_secret() -> String {
format!("{SECRET_PREFIX}{}", laravel::str::random(32))
}
pub async fn secret(endpoint: i64) -> laravel::Result<String> {
let row: Option<Row> = db::table("webhook_endpoints")
.select(["secret"])
.filter(col("id").eq(endpoint))
.first()
.await?;
let encrypted = row
.and_then(|row| {
row.0
.get("secret")
.and_then(Value::as_str)
.map(str::to_owned)
})
.ok_or_else(|| laravel::Error::msg(format!("No webhook endpoint [{endpoint}].")))?;
laravel::crypt::decrypt_string(&encrypted)
}
pub async fn rotate_secret(endpoint: i64) -> laravel::Result<String> {
let secret = new_secret();
db::table("webhook_endpoints")
.filter(col("id").eq(endpoint))
.update(values! {
secret: laravel::crypt::encrypt_string(&secret)?,
updated_at: laravel::now().timestamp(),
})
.await?;
Ok(secret)
}
pub async fn enable(endpoint: i64) -> laravel::Result<()> {
db::table("webhook_endpoints")
.filter(col("id").eq(endpoint))
.update(values! {
active: true,
consecutive_failures: 0_i64,
disabled_at: None::<String>,
updated_at: laravel::now().timestamp(),
})
.await?;
Ok(())
}
#[derive(Queueable)]
pub struct DeliverWebhook {
pub delivery_id: i64,
}
#[job(name = "fusion-stack.deliver-webhook", retry_for = 7.days())]
impl DeliverWebhook {
async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
deliver(self.delivery_id, attempt).await
}
}
fn int(row: &Map<String, Value>, key: &str) -> i64 {
match row.get(key) {
Some(Value::Bool(value)) => i64::from(*value),
Some(value) => value.as_i64().unwrap_or_default(),
None => 0,
}
}
fn text(row: &Map<String, Value>, key: &str) -> Option<String> {
row.get(key).and_then(Value::as_str).map(str::to_owned)
}
async fn deliver(delivery_id: i64, attempt: &Attempt) -> laravel::Result<()> {
let delivery: Option<Row> = db::table("webhook_deliveries")
.filter(col("id").eq(delivery_id))
.first()
.await?;
let Some(Row(delivery)) = delivery else {
return Ok(());
};
if text(&delivery, "status").as_deref() == Some(DELIVERED) {
return Ok(());
}
let endpoint_id = int(&delivery, "webhook_endpoint_id");
let endpoint: Option<Row> = db::table("webhook_endpoints")
.filter(col("id").eq(endpoint_id))
.first()
.await?;
let Some(Row(endpoint)) = endpoint else {
return Ok(());
};
if int(&endpoint, "active") == 0 {
update_delivery(
delivery_id,
values! { status: FAILED, error: "The endpoint is disabled.", updated_at: laravel::now().timestamp() },
)
.await?;
return Ok(());
}
let settings = settings();
let kind = text(&delivery, "event_type").unwrap_or_default();
let stored: Value = text(&delivery, "payload")
.and_then(|payload| serde_json::from_str(&payload).ok())
.unwrap_or(Value::Null);
let body = payload(stored, text(&endpoint, "version").as_deref(), &kind).to_string();
let secret =
laravel::crypt::decrypt_string(&text(&endpoint, "secret").unwrap_or_default())?;
let url = text(&endpoint, "url").unwrap_or_default();
let event_id = text(&delivery, "event_id").unwrap_or_default();
let started = Instant::now();
let destination = if settings.allow_private_addresses {
Destination::Unchecked
} else {
let url = url.clone();
laravel::task::spawn_blocking(move || Destination::of(&url, lookup)).await?
};
let (status, error) = if let Destination::Refused(reason) = destination {
(None, Some(reason))
} else {
let sent = client::post(url.as_str())
.header("Webhook-Id", event_id.as_str())
.header(
super::Signer::HEADER,
super::Signer::sign(&body, &secret, time::now()),
)
.header("User-Agent", "Fusion Stack Webhooks")
.body(body, "application/json")
.timeout(i64::try_from(settings.timeout).unwrap_or(10).seconds())
.configure_transport(move |transport| destination.apply(transport))
.await;
match sent {
Ok(response) if response.successful() => (Some(response.status().as_u16()), None),
Ok(response) => {
let status = response.status().as_u16();
(
Some(status),
Some(format!("The endpoint responded with {status}.")),
)
}
Err(error) => (None, Some(error.to_string())),
}
};
let attempts = int(&delivery, "attempts") + 1;
let retry_in = if error.is_none() || attempt.connection() == "sync" {
None
} else {
usize::try_from(attempts - 1)
.ok()
.and_then(|index| settings.backoff.get(index))
.copied()
};
let status_text = match (&error, retry_in) {
(None, _) => DELIVERED,
(Some(_), Some(_)) => PENDING,
(Some(_), None) => FAILED,
};
let now = laravel::now().timestamp();
update_delivery(
delivery_id,
values! {
status: status_text,
attempts: attempts,
response_status: status.map(i64::from),
duration_ms: i64::try_from(started.elapsed().as_millis()).unwrap_or(i64::MAX),
error: error.as_ref().map(|error| error.chars().take(1000).collect::<String>()),
delivered_at: error.is_none().then_some(now),
updated_at: now,
},
)
.await?;
match (error, retry_in) {
(None, _) => {
if int(&endpoint, "consecutive_failures") > 0 {
db::table("webhook_endpoints")
.filter(col("id").eq(endpoint_id))
.update(values! { consecutive_failures: 0_i64 })
.await?;
}
}
(Some(_), Some(delay)) => {
attempt.release(i64::try_from(delay).unwrap_or(i64::MAX).seconds());
}
(Some(_), None) => count_failure(&endpoint, endpoint_id, &settings).await?,
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Destination {
Unchecked,
Direct,
Pinned(String, Vec<SocketAddr>),
Unreachable(String),
Refused(String),
}
impl Destination {
pub(crate) fn of(url: &str, lookup: impl FnOnce(&str, u16) -> Vec<SocketAddr>) -> Self {
let Ok(url) = reqwest::Url::parse(url) else {
return Self::Direct;
};
let Some(host) = url.host_str() else {
return Self::Direct;
};
let private = || {
format!(
"The endpoint's host [{}] is not on the public internet, so the webhook was not sent.",
host.trim_matches(['[', ']'])
)
};
if let Ok(address) = host.trim_matches(['[', ']']).parse::<IpAddr>() {
return if super::is_public(address) {
Self::Direct
} else {
Self::Refused(private())
};
}
let addresses = lookup(host, url.port_or_known_default().unwrap_or(443));
if addresses.is_empty() {
return Self::Unreachable(format!(
"The endpoint's host [{host}] could not be resolved, so the webhook was not sent."
));
}
if addresses
.iter()
.all(|address| super::is_public(address.ip()))
{
Self::Pinned(host.to_owned(), addresses)
} else {
Self::Unreachable(private())
}
}
fn apply(&self, transport: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
let transport = transport.redirect(reqwest::redirect::Policy::none());
match self {
Self::Pinned(host, addresses) => transport.resolve_to_addrs(host, addresses),
Self::Unreachable(reason) => transport.dns_resolver(NoLookup(reason.clone())),
Self::Unchecked | Self::Direct | Self::Refused(_) => transport,
}
}
}
fn lookup(host: &str, port: u16) -> Vec<SocketAddr> {
(host, port)
.to_socket_addrs()
.map(Iterator::collect)
.unwrap_or_default()
}
struct NoLookup(String);
impl reqwest::dns::Resolve for NoLookup {
fn resolve(&self, _name: reqwest::dns::Name) -> reqwest::dns::Resolving {
let reason = self.0.clone();
Box::pin(async move { Err(reason.into()) })
}
}
async fn update_delivery(id: i64, values: db::Values) -> laravel::Result<()> {
db::table("webhook_deliveries")
.filter(col("id").eq(id))
.update(values)
.await?;
Ok(())
}
async fn count_failure(
endpoint: &Map<String, Value>,
id: i64,
settings: &Settings,
) -> laravel::Result<()> {
let failures = int(endpoint, "consecutive_failures") + 1;
let disable = settings
.disable_after
.is_some_and(|limit| limit >= 1 && failures >= limit);
let now = laravel::now().timestamp();
let query = db::table("webhook_endpoints").filter(col("id").eq(id));
if disable {
query
.update(values! { consecutive_failures: failures, active: false, disabled_at: now, updated_at: now })
.await?;
} else {
query
.update(values! { consecutive_failures: failures })
.await?;
}
Ok(())
}
pub(crate) fn payload(stored: Value, version: Option<&str>, kind: &str) -> Value {
let Some(registry) = state().and_then(|state| state.registry.as_ref()) else {
return stored;
};
let version = registry
.resolve(version, time::now())
.unwrap_or_else(|_| registry.default.clone());
let Value::Object(stored) = stored else {
return stored;
};
let mut document = Map::new();
let mut payload = Map::new();
for (key, value) in stored {
if key == "data" || key == "included" {
document.insert(key, value);
} else {
payload.insert(key, value);
}
}
let mut document = Value::Object(document);
let route = format!("webhooks.{kind}");
let types = versioning::document::types(&document);
for change in registry.changes_after(&version, None).iter().rev() {
if versioning::applies_to(change.as_ref(), &types, &route) {
change.transform_response(&mut document);
}
}
payload.insert("api_version".into(), Value::String(version.to_string()));
if let Value::Object(document) = document {
payload.extend(document);
}
Value::Object(payload)
}
}
#[cfg(test)]
mod tests {
use std::net::IpAddr;
use super::{Signer, is_public};
#[test]
fn tells_public_addresses_from_private_ones() {
let addresses: serde_json::Value = serde_json::from_str(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/webhook-addresses.json"
)))
.unwrap_or_default();
let verdicts = |list: &str| -> Vec<(String, bool)> {
addresses[list]
.as_array()
.into_iter()
.flatten()
.filter_map(serde_json::Value::as_str)
.map(|address| {
let parsed: Option<IpAddr> = address.parse().ok();
(address.to_owned(), parsed.is_some_and(is_public))
})
.collect()
};
let (public, private) = (verdicts("public"), verdicts("private"));
assert!(public.len() > 5 && private.len() > 20);
assert_eq!(
public
.iter()
.filter(|(_, public)| !public)
.collect::<Vec<_>>(),
Vec::<&(String, bool)>::new()
);
assert_eq!(
private
.iter()
.filter(|(_, public)| *public)
.collect::<Vec<_>>(),
Vec::<&(String, bool)>::new()
);
}
#[cfg(feature = "database")]
#[test]
fn deliveries_connect_only_to_public_addresses_they_checked() {
use std::net::SocketAddr;
use super::Destination;
let address = |address: &str| -> SocketAddr { address.parse().expect("a socket address") };
let never =
|_: &str, _: u16| -> Vec<SocketAddr> { panic!("an IP address is not looked up") };
let private = |host: &str| {
format!(
"The endpoint's host [{host}] is not on the public internet, so the webhook was not sent."
)
};
for (url, host) in [
("http://127.0.0.1:9/hooks", "127.0.0.1"),
("http://2130706433:9/hooks", "127.0.0.1"),
("http://0x7f.1/hooks", "127.0.0.1"),
("http://[::1]:9/hooks", "::1"),
("http://169.254.169.254/latest/meta-data", "169.254.169.254"),
("https://10.0.0.5/hooks", "10.0.0.5"),
] {
assert_eq!(
Destination::of(url, never),
Destination::Refused(private(host)),
"{url}"
);
}
assert_eq!(
Destination::of("https://93.184.216.34/hooks", never),
Destination::Direct
);
let public = vec![
address("93.184.216.34:443"),
address("[2606:4700:4700::1111]:443"),
];
assert_eq!(
Destination::of("https://hooks.example.com/orders", |host, port| {
assert_eq!((host, port), ("hooks.example.com", 443));
public.clone()
}),
Destination::Pinned("hooks.example.com".to_owned(), public.clone())
);
assert_eq!(
Destination::of("http://hooks.example.com:8080/orders", |_, port| vec![
SocketAddr::new(public[0].ip(), port)
]),
Destination::Pinned(
"hooks.example.com".to_owned(),
vec![address("93.184.216.34:8080")]
)
);
assert_eq!(
Destination::of("https://hooks.example.com/orders", |_, _| vec![
public[0],
address("10.0.0.5:443")
]),
Destination::Unreachable(private("hooks.example.com"))
);
assert_eq!(
Destination::of("https://localhost/hooks", |_, _| vec![address(
"127.0.0.1:443"
)]),
Destination::Unreachable(private("localhost"))
);
assert_eq!(
Destination::of("https://nowhere.example.com/hooks", |_, _| Vec::new()),
Destination::Unreachable(
"The endpoint's host [nowhere.example.com] could not be resolved, so the webhook was not sent.".to_owned()
)
);
}
#[test]
fn signatures_verify_within_the_tolerance() {
let header = Signer::sign("{\"a\":1}", "whsec_x", 1_000);
assert!(header.starts_with("t=1000,v1="));
assert!(Signer::verify(
"{\"a\":1}",
Some(&header),
"whsec_x",
300,
1_200
));
assert!(!Signer::verify(
"{\"a\":1}",
Some(&header),
"whsec_x",
300,
1_301
));
assert!(!Signer::verify(
"{\"a\":2}",
Some(&header),
"whsec_x",
300,
1_000
));
assert!(!Signer::verify(
"{\"a\":1}",
Some(&header),
"whsec_y",
300,
1_000
));
let old = Signer::sign("{\"a\":1}", "whsec_old", 1_000);
let both = format!("{header},{}", old.split_once(',').unwrap_or_default().1);
assert!(Signer::verify(
"{\"a\":1}",
Some(&both),
"whsec_old",
300,
1_000
));
assert!(!Signer::verify("{\"a\":1}", None, "whsec_x", 300, 1_000));
}
#[test]
fn signatures_match_php_hash_hmac() {
assert_eq!(
Signer::sign("{}", "whsec_test", 1_700_000_000),
"t=1700000000,v1=35495024f4ef3f94e5a93e22221544c4b75e9a42300cd965ab81cb85cd994e91"
);
}
}