adk_agent/ambient/webhook_trigger.rs
1use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
2use async_trait::async_trait;
3use futures::stream::BoxStream;
4use std::net::{IpAddr, Ipv4Addr, SocketAddr};
5use std::sync::Arc;
6use tokio::sync::mpsc;
7use tokio_util::sync::CancellationToken;
8
9use super::event_source::{EventSource, TriggerEvent};
10
11/// Decides whether an inbound webhook request is allowed to trigger agent work.
12///
13/// A webhook that reaches an agent is a remote code path into application logic, so the
14/// decision needs to be explicit. Implement this to check a provider signature, validate a
15/// bearer token, or consult an allowlist, and return the principal the request speaks for.
16///
17/// # Example
18///
19/// ```rust
20/// use adk_agent::ambient::{WebhookRequest, WebhookVerifier};
21///
22/// #[derive(Debug)]
23/// struct SharedToken(String);
24///
25/// impl WebhookVerifier for SharedToken {
26/// fn verify(&self, request: &WebhookRequest<'_>) -> Result<String, String> {
27/// match request.header("authorization") {
28/// Some(value) if value == format!("Bearer {}", self.0) => Ok("ci".to_string()),
29/// Some(_) => Err("token mismatch".to_string()),
30/// None => Err("missing authorization header".to_string()),
31/// }
32/// }
33/// }
34/// ```
35pub trait WebhookVerifier: Send + Sync + std::fmt::Debug {
36 /// Returns the verified principal, or the reason the request is rejected.
37 ///
38 /// The reason is logged, never returned to the caller: a rejected request receives a
39 /// bare `401` so it cannot be used to probe which part of a credential was wrong.
40 fn verify(&self, request: &WebhookRequest<'_>) -> std::result::Result<String, String>;
41}
42
43/// Verifies [Standard Webhooks](adk_core::webhook) signatures and refuses replays.
44///
45/// Checks the `webhook-timestamp` against the tolerance, the `webhook-signature` against
46/// every configured secret, and remembers each accepted `webhook-id` for twice the
47/// tolerance, so a captured delivery cannot be replayed while its timestamp is still
48/// fresh. Every accepted request speaks for `principal`.
49///
50/// # Example
51///
52/// ```rust
53/// use std::sync::Arc;
54/// use adk_agent::ambient::{StandardWebhookVerifier, WebhookTrigger};
55/// use adk_core::webhook::{WebhookSecret, WebhookVerifier};
56///
57/// let secret = WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw")?;
58/// let trigger = WebhookTrigger::new(8080, "/hooks/ci")
59/// .with_verifier(Arc::new(StandardWebhookVerifier::new("ci", WebhookVerifier::new(secret))));
60/// # let _ = trigger;
61/// # Ok::<(), adk_core::webhook::WebhookError>(())
62/// ```
63#[derive(Debug)]
64pub struct StandardWebhookVerifier {
65 principal: String,
66 verifier: adk_core::webhook::WebhookVerifier,
67 replays: adk_core::webhook::InMemoryWebhookReplayGuard,
68}
69
70impl StandardWebhookVerifier {
71 /// Creates a verifier whose accepted requests speak for `principal`.
72 pub fn new(principal: impl Into<String>, verifier: adk_core::webhook::WebhookVerifier) -> Self {
73 Self {
74 principal: principal.into(),
75 verifier,
76 replays: adk_core::webhook::InMemoryWebhookReplayGuard::new(),
77 }
78 }
79}
80
81impl WebhookVerifier for StandardWebhookVerifier {
82 fn verify(&self, request: &WebhookRequest<'_>) -> std::result::Result<String, String> {
83 let headers = adk_core::webhook::WebhookHeaders::from_lookup(|name| request.header(name))
84 .map_err(|error| error.to_string())?;
85 let verified =
86 self.verifier.verify(&headers, request.body()).map_err(|error| error.to_string())?;
87 let window = adk_core::webhook::replay_window(self.verifier.tolerance());
88 let keep_until = chrono::Utc::now()
89 + chrono::Duration::from_std(window).unwrap_or(chrono::Duration::MAX);
90 if !self.replays.record(&verified.id, keep_until) {
91 return Err(adk_core::webhook::WebhookError::Replayed(verified.id).to_string());
92 }
93 Ok(self.principal.clone())
94 }
95}
96
97/// An inbound webhook request, as presented to a [`WebhookVerifier`].
98pub struct WebhookRequest<'a> {
99 headers: &'a axum::http::HeaderMap,
100 body: &'a [u8],
101}
102
103impl<'a> WebhookRequest<'a> {
104 /// A header value as UTF-8, or `None` when absent or not UTF-8.
105 pub fn header(&self, name: &str) -> Option<&str> {
106 self.headers.get(name).and_then(|value| value.to_str().ok())
107 }
108
109 /// The raw request body.
110 ///
111 /// Signature schemes are computed over the exact bytes received, so this is deliberately
112 /// the unparsed body.
113 pub fn body(&self) -> &'a [u8] {
114 self.body
115 }
116}
117
118impl std::fmt::Debug for WebhookRequest<'_> {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 // Headers and body carry credentials and caller data; report only shape.
121 f.debug_struct("WebhookRequest")
122 .field("header_count", &self.headers.len())
123 .field("body_bytes", &self.body.len())
124 .finish()
125 }
126}
127
128/// Emits trigger events when authorized HTTP POST requests arrive on the configured path.
129///
130/// Binds loopback by default. Serving a non-loopback address requires a
131/// [`WebhookVerifier`], because a reachable unauthenticated webhook lets any caller start
132/// application-defined agent work.
133///
134/// # Example
135///
136/// ```rust
137/// use adk_agent::ambient::WebhookTrigger;
138///
139/// // Local development: loopback, no verifier required.
140/// let trigger = WebhookTrigger::new(8080, "/webhook");
141/// assert!(trigger.bind_address().ip().is_loopback());
142/// ```
143pub struct WebhookTrigger {
144 path: String,
145 name: String,
146 bind_address: SocketAddr,
147 verifier: Option<Arc<dyn WebhookVerifier>>,
148 accept_non_json: bool,
149 max_body_bytes: usize,
150}
151
152/// Bodies above this size are rejected before parsing.
153const DEFAULT_MAX_BODY_BYTES: usize = 1024 * 1024;
154
155impl WebhookTrigger {
156 /// Creates a webhook trigger on loopback at the given port and path.
157 ///
158 /// The path is prefixed with `/` when it is not already.
159 pub fn new(port: u16, path: &str) -> Self {
160 let path = if path.starts_with('/') { path.to_string() } else { format!("/{path}") };
161
162 Self {
163 name: format!("webhook:{path}"),
164 path,
165 // Loopback, not `0.0.0.0`: binding every interface is a decision the caller
166 // should have to make, alongside supplying a verifier.
167 bind_address: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
168 verifier: None,
169 accept_non_json: false,
170 max_body_bytes: DEFAULT_MAX_BODY_BYTES,
171 }
172 }
173
174 /// Serves on `address` instead of loopback.
175 ///
176 /// A non-loopback address requires [`WebhookTrigger::with_verifier`]; without one,
177 /// [`EventSource::subscribe`] fails rather than exposing an open trigger.
178 pub fn with_bind_address(mut self, address: SocketAddr) -> Self {
179 self.bind_address = address;
180 self
181 }
182
183 /// Requires every request to be authorized by `verifier`.
184 pub fn with_verifier(mut self, verifier: Arc<dyn WebhookVerifier>) -> Self {
185 self.verifier = Some(verifier);
186 self
187 }
188
189 /// Accepts bodies that are not valid JSON, wrapping them as a JSON string.
190 ///
191 /// Off by default. Coercing a malformed body into a string produces a trigger event
192 /// indistinguishable from a deliberate one, so unparseable input is rejected with `400`
193 /// unless a caller opts in.
194 pub fn accept_non_json(mut self) -> Self {
195 self.accept_non_json = true;
196 self
197 }
198
199 /// Sets the largest accepted body, in bytes. Defaults to 1 MiB.
200 pub fn with_max_body_bytes(mut self, max_body_bytes: usize) -> Self {
201 self.max_body_bytes = max_body_bytes;
202 self
203 }
204
205 /// The address this trigger serves on.
206 pub fn bind_address(&self) -> SocketAddr {
207 self.bind_address
208 }
209}
210
211#[async_trait]
212impl EventSource for WebhookTrigger {
213 fn name(&self) -> &str {
214 &self.name
215 }
216
217 async fn subscribe(&self) -> Result<BoxStream<'static, TriggerEvent>> {
218 // Fail closed. An exposed webhook with no verifier is a remote trigger for anyone
219 // who can reach the port, and refusing at subscribe time is the only point where
220 // the mistake is still cheap.
221 if !self.bind_address.ip().is_loopback() && self.verifier.is_none() {
222 return Err(AdkError::new(
223 ErrorComponent::Agent,
224 ErrorCategory::InvalidInput,
225 "agent.ambient.webhook_unauthenticated",
226 format!(
227 "WebhookTrigger is set to serve {}, which is reachable beyond this host, \
228 with no verifier. Any caller able to reach the port could start agent \
229 work. Call `with_verifier`, or leave the default loopback bind.",
230 self.bind_address
231 ),
232 ));
233 }
234
235 let (tx, mut rx) = mpsc::channel::<TriggerEvent>(256);
236 let source_name = self.name.clone();
237 let path = self.path.clone();
238 let bind_address = self.bind_address;
239 let verifier = self.verifier.clone();
240 let accept_non_json = self.accept_non_json;
241 let max_body_bytes = self.max_body_bytes;
242
243 // Bind before spawning so a port conflict is reported to the caller instead of
244 // vanishing into a background log line.
245 let listener = tokio::net::TcpListener::bind(bind_address).await.map_err(|e| {
246 AdkError::new(
247 ErrorComponent::Agent,
248 ErrorCategory::Unavailable,
249 "agent.ambient.webhook_bind_failed",
250 format!("WebhookTrigger could not bind {bind_address}: {e}"),
251 )
252 })?;
253
254 // The server's lifetime is tied to the stream the caller holds. Dropping the stream
255 // fires this token, `axum` shuts down gracefully, and the port is released — before,
256 // the server stayed bound after the consumer went away, so a restart on the same
257 // port failed while requests kept being accepted and discarded.
258 let shutdown = CancellationToken::new();
259 let server_shutdown = shutdown.clone();
260
261 tokio::spawn(async move {
262 use axum::Router;
263 use axum::body::Bytes;
264 use axum::http::{HeaderMap, StatusCode};
265 use axum::routing::post;
266
267 let app = Router::new().route(
268 &path,
269 post(move |headers: HeaderMap, body: Bytes| {
270 let tx = tx.clone();
271 let source = source_name.clone();
272 let verifier = verifier.clone();
273 async move {
274 if body.len() > max_body_bytes {
275 tracing::warn!(
276 body.bytes = body.len(),
277 limit = max_body_bytes,
278 "webhook body rejected as oversized"
279 );
280 return StatusCode::PAYLOAD_TOO_LARGE;
281 }
282
283 let principal = match &verifier {
284 Some(verifier) => {
285 let request =
286 WebhookRequest { headers: &headers, body: body.as_ref() };
287 match verifier.verify(&request) {
288 Ok(principal) => Some(principal),
289 Err(reason) => {
290 // Logged, not returned: the response must not reveal
291 // which part of a credential failed.
292 tracing::warn!(
293 reason = %reason,
294 "webhook request rejected by verifier"
295 );
296 return StatusCode::UNAUTHORIZED;
297 }
298 }
299 }
300 None => None,
301 };
302
303 let payload = match serde_json::from_slice::<serde_json::Value>(&body) {
304 Ok(value) => value,
305 Err(_) if accept_non_json => serde_json::Value::String(
306 String::from_utf8_lossy(&body).to_string(),
307 ),
308 Err(e) => {
309 tracing::warn!(
310 error = %e,
311 "webhook body rejected as malformed JSON"
312 );
313 return StatusCode::BAD_REQUEST;
314 }
315 };
316
317 let event = TriggerEvent { source, payload, principal };
318
319 if tx.send(event).await.is_err() {
320 tracing::debug!("webhook subscriber dropped, refusing the request");
321 return StatusCode::SERVICE_UNAVAILABLE;
322 }
323
324 StatusCode::OK
325 }
326 }),
327 );
328
329 tracing::info!(address = %bind_address, path = %path, "webhook trigger listening");
330
331 let served = axum::serve(listener, app)
332 .with_graceful_shutdown(async move { server_shutdown.cancelled().await })
333 .await;
334
335 if let Err(e) = served {
336 tracing::warn!(error = %e, "webhook trigger server error");
337 }
338 tracing::debug!(address = %bind_address, "webhook trigger stopped");
339 });
340
341 // Cancels on drop, which is what releases the port.
342 let guard = shutdown.drop_guard();
343 let stream = async_stream::stream! {
344 let _guard = guard;
345 while let Some(event) = rx.recv().await {
346 yield event;
347 }
348 };
349
350 Ok(Box::pin(stream))
351 }
352}
353
354impl std::fmt::Debug for WebhookTrigger {
355 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
356 f.debug_struct("WebhookTrigger")
357 .field("bind_address", &self.bind_address)
358 .field("path", &self.path)
359 .field("verifier", &self.verifier)
360 .field("accept_non_json", &self.accept_non_json)
361 .field("max_body_bytes", &self.max_body_bytes)
362 .finish()
363 }
364}