1use std::fmt;
4use std::net::IpAddr;
5use std::sync::Arc;
6
7use adk_core::egress::EgressPolicy;
8use adk_core::webhook::WebhookSecret;
9use adk_core::webhook_delivery::{
10 DeadLetterSink, DeliveryReport, RetryPolicy, WebhookDelivery, WebhookEndpoint, WebhookMessage,
11};
12use async_trait::async_trait;
13use chrono::{DateTime, Utc};
14use serde::Serialize;
15use tokio::sync::Semaphore;
16
17use super::{EventFilter, EventRecord, EventSink, KernelEvent};
18use crate::error::{KernelError, Result};
19
20#[derive(Serialize)]
23struct Payload<'a> {
24 #[serde(rename = "type")]
25 kind: &'static str,
26 timestamp: DateTime<Utc>,
27 data: &'a EventRecord,
28}
29
30#[derive(Clone)]
80pub struct WebhookSink {
81 endpoint: WebhookEndpoint,
82 origin: String,
84 filter: EventFilter,
85 delivery: WebhookDelivery,
86 in_flight: Arc<Semaphore>,
87 max_in_flight: usize,
88}
89
90impl fmt::Debug for WebhookSink {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 f.debug_struct("WebhookSink")
93 .field("origin", &self.origin)
94 .field("filter", &self.filter)
95 .field("retry", &self.delivery.retry_policy())
96 .field("max_in_flight", &self.max_in_flight)
97 .finish_non_exhaustive()
98 }
99}
100
101impl WebhookSink {
102 pub const DEFAULT_MAX_IN_FLIGHT: usize = 1;
105
106 pub fn new(url: &str, secret: WebhookSecret) -> Result<Self> {
115 let parsed = check_url(url)?;
116 let delivery = WebhookDelivery::new()
117 .with_egress_policy(EgressPolicy::allow_private_networks());
120 Ok(Self {
121 endpoint: WebhookEndpoint::new(parsed.as_str(), secret),
122 origin: parsed.origin().ascii_serialization(),
123 filter: EventFilter::default(),
124 delivery,
125 in_flight: Arc::new(Semaphore::new(Self::DEFAULT_MAX_IN_FLIGHT)),
126 max_in_flight: Self::DEFAULT_MAX_IN_FLIGHT,
127 })
128 }
129
130 #[must_use]
132 pub fn with_filter(mut self, filter: EventFilter) -> Self {
133 self.filter = filter;
134 self
135 }
136
137 #[must_use]
139 pub fn with_retry_policy(mut self, retry: RetryPolicy) -> Self {
140 self.delivery = self.delivery.with_retry_policy(retry);
141 self
142 }
143
144 #[must_use]
146 pub fn with_dead_letter_sink(mut self, sink: Arc<dyn DeadLetterSink>) -> Self {
147 self.delivery = self.delivery.with_dead_letter_sink(sink);
148 self
149 }
150
151 #[must_use]
153 pub fn with_max_in_flight(mut self, max: usize) -> Self {
154 self.max_in_flight = max.max(1);
155 self.in_flight = Arc::new(Semaphore::new(self.max_in_flight));
156 self
157 }
158
159 pub fn filter(&self) -> &EventFilter {
161 &self.filter
162 }
163
164 pub fn origin(&self) -> &str {
166 &self.origin
167 }
168}
169
170#[async_trait]
171impl EventSink for WebhookSink {
172 async fn emit(&self, event: &KernelEvent) -> Result<()> {
175 self.emit_record(&EventRecord { cursor: 0, at: Utc::now(), event: event.clone() }).await
176 }
177
178 async fn emit_record(&self, record: &EventRecord) -> Result<()> {
179 if !self.filter.matches(&record.event) {
180 return Ok(());
181 }
182 let kind = record.event.name();
183 let id = format!("evt_{}", uuid::Uuid::new_v4().simple());
184 let payload = Payload { kind, timestamp: record.at, data: record };
185 let message = WebhookMessage::json(id, &payload)?;
186 let permit = Arc::clone(&self.in_flight).acquire_owned().await.map_err(|_| {
188 KernelError::Config { reason: "the webhook sink's delivery limit is closed".into() }
189 })?;
190 let (delivery, endpoint, origin) =
191 (self.delivery.clone(), self.endpoint.clone(), self.origin.clone());
192 let cursor = record.cursor;
193 tokio::spawn(async move {
194 let report = delivery.deliver(&endpoint, &message).await;
195 drop(permit);
196 match report {
197 DeliveryReport::Delivered { attempts, status } => tracing::debug!(
198 webhook.id = %message.id,
199 webhook.origin = %origin,
200 event.kind = kind,
201 event.cursor = cursor,
202 attempts,
203 http.status = status,
204 "kernel event delivered"
205 ),
206 DeliveryReport::DeadLettered(letter) => tracing::warn!(
207 webhook.id = %message.id,
208 webhook.origin = %origin,
209 event.kind = kind,
210 event.cursor = cursor,
211 attempts = letter.attempts,
212 http.status = letter.last_status,
213 "kernel event not delivered"
214 ),
215 }
216 });
217 Ok(())
218 }
219}
220
221fn check_url(url: &str) -> Result<reqwest::Url> {
224 let invalid =
225 |reason: String| KernelError::Config { reason: format!("webhook sink: {reason}") };
226 let parsed = reqwest::Url::parse(url)
227 .map_err(|error| invalid(format!("the URL does not parse: {error}")))?;
228 if !parsed.username().is_empty() || parsed.password().is_some() {
229 return Err(invalid(
230 "the URL carries credentials; remove them, as the signature authenticates each \
231 delivery"
232 .into(),
233 ));
234 }
235 match parsed.scheme() {
236 "https" => Ok(parsed),
237 "http" if is_loopback(&parsed) => Ok(parsed),
238 "http" => Err(invalid(format!(
239 "{} must use https; plain http is accepted on loopback only",
240 parsed.origin().ascii_serialization()
241 ))),
242 other => Err(invalid(format!("the scheme `{other}` is not allowed; use https"))),
243 }
244}
245
246fn is_loopback(url: &reqwest::Url) -> bool {
248 let host = url.host_str().unwrap_or_default();
249 let host = host.trim_start_matches('[').trim_end_matches(']');
250 host == "localhost"
251 || host.ends_with(".localhost")
252 || host.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 fn secret() -> WebhookSecret {
260 WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw").unwrap()
261 }
262
263 #[test]
264 fn urls_are_https_or_loopback_http_without_credentials() {
265 for url in [
266 "https://hooks.example.com/kernel",
267 "https://10.0.0.7/kernel",
268 "http://127.0.0.1:9000/kernel",
269 "http://[::1]:9000/kernel",
270 "http://localhost:9000/kernel",
271 "http://kernel.localhost/hooks",
272 ] {
273 assert!(WebhookSink::new(url, secret()).is_ok(), "{url}");
274 }
275 for (url, reason) in [
276 ("http://hooks.example.com/kernel", "must use https"),
277 ("http://10.0.0.7/kernel", "must use https"),
278 ("ftp://hooks.example.com/kernel", "scheme `ftp`"),
279 ("https://user:pass@hooks.example.com/kernel", "carries credentials"),
280 ("https://token@hooks.example.com/kernel", "carries credentials"),
281 ("not a url", "does not parse"),
282 ] {
283 let error = WebhookSink::new(url, secret()).unwrap_err().to_string();
284 assert!(error.contains(reason), "{url}: {error}");
285 assert!(!error.contains("pass") && !error.contains("/kernel"), "{url}: {error}");
286 }
287 }
288
289 #[test]
290 fn the_debug_form_names_the_origin_only() {
291 let sink = WebhookSink::new("https://hooks.example.com/T0K3N?key=s3cr3t", secret())
292 .unwrap()
293 .with_max_in_flight(0);
294 let debug = format!("{sink:?}");
295 assert!(debug.contains("https://hooks.example.com"), "{debug}");
296 for hidden in ["T0K3N", "s3cr3t", "MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"] {
297 assert!(!debug.contains(hidden), "{debug}");
298 }
299 assert_eq!(sink.max_in_flight, 1, "at least one delivery runs");
300 assert_eq!(sink.origin(), "https://hooks.example.com");
301 }
302}