Skip to main content

adk_server/webhooks/
ingress.rs

1//! Signed inbound webhooks that wake agents: `POST /hooks/{name}` enqueues a durable run.
2//!
3//! Each [`WebhookHook`] names a [Standard Webhooks](adk_core::webhook) secret and how a
4//! verified delivery becomes a [`NewRun`]. [`WebhookIngress`] serves the hooks:
5//!
6//! | Step | Refusal | Status |
7//! |------|---------|--------|
8//! | Look up the hook by name | Unknown hook | `404` |
9//! | Verify the signature and timestamp, or the hook's [forge signature](super::forge) | Missing, malformed, expired, or mismatched | `401` (reason logged, never returned) |
10//! | Check the kill switch | Frozen, or a replicated control that is stale | `503` with `Retry-After` |
11//! | Check the hook's pending-run cap | `max_pending` unfinished runs from this hook | `429` with `Retry-After` |
12//! | Parse the body and render the mapping | Not JSON, or a template that renders an empty key | `422` |
13//! | Enqueue with idempotency key `hook:{name}:{webhook-id}` | Store unreachable | `503` with `Retry-After` |
14//! | | Rejected by `OnConflict::Reject` | `409` with `blockingRunId` |
15//!
16//! A new run answers `202 Accepted`; a redelivery of a `webhook-id` that already has a
17//! run answers `200 OK` with that run, so a sender's retry never creates a second run.
18//! Bodies are `{"runId", "state", "duplicate"}` in camelCase.
19//!
20//! Every run a hook creates acts for its user as a service
21//! ([`NewRun::with_service_subject`]), so its audit records name a service, not a person.
22//!
23//! The run executes when a [`DurableWorker`](crate::background::DurableWorker) (feature
24//! `background`) claims it from the same [`DurableRunStore`] — the worker that runs every
25//! other durable run, under the runner's budget, policy, and kill switch. With a
26//! [`GovernanceControl::mirrored`] control, a freeze written by any replica, or a mirror
27//! that has gone stale, refuses deliveries on every replica.
28//!
29//! # Example
30//!
31//! ```rust
32//! use std::sync::Arc;
33//! use adk_core::run_store::{InMemoryRunStore, OnConflict};
34//! use adk_core::webhook::{WebhookSecret, WebhookVerifier};
35//! use adk_server::webhooks::{WebhookHook, WebhookIngress};
36//! use serde_json::json;
37//!
38//! let secret = WebhookSecret::from_base64("whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw")?;
39//! let ingress = WebhookIngress::new(Arc::new(InMemoryRunStore::new())).with_hook(
40//!     WebhookHook::new("github", WebhookVerifier::new(secret), "triage", "triage_agent")
41//!         .with_input_template(json!({"text": "Triage issue #{{/payload/issue/number}}: {{/payload/issue/title}}"}))
42//!         .with_concurrency_key("repo:{{/payload/repository/id}}", OnConflict::Enqueue)
43//!         .with_max_pending(100),
44//! );
45//! let router = adk_server::webhooks::webhook_ingress_router(ingress);
46//! # let _ = router;
47//! # Ok::<(), Box<dyn std::error::Error>>(())
48//! ```
49
50use std::collections::HashMap;
51use std::sync::Arc;
52use std::time::Duration;
53
54use adk_core::GovernanceControl;
55use adk_core::run_store::{DurableRunStore, Enqueued, NewRun, OnConflict, RunFilter, RunState};
56use adk_core::webhook::{VerifiedWebhook, WebhookHeaders, WebhookVerifier};
57use axum::Json;
58use axum::Router;
59use axum::body::Bytes;
60use axum::extract::{DefaultBodyLimit, Path, State};
61use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
62use axum::response::{IntoResponse, Response};
63use axum::routing::post;
64use serde::Serialize;
65use serde_json::{Value, json};
66
67/// Largest accepted webhook body.
68pub const DEFAULT_HOOK_BODY_LIMIT: usize = 1024 * 1024;
69
70/// A verified delivery, as a custom mapper sees it.
71#[derive(Debug, Clone, Copy)]
72pub struct HookDelivery<'a> {
73    /// The hook's name.
74    pub hook: &'a str,
75    /// The verified `webhook-id` and signing time.
76    pub webhook: &'a VerifiedWebhook,
77    /// The parsed JSON body.
78    pub payload: &'a Value,
79}
80
81type HookMapper = Arc<dyn Fn(&HookDelivery<'_>) -> adk_core::Result<NewRun> + Send + Sync>;
82
83/// One inbound webhook: its secret and the run each delivery enqueues.
84///
85/// Templates are JSON values. A string that is exactly `{{/json/pointer}}` becomes the
86/// value at that pointer; a string that contains `{{/json/pointer}}` placeholders has
87/// each replaced by the value as text. Pointers resolve against
88/// `{"payload": <body>, "webhook": {"id", "timestamp"}, "hook": {"name"}}`.
89///
90/// In the input template a missing value renders as `null` (whole-string placeholder)
91/// or empty text. In the user, session, and concurrency-key templates a missing value
92/// refuses the delivery with `422`, so deliveries that lack the field never share a key.
93#[derive(Clone)]
94pub struct WebhookHook {
95    name: String,
96    verifier: HookAuth,
97    queue: String,
98    app_name: String,
99    target: String,
100    user_id: String,
101    session_id: Option<String>,
102    input: Option<Value>,
103    concurrency_key: Option<(String, OnConflict)>,
104    max_attempts: u32,
105    max_pending: Option<usize>,
106    mapper: Option<HookMapper>,
107}
108
109impl std::fmt::Debug for WebhookHook {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.debug_struct("WebhookHook")
112            .field("name", &self.name)
113            .field("queue", &self.queue)
114            .field("app_name", &self.app_name)
115            .field("target", &self.target)
116            .field("max_pending", &self.max_pending)
117            .finish_non_exhaustive()
118    }
119}
120
121/// How a hook authenticates its deliveries.
122#[derive(Clone)]
123enum HookAuth {
124    Standard(WebhookVerifier),
125    Forge(super::forge::ForgeSignature),
126}
127
128impl WebhookHook {
129    /// Creates a hook served at `/hooks/{name}` that authenticates its deliveries with a
130    /// forge's push signature instead of Standard Webhooks (spec 3.5 §7.8.2 "Files and
131    /// git"); otherwise as [`new`](Self::new).
132    ///
133    /// # Example
134    ///
135    /// ```rust
136    /// use adk_server::webhooks::{ForgeSecret, ForgeSignature, WebhookHook};
137    ///
138    /// let secret = ForgeSecret::new("a shared secret").unwrap();
139    /// let hook = WebhookHook::forge("github", ForgeSignature::GitHub(secret), "site", "website.repository.push");
140    /// assert_eq!(hook.name(), "github");
141    /// ```
142    pub fn forge(
143        name: impl Into<String>,
144        signature: super::forge::ForgeSignature,
145        app_name: impl Into<String>,
146        target: impl Into<String>,
147    ) -> Self {
148        Self::with_auth(name, HookAuth::Forge(signature), app_name, target)
149    }
150
151    /// Creates a hook served at `/hooks/{name}` that enqueues runs of `target` in
152    /// `app_name` on the `default` queue, as user `webhook:{name}`, with the body as input.
153    pub fn new(
154        name: impl Into<String>,
155        verifier: WebhookVerifier,
156        app_name: impl Into<String>,
157        target: impl Into<String>,
158    ) -> Self {
159        Self::with_auth(name, HookAuth::Standard(verifier), app_name, target)
160    }
161
162    fn with_auth(
163        name: impl Into<String>,
164        verifier: HookAuth,
165        app_name: impl Into<String>,
166        target: impl Into<String>,
167    ) -> Self {
168        let name = name.into();
169        Self {
170            user_id: format!("webhook:{name}"),
171            name,
172            verifier,
173            queue: "default".to_string(),
174            app_name: app_name.into(),
175            target: target.into(),
176            session_id: None,
177            input: None,
178            concurrency_key: None,
179            max_attempts: NewRun::DEFAULT_MAX_ATTEMPTS,
180            max_pending: None,
181            mapper: None,
182        }
183    }
184
185    /// The hook's name.
186    pub fn name(&self) -> &str {
187        &self.name
188    }
189
190    /// Sets the queue runs are enqueued on.
191    pub fn with_queue(mut self, queue: impl Into<String>) -> Self {
192        self.queue = queue.into();
193        self
194    }
195
196    /// Sets the user template.
197    pub fn with_user_id(mut self, template: impl Into<String>) -> Self {
198        self.user_id = template.into();
199        self
200    }
201
202    /// Continues the session the template names instead of starting a new one per run.
203    pub fn with_session_id(mut self, template: impl Into<String>) -> Self {
204        self.session_id = Some(template.into());
205        self
206    }
207
208    /// Sets the input template; without one the body is the input.
209    pub fn with_input_template(mut self, template: Value) -> Self {
210        self.input = Some(template);
211        self
212    }
213
214    /// Runs sharing the rendered key run one at a time; `on_conflict` decides what a
215    /// delivery does while one is unfinished.
216    pub fn with_concurrency_key(
217        mut self,
218        template: impl Into<String>,
219        on_conflict: OnConflict,
220    ) -> Self {
221        self.concurrency_key = Some((template.into(), on_conflict));
222        self
223    }
224
225    /// Sets the most attempts each run may take.
226    pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
227        self.max_attempts = max_attempts;
228        self
229    }
230
231    /// Answers `429` while this many runs from this hook are unfinished.
232    pub fn with_max_pending(mut self, max_pending: usize) -> Self {
233        self.max_pending = Some(max_pending);
234        self
235    }
236
237    /// Replaces the templates with code. The idempotency key is still set from the
238    /// `webhook-id`, overriding any key the mapper sets.
239    pub fn with_mapper(
240        mut self,
241        mapper: impl Fn(&HookDelivery<'_>) -> adk_core::Result<NewRun> + Send + Sync + 'static,
242    ) -> Self {
243        self.mapper = Some(Arc::new(mapper));
244        self
245    }
246
247    /// The idempotency key of the run a delivery creates.
248    ///
249    /// # Example
250    ///
251    /// ```rust
252    /// assert_eq!(adk_server::webhooks::WebhookHook::idempotency_key("github", "msg_1"), "hook:github:msg_1");
253    /// ```
254    pub fn idempotency_key(hook: &str, webhook_id: &str) -> String {
255        format!("hook:{hook}:{webhook_id}")
256    }
257
258    fn map(&self, delivery: &HookDelivery<'_>) -> Result<NewRun, String> {
259        let mut run = match &self.mapper {
260            Some(mapper) => mapper(delivery).map_err(|error| error.message.clone())?,
261            None => {
262                let context = json!({
263                    "payload": delivery.payload,
264                    "webhook": {
265                        "id": delivery.webhook.id,
266                        "timestamp": delivery.webhook.timestamp.to_rfc3339(),
267                    },
268                    "hook": { "name": self.name },
269                });
270                let text = |field: &str, template: &str| {
271                    let rendered = render_key(template, &context)
272                        .map_err(|reason| format!("{field} template `{template}`: {reason}"))?;
273                    if rendered.trim().is_empty() {
274                        Err(format!("{field} template `{template}` rendered empty"))
275                    } else {
276                        Ok(rendered)
277                    }
278                };
279                let input = match &self.input {
280                    Some(template) => render(template, &context),
281                    None => delivery.payload.clone(),
282                };
283                let mut run = NewRun::new(
284                    self.queue.clone(),
285                    self.app_name.clone(),
286                    text("userId", &self.user_id)?,
287                    self.target.clone(),
288                    input,
289                )
290                .with_max_attempts(self.max_attempts);
291                if let Some(template) = &self.session_id {
292                    run = run.with_session_id(text("sessionId", template)?);
293                }
294                if let Some((template, on_conflict)) = &self.concurrency_key {
295                    run = run.with_concurrency_key(text("concurrencyKey", template)?, *on_conflict);
296                }
297                run
298            }
299        };
300        run.idempotency_key = Some(Self::idempotency_key(&self.name, &delivery.webhook.id));
301        run.validate().map_err(|error| error.message)?;
302        Ok(run.with_service_subject())
303    }
304}
305
306/// Renders a template value; see [`WebhookHook`].
307fn render(template: &Value, context: &Value) -> Value {
308    match template {
309        Value::String(text) => {
310            let trimmed = text.trim();
311            if let Some(pointer) =
312                trimmed.strip_prefix("{{").and_then(|rest| rest.strip_suffix("}}"))
313                && !pointer.contains("{{")
314            {
315                return context.pointer(pointer.trim()).cloned().unwrap_or(Value::Null);
316            }
317            Value::String(render_text(text, context))
318        }
319        Value::Array(items) => {
320            Value::Array(items.iter().map(|item| render(item, context)).collect())
321        }
322        Value::Object(map) => Value::Object(
323            map.iter().map(|(key, value)| (key.clone(), render(value, context))).collect(),
324        ),
325        other => other.clone(),
326    }
327}
328
329/// Replaces each `{{/pointer}}` in `template` with the pointed value as text; a missing
330/// or null value renders empty.
331fn render_text(template: &str, context: &Value) -> String {
332    render_placeholders(template, context, false).unwrap_or_default()
333}
334
335/// Like [`render_text`], but a missing or null value is an error, so deliveries that lack
336/// the field never share a key.
337fn render_key(template: &str, context: &Value) -> Result<String, String> {
338    render_placeholders(template, context, true)
339}
340
341fn render_placeholders(template: &str, context: &Value, strict: bool) -> Result<String, String> {
342    let mut out = String::with_capacity(template.len());
343    let mut rest = template;
344    while let Some(start) = rest.find("{{") {
345        let Some(len) = rest[start + 2..].find("}}") else { break };
346        out.push_str(&rest[..start]);
347        let pointer = rest[start + 2..start + 2 + len].trim();
348        match context.pointer(pointer) {
349            Some(Value::String(text)) => out.push_str(text),
350            Some(Value::Null) | None if strict => {
351                return Err(format!("`{pointer}` is missing from the delivery"));
352            }
353            Some(Value::Null) | None => {}
354            Some(other) => out.push_str(&other.to_string()),
355        }
356        rest = &rest[start + 2 + len + 2..];
357    }
358    out.push_str(rest);
359    Ok(out)
360}
361
362/// The webhook endpoints and the run store they enqueue into.
363#[derive(Clone)]
364pub struct WebhookIngress {
365    store: Arc<dyn DurableRunStore>,
366    hooks: Arc<HashMap<String, WebhookHook>>,
367    governance: Option<GovernanceControl>,
368    retry_after: Duration,
369    body_limit: usize,
370}
371
372impl std::fmt::Debug for WebhookIngress {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        f.debug_struct("WebhookIngress")
375            .field("hooks", &self.hooks.keys().collect::<Vec<_>>())
376            .field("retry_after", &self.retry_after)
377            .field("body_limit", &self.body_limit)
378            .finish_non_exhaustive()
379    }
380}
381
382impl WebhookIngress {
383    /// Creates an ingress with no hooks over `store`.
384    pub fn new(store: Arc<dyn DurableRunStore>) -> Self {
385        Self {
386            store,
387            hooks: Arc::new(HashMap::new()),
388            governance: None,
389            retry_after: Duration::from_secs(30),
390            body_limit: DEFAULT_HOOK_BODY_LIMIT,
391        }
392    }
393
394    /// Adds a hook, replacing one with the same name.
395    pub fn with_hook(mut self, hook: WebhookHook) -> Self {
396        Arc::make_mut(&mut self.hooks).insert(hook.name.clone(), hook);
397        self
398    }
399
400    /// Sets the kill switch deliveries are checked against.
401    ///
402    /// [`ServerBuilder::with_webhook_ingress`](crate::ServerBuilder::with_webhook_ingress)
403    /// installs [`ServerConfig::governance`](crate::ServerConfig::governance) when none
404    /// is set here.
405    pub fn with_governance(mut self, governance: GovernanceControl) -> Self {
406        self.governance = Some(governance);
407        self
408    }
409
410    /// Sets the `Retry-After` sent with `429` and `503` answers.
411    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
412        self.retry_after = retry_after;
413        self
414    }
415
416    /// Sets the largest accepted body.
417    pub fn with_body_limit(mut self, bytes: usize) -> Self {
418        self.body_limit = bytes;
419        self
420    }
421
422    pub(crate) fn has_governance(&self) -> bool {
423        self.governance.is_some()
424    }
425
426    /// The run store deliveries enqueue into.
427    pub fn store(&self) -> &Arc<dyn DurableRunStore> {
428        &self.store
429    }
430
431    /// Unfinished runs this hook created.
432    async fn pending(
433        &self,
434        hook: &WebhookHook,
435    ) -> adk_core::Result<Vec<adk_core::run_store::RunRecord>> {
436        let prefix = format!("hook:{}:", hook.name);
437        let unfinished = self
438            .store
439            .list(RunFilter::default().queue(hook.queue.clone()).states([
440                RunState::Queued,
441                RunState::Running,
442                RunState::Waiting,
443            ]))
444            .await?;
445        Ok(unfinished
446            .into_iter()
447            .filter(|run| {
448                run.idempotency_key.as_deref().is_some_and(|key| key.starts_with(&prefix))
449            })
450            .collect())
451    }
452
453    fn retry_later(&self, status: StatusCode, code: &str, message: String) -> Response {
454        let mut response =
455            (status, Json(json!({"error": code, "message": message}))).into_response();
456        if let Ok(value) = HeaderValue::from_str(&self.retry_after.as_secs().max(1).to_string()) {
457            response.headers_mut().insert(header::RETRY_AFTER, value);
458        }
459        response
460    }
461}
462
463/// A run accepted for a delivery.
464#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
465#[serde(rename_all = "camelCase")]
466pub struct HookAccepted {
467    /// The run's identifier.
468    pub run_id: String,
469    /// The run's state.
470    pub state: RunState,
471    /// Whether the delivery was a redelivery of one that already has this run.
472    pub duplicate: bool,
473}
474
475async fn receive(
476    State(ingress): State<WebhookIngress>,
477    Path(name): Path<String>,
478    headers: HeaderMap,
479    body: Bytes,
480) -> Response {
481    let Some(hook) = ingress.hooks.get(&name) else {
482        return (StatusCode::NOT_FOUND, Json(json!({"error": "hook.not_found"}))).into_response();
483    };
484    let lookup = |name: &'static str| headers.get(name).and_then(|v| v.to_str().ok());
485    let verified = match &hook.verifier {
486        HookAuth::Standard(verifier) => {
487            WebhookHeaders::from_lookup(lookup).and_then(|parsed| verifier.verify(&parsed, &body))
488        }
489        HookAuth::Forge(forge) => forge.verify(lookup, &body),
490    };
491    let verified = match verified {
492        Ok(verified) => verified,
493        Err(error) => {
494            tracing::warn!(hook.name = %name, error.code = error.code(), error = %error, "webhook rejected");
495            return (StatusCode::UNAUTHORIZED, Json(json!({"error": "unauthorized"})))
496                .into_response();
497        }
498    };
499    if let Some(governance) = &ingress.governance
500        && let Err(error) = governance.check()
501    {
502        tracing::info!(hook.name = %name, webhook.id = %verified.id, error.code = %error.code, "webhook refused by governance");
503        return ingress.retry_later(StatusCode::SERVICE_UNAVAILABLE, error.code, error.message);
504    }
505    if let Some(max_pending) = hook.max_pending {
506        match ingress.pending(hook).await {
507            Ok(pending) if pending.len() >= max_pending => {
508                // A redelivery of a message whose run is still pending is answered, not throttled.
509                let key = WebhookHook::idempotency_key(&hook.name, &verified.id);
510                if let Some(run) =
511                    pending.iter().find(|run| run.idempotency_key.as_deref() == Some(key.as_str()))
512                {
513                    return (
514                        StatusCode::OK,
515                        Json(HookAccepted {
516                            run_id: run.run_id.clone(),
517                            state: run.state,
518                            duplicate: true,
519                        }),
520                    )
521                        .into_response();
522                }
523                return ingress.retry_later(
524                    StatusCode::TOO_MANY_REQUESTS,
525                    "hook.max_pending",
526                    format!(
527                        "hook '{name}' has {} unfinished runs (max {max_pending})",
528                        pending.len()
529                    ),
530                );
531            }
532            Ok(_) => {}
533            Err(error) => {
534                return ingress.retry_later(
535                    StatusCode::SERVICE_UNAVAILABLE,
536                    error.code,
537                    error.message,
538                );
539            }
540        }
541    }
542    let payload: Value = match serde_json::from_slice(&body) {
543        Ok(payload) => payload,
544        Err(error) => {
545            return (
546                StatusCode::UNPROCESSABLE_ENTITY,
547                Json(json!({"error": "hook.invalid_body", "message": format!("body is not JSON: {error}")})),
548            )
549                .into_response();
550        }
551    };
552    let delivery = HookDelivery { hook: &hook.name, webhook: &verified, payload: &payload };
553    let run = match hook.map(&delivery) {
554        Ok(run) => run,
555        Err(message) => {
556            return (
557                StatusCode::UNPROCESSABLE_ENTITY,
558                Json(json!({"error": "hook.mapping_failed", "message": message})),
559            )
560                .into_response();
561        }
562    };
563    match ingress.store.enqueue(run).await {
564        Ok(Enqueued::Created(record)) => {
565            tracing::info!(hook.name = %name, webhook.id = %verified.id, run.id = %record.run_id, "webhook woke a run");
566            (
567                StatusCode::ACCEPTED,
568                Json(HookAccepted { run_id: record.run_id, state: record.state, duplicate: false }),
569            )
570                .into_response()
571        }
572        Ok(Enqueued::Existing(record)) => {
573            tracing::info!(hook.name = %name, webhook.id = %verified.id, run.id = %record.run_id, "webhook redelivery matched an existing run");
574            (
575                StatusCode::OK,
576                Json(HookAccepted { run_id: record.run_id, state: record.state, duplicate: true }),
577            )
578                .into_response()
579        }
580        Ok(Enqueued::Rejected { blocking_run_id }) => (
581            StatusCode::CONFLICT,
582            Json(json!({"error": "hook.concurrency_conflict", "blockingRunId": blocking_run_id})),
583        )
584            .into_response(),
585        Err(error) => {
586            tracing::warn!(hook.name = %name, webhook.id = %verified.id, error = %error, "webhook not enqueued");
587            ingress.retry_later(StatusCode::SERVICE_UNAVAILABLE, error.code, error.message)
588        }
589    }
590}
591
592/// Serves `POST /hooks/{name}` for `ingress`, with no authentication layer: the
593/// signature is the authentication.
594///
595/// [`ServerBuilder::with_webhook_ingress`](crate::ServerBuilder::with_webhook_ingress)
596/// mounts this router and installs the server's kill switch.
597pub fn webhook_ingress_router(ingress: WebhookIngress) -> Router {
598    let limit = ingress.body_limit;
599    Router::new()
600        .route("/hooks/{name}", post(receive))
601        .layer(DefaultBodyLimit::max(limit))
602        .with_state(ingress)
603}
604
605#[cfg(test)]
606mod tests {
607    use super::*;
608
609    #[test]
610    fn templates_render_values_and_text() {
611        let context = json!({"payload": {"issue": {"number": 42, "title": "Crash"}, "tags": ["a"]}, "hook": {"name": "gh"}});
612        let rendered = render(
613            &json!({
614                "text": "Issue #{{/payload/issue/number}}: {{/payload/issue/title}}{{/payload/missing}}",
615                "tags": "{{/payload/tags}}",
616                "missing": "{{ /payload/nope }}",
617                "fixed": 3
618            }),
619            &context,
620        );
621        assert_eq!(
622            rendered,
623            json!({"text": "Issue #42: Crash", "tags": ["a"], "missing": null, "fixed": 3})
624        );
625        assert_eq!(render_text("{{/hook/name}}:{{/payload/issue/number}}", &context), "gh:42");
626        assert_eq!(render_text("unterminated {{/hook/name", &context), "unterminated {{/hook/name");
627        assert_eq!(
628            render_key("repo:{{/payload/issue/number}}", &context),
629            Ok("repo:42".to_string())
630        );
631        assert!(render_key("thread:{{/payload/thread}}", &context).is_err());
632    }
633}