Skip to main content

adk_kernel/bus/
webhook.rs

1//! The outbound webhook sink (spec 3.2 §7.6).
2
3use 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/// One delivery's body: the Standard Webhooks payload shape, whose `data` is the record the
21/// control plane's SSE stream sends for the same event.
22#[derive(Serialize)]
23struct Payload<'a> {
24    #[serde(rename = "type")]
25    kind: &'static str,
26    timestamp: DateTime<Utc>,
27    data: &'a EventRecord,
28}
29
30/// Delivers the kernel's events to an HTTP endpoint as signed webhooks (spec 3.2 §7.6).
31///
32/// Each event the sink's [`EventFilter`] selects is `POST`ed as JSON, signed with
33/// [Standard Webhooks](adk_core::webhook) signatures — the scheme the kernel's webhook
34/// ingress verifies — through `adk-core`'s [`WebhookDelivery`]:
35///
36/// | Part | Value |
37/// |---|---|
38/// | `webhook-id` | `evt_<uuid>`, one per event and the same on every retry, so a receiver deduplicates on it |
39/// | `webhook-timestamp`, `webhook-signature` | Signed afresh for each attempt with the sink's secret |
40/// | Body | `{"type": "<event type>", "timestamp": "<RFC 3339>", "data": {"cursor": …, "at": …, "event": {…}}}`; `data` is the record `GET /api/kernel/events` streams |
41///
42/// | Concern | Behaviour |
43/// |---|---|
44/// | Selection | The [`EventFilter`]; the default leaves out `health` |
45/// | Destination | `https`, or plain `http` to this machine (`localhost`, `*.localhost`, a loopback address) only; a URL with credentials in it is refused |
46/// | Retry | The [`RetryPolicy`]: connection errors, timeouts, `408`, `425`, `429` and `5xx` are retried with exponential backoff and full jitter, honouring `Retry-After`; redirects are never followed |
47/// | Undeliverable | Any other status, or the last failed attempt, ends the event at the [`DeadLetterSink`] when one is set, and drops it with a warning otherwise |
48/// | Back-pressure | At most [`with_max_in_flight`](Self::with_max_in_flight) deliveries run at once, each on its own task; past that the bus queues the sink's events and, when its queue is full, drops `health` first and then the oldest (§7.6). The bus and the processes never wait on the receiver |
49/// | Logs | The endpoint's origin only — never its path, query or the secret |
50///
51/// Deliveries run in order with one in flight; with more, a later event may arrive before
52/// an earlier one that is being retried, and the receiver orders by `data.cursor`. A
53/// `held` event carries the held call's arguments: leave [`EventKind::Held`] out of the
54/// filter for a receiver that should not see them.
55///
56/// [`EventKind::Held`]: crate::EventKind::Held
57///
58/// # Example
59///
60/// ```rust
61/// use std::sync::Arc;
62/// use adk_core::webhook::WebhookSecret;
63/// use adk_kernel::{EventBus, EventFilter, EventKind, WebhookSink};
64///
65/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
66/// // Read the secret from the environment or a secret store, never from source.
67/// let secret = WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw")?;
68/// let sink = WebhookSink::new("https://hooks.example.com/kernel", secret.clone())?
69///     .with_filter(EventFilter::only([EventKind::Held, EventKind::Decided, EventKind::Governance]));
70/// let bus = EventBus::default();
71/// bus.add_sink(Arc::new(sink));
72/// // On a kernel: `Kernel::builder().event_sink(Arc::new(sink))`.
73///
74/// assert!(WebhookSink::new("http://hooks.example.com/kernel", secret.clone()).is_err());
75/// assert!(WebhookSink::new("http://127.0.0.1:9000/kernel", secret).is_ok());
76/// # Ok(())
77/// # }
78/// ```
79#[derive(Clone)]
80pub struct WebhookSink {
81    endpoint: WebhookEndpoint,
82    /// `scheme://host[:port]`, what the logs name; the path may carry a token.
83    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    /// How many deliveries run at once by default: one, so the receiver gets events in
103    /// order.
104    pub const DEFAULT_MAX_IN_FLIGHT: usize = 1;
105
106    /// A sink delivering to `url`, signed with `secret`, with the default [`EventFilter`],
107    /// [`RetryPolicy`] and no dead-letter sink.
108    ///
109    /// # Errors
110    ///
111    /// Returns [`KernelError::Config`] when `url` does not parse, carries credentials, or
112    /// is neither `https` nor plain `http` to a loopback host. The error names the URL's
113    /// origin only.
114    pub fn new(url: &str, secret: WebhookSecret) -> Result<Self> {
115        let parsed = check_url(url)?;
116        let delivery = WebhookDelivery::new()
117            // `check_url` admits only https and loopback http; an operator configures the URL,
118            // so a receiver on the private network is allowed over https.
119            .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    /// Delivers only the events `filter` selects.
131    #[must_use]
132    pub fn with_filter(mut self, filter: EventFilter) -> Self {
133        self.filter = filter;
134        self
135    }
136
137    /// Retries each delivery under `retry`.
138    #[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    /// Keeps each undeliverable event, with its last error, in `sink`.
145    #[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    /// Runs at most `max` deliveries at once (at least one).
152    #[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    /// The events the sink delivers.
160    pub fn filter(&self) -> &EventFilter {
161        &self.filter
162    }
163
164    /// The endpoint's origin, `scheme://host[:port]`.
165    pub fn origin(&self) -> &str {
166        &self.origin
167    }
168}
169
170#[async_trait]
171impl EventSink for WebhookSink {
172    /// Delivers `event` with cursor 0, which the bus never issues; the bus itself calls
173    /// [`emit_record`](EventSink::emit_record).
174    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        // Waiting here, not in `publish`, is what fills the bus's queue for this sink.
187        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
221/// `url` when deliveries may go to it: `https`, or plain `http` to this machine, with no
222/// credentials in it. Errors name the origin at most, as the path may carry a token.
223fn 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
246/// Whether `url` names this machine.
247fn 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}