use std::sync::Arc;
use std::time::Duration as StdDuration;
use async_trait::async_trait;
use super::{CallbackPolicy, CallbackRejected, Channel, Delivery, DeliveryFailure, Notifier};
use crate::core::{Clock, SystemClock};
pub use crate::webhook::{ATTEMPT_HEADER, SIGNATURE_HEADER, TIMESTAMP_HEADER};
#[derive(Debug, Clone)]
pub struct WebhookConfig {
pub timeout: StdDuration,
pub signing_key: Option<String>,
pub policy: CallbackPolicy,
}
impl Default for WebhookConfig {
fn default() -> Self {
Self {
timeout: StdDuration::from_secs(15),
signing_key: None,
policy: CallbackPolicy::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum WebhookError {
#[error(transparent)]
Rejected(#[from] CallbackRejected),
#[error("callback returned {status}")]
Status {
status: u16,
},
#[error("callback unreachable: {0}")]
Unreachable(String),
#[error("the endpoint did not echo the challenge")]
EchoFailed,
#[error("this delivery names no callback URL, so it is not a webhook's to make")]
NotOurs,
}
impl WebhookError {
pub fn is_retriable(&self) -> bool {
match self {
Self::Rejected(CallbackRejected::Malformed(_) | CallbackRejected::NotHttps)
| Self::Rejected(CallbackRejected::NoHost) => false,
Self::Rejected(_) => true,
Self::Status { status } => {
!(400..500).contains(status) || *status == 408 || *status == 429
}
Self::Unreachable(_) => true,
Self::EchoFailed => false,
Self::NotOurs => false,
}
}
}
#[derive(Debug)]
pub struct WebhookNotifier {
http: reqwest::Client,
config: WebhookConfig,
clock: Arc<dyn Clock>,
}
impl WebhookNotifier {
pub fn new(config: WebhookConfig) -> Result<Self, WebhookError> {
crate::crypto::install_crypto_provider();
let http = reqwest::Client::builder()
.timeout(config.timeout)
.redirect(reqwest::redirect::Policy::none())
.dns_resolver(Arc::new(GuardedResolver {
allow_private: config.policy.allow_private_addresses,
}))
.user_agent(concat!("openadr-vtn/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| WebhookError::Unreachable(e.to_string()))?;
Ok(Self {
http,
config,
clock: Arc::new(SystemClock),
})
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
pub fn shared(config: WebhookConfig) -> Result<Arc<Self>, WebhookError> {
Ok(Arc::new(Self::new(config)?))
}
async fn echo_challenge(&self, callback_url: &str) -> Result<(), WebhookError> {
let url = self.check_url(callback_url)?;
let challenge = random_token();
let mut with_echo = url.clone();
with_echo.query_pairs_mut().append_pair("echo", &challenge);
let mut response = self
.http
.get(with_echo)
.send()
.await
.map_err(|e| WebhookError::Unreachable(e.to_string()))?;
if !response.status().is_success() {
return Err(WebhookError::Status {
status: response.status().as_u16(),
});
}
let mut body = Vec::with_capacity(ECHO_BODY_LIMIT);
while let Some(chunk) = response
.chunk()
.await
.map_err(|e| WebhookError::Unreachable(e.to_string()))?
{
if body.len() + chunk.len() > ECHO_BODY_LIMIT {
return Err(WebhookError::EchoFailed);
}
body.extend_from_slice(&chunk);
}
let body = String::from_utf8(body).map_err(|_| WebhookError::EchoFailed)?;
if body.trim() != challenge {
return Err(WebhookError::EchoFailed);
}
Ok(())
}
fn check_url(&self, callback_url: &str) -> Result<url::Url, WebhookError> {
Ok(self.config.policy.check_literal(callback_url)?)
}
fn sign(&self, body: &[u8]) -> Option<(String, String)> {
let key = self.config.signing_key.as_ref()?;
let at = self.clock.now();
Some((
crate::webhook::sign(key.as_bytes(), at, body),
at.as_second().to_string(),
))
}
async fn post(&self, delivery: &Delivery, attempt: u32) -> Result<(), WebhookError> {
let Some(callback_url) = delivery.route.callback_url() else {
return Err(WebhookError::NotOurs);
};
let url = self.check_url(callback_url)?;
let body = serde_json::to_vec(&delivery.notification)
.map_err(|e| WebhookError::Unreachable(e.to_string()))?;
let mut request = self
.http
.post(url)
.header(reqwest::header::CONTENT_TYPE, "application/json")
.header(ATTEMPT_HEADER, attempt.to_string())
.body(body.clone());
if let Some(token) = delivery.route.bearer_token() {
request = request.bearer_auth(token);
}
if let Some((signature, at)) = self.sign(&body) {
request = request
.header(SIGNATURE_HEADER, signature)
.header(TIMESTAMP_HEADER, at);
}
match request.send().await {
Ok(response) if response.status().is_success() => Ok(()),
Ok(response) => Err(WebhookError::Status {
status: response.status().as_u16(),
}),
Err(e) => Err(WebhookError::Unreachable(e.to_string())),
}
}
}
#[async_trait]
impl Notifier for WebhookNotifier {
fn handles(&self, channel: Channel) -> bool {
channel == Channel::Webhook
}
async fn deliver(&self, delivery: &Delivery, attempt: u32) -> Result<(), DeliveryFailure> {
match self.post(delivery, attempt).await {
Ok(()) => {
tracing::debug!(
subscription = ?delivery.subscription_id,
object = %delivery.notification.object.object_type(),
"notification delivered"
);
Ok(())
}
Err(e) => {
tracing::debug!(
subscription = ?delivery.subscription_id,
error = %e,
retriable = e.is_retriable(),
"delivery attempt failed"
);
Err(if e.is_retriable() {
DeliveryFailure::retriable(e.to_string())
} else {
DeliveryFailure::permanent(e.to_string())
})
}
}
}
async fn verify_callback(&self, callback_url: &str) -> Result<(), DeliveryFailure> {
match self.echo_challenge(callback_url).await {
Ok(()) => Ok(()),
Err(e) => Err(if e.is_retriable() {
DeliveryFailure::retriable(e.to_string())
} else {
DeliveryFailure::permanent(e.to_string())
}),
}
}
fn name(&self) -> &'static str {
"webhook"
}
}
#[derive(Debug)]
struct GuardedResolver {
allow_private: bool,
}
impl reqwest::dns::Resolve for GuardedResolver {
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
let allow_private = self.allow_private;
Box::pin(async move {
let host = name.as_str().to_string();
let resolved: Vec<std::net::SocketAddr> =
tokio::net::lookup_host((host.as_str(), 0)).await?.collect();
if resolved.is_empty() {
return Err(Box::new(CallbackRejected::Unresolvable {
host,
detail: "resolved to no addresses".into(),
})
as Box<dyn std::error::Error + Send + Sync>);
}
if !allow_private && let Some(bad) = resolved.iter().find(|a| super::is_private(a.ip()))
{
return Err(Box::new(CallbackRejected::PrivateAddress {
host: format!("{host} ({})", bad.ip()),
})
as Box<dyn std::error::Error + Send + Sync>);
}
Ok(Box::new(resolved.into_iter()) as reqwest::dns::Addrs)
})
}
}
const ECHO_BODY_LIMIT: usize = 1024;
fn random_token() -> String {
use rand::Rng as _;
let bytes: [u8; 16] = rand::rng().random();
bytes.iter().fold(String::with_capacity(32), |mut acc, b| {
use std::fmt::Write as _;
let _ = write!(acc, "{b:02x}");
acc
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_transport_re_checks_the_callback_before_using_it() {
let notifier = WebhookNotifier::new(WebhookConfig::default()).unwrap();
for url in ["http://example.com/hook", "https://localhost/hook"] {
let err = notifier.check_url(url).unwrap_err();
assert!(matches!(err, WebhookError::Rejected(_)), "{url}: {err:?}");
}
}
#[test]
fn a_signed_delivery_is_verifiable_by_the_receiver() {
let at: crate::model::Timestamp = "2026-01-01T00:00:00Z".parse().unwrap();
let with_key = |key: &str| {
WebhookNotifier::new(WebhookConfig {
signing_key: Some(key.into()),
..Default::default()
})
.unwrap()
.with_clock(Arc::new(crate::core::FixedClock::new(at)))
};
let (signature, stamp) = with_key("secret").sign(b"body").unwrap();
assert_eq!(crate::webhook::parse_timestamp(&stamp), Some(at));
crate::webhook::Signature::parse(&signature)
.unwrap()
.verify(
b"secret",
b"body",
at,
at,
crate::webhook::DEFAULT_TOLERANCE,
)
.expect("a receiver verifies what the transport signed");
assert_eq!(signature, with_key("secret").sign(b"body").unwrap().0);
assert_ne!(signature, with_key("other").sign(b"body").unwrap().0);
assert_ne!(signature, with_key("secret").sign(b"different").unwrap().0);
let unsigned = WebhookNotifier::new(WebhookConfig::default()).unwrap();
assert!(unsigned.sign(b"body").is_none());
}
#[test]
fn a_client_error_is_permanent_and_a_server_error_is_not() {
let status = |status| WebhookError::Status { status };
assert!(!status(400).is_retriable(), "a 400 will always be a 400");
assert!(!status(404).is_retriable());
assert!(status(408).is_retriable());
assert!(status(429).is_retriable());
assert!(status(500).is_retriable());
assert!(status(503).is_retriable());
assert!(WebhookError::Unreachable("refused".into()).is_retriable());
assert!(!WebhookError::Rejected(CallbackRejected::NotHttps).is_retriable());
assert!(
WebhookError::Rejected(CallbackRejected::PrivateAddress { host: "h".into() })
.is_retriable()
);
}
#[tokio::test]
async fn the_resolver_refuses_a_name_that_answers_privately() {
use reqwest::dns::Resolve as _;
use std::str::FromStr as _;
let name = || reqwest::dns::Name::from_str("localhost").unwrap();
let guarded = GuardedResolver {
allow_private: false,
};
let err = guarded
.resolve(name())
.await
.err()
.expect("a loopback answer must be refused inside the connector");
assert!(err.to_string().contains("loopback"), "{err}");
let permissive = GuardedResolver {
allow_private: true,
};
assert!(permissive.resolve(name()).await.is_ok());
}
#[test]
fn challenges_do_not_repeat() {
let a = random_token();
assert_eq!(a.len(), 32);
assert_ne!(a, random_token());
}
}