Skip to main content

adk_server/webhooks/
openai.rs

1//! OpenAI webhook event handler.
2//!
3//! Receives signed webhook events from OpenAI for background task completion
4//! and other asynchronous notifications. OpenAI signs deliveries with the
5//! [Standard Webhooks](https://www.standardwebhooks.com/) scheme, so the handler
6//! verifies the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers
7//! over the raw body, refuses a delivery outside the timestamp tolerance, and
8//! broadcasts each delivery once.
9//!
10//! # Example
11//!
12//! ```rust
13//! use adk_server::webhooks::{OpenAIWebhookConfig, OpenAIWebhookHandler};
14//!
15//! let config = OpenAIWebhookConfig {
16//!     webhook_secret: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw".to_string(),
17//!     path: "/webhooks/openai".to_string(),
18//! };
19//!
20//! let handler = OpenAIWebhookHandler::new(config)?;
21//! let mut events = handler.subscribe();
22//! let router = handler.router();
23//! # let _ = (&mut events, router);
24//! # Ok::<(), adk_core::webhook::WebhookError>(())
25//! ```
26
27use std::sync::Arc;
28
29use adk_core::webhook::{
30    InMemoryWebhookReplayGuard, VerifiedWebhook, WebhookError, WebhookHeaders, WebhookSecret,
31    WebhookVerifier, replay_window,
32};
33use axum::{
34    Router,
35    body::Bytes,
36    extract::State,
37    http::{HeaderMap, StatusCode},
38    routing::post,
39};
40use tokio::sync::broadcast;
41use tracing::{debug, warn};
42
43/// Configuration for the OpenAI webhook handler.
44#[derive(Clone)]
45pub struct OpenAIWebhookConfig {
46    /// The endpoint's signing secret, as the OpenAI dashboard shows it (`whsec_...`).
47    pub webhook_secret: String,
48    /// Path to mount the webhook endpoint (e.g., "/webhooks/openai").
49    pub path: String,
50}
51
52impl std::fmt::Debug for OpenAIWebhookConfig {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("OpenAIWebhookConfig")
55            .field("webhook_secret", &"[REDACTED]")
56            .field("path", &self.path)
57            .finish()
58    }
59}
60
61/// A parsed webhook event from OpenAI.
62#[derive(Debug, Clone)]
63pub struct WebhookEvent {
64    /// The type of event (e.g., "response.completed", "response.failed").
65    pub event_type: String,
66    /// The response ID associated with this event.
67    pub response_id: String,
68    /// The raw response payload as JSON, if present.
69    /// Consumers with access to `adk-model` can convert this to `LlmResponse`
70    /// via `responses_convert::from_response`.
71    pub response: Option<serde_json::Value>,
72    /// Error information, if the event represents a failure.
73    pub error: Option<String>,
74}
75
76/// OpenAI webhook event handler.
77///
78/// Provides an Axum router that receives POST requests at the configured path,
79/// verifies each delivery's Standard Webhooks signature and timestamp, parses the
80/// event payload, and broadcasts parsed events to subscribers via a tokio
81/// broadcast channel. A redelivery of a `webhook-id` already broadcast is
82/// acknowledged and not broadcast again.
83#[derive(Clone)]
84pub struct OpenAIWebhookHandler {
85    config: Arc<OpenAIWebhookConfig>,
86    verifier: Arc<WebhookVerifier>,
87    seen: Arc<InMemoryWebhookReplayGuard>,
88    tx: broadcast::Sender<WebhookEvent>,
89}
90
91impl OpenAIWebhookHandler {
92    /// Creates a webhook handler with the given configuration.
93    ///
94    /// The broadcast channel has a capacity of 64 events. If subscribers
95    /// fall behind, older events will be dropped.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`WebhookError::InvalidSecret`] when `webhook_secret` is not a
100    /// `whsec_`-prefixed or bare base64 secret.
101    pub fn new(config: OpenAIWebhookConfig) -> Result<Self, WebhookError> {
102        let secret = WebhookSecret::from_base64(&config.webhook_secret)?;
103        Ok(Self::with_verifier(config, WebhookVerifier::new(secret)))
104    }
105
106    /// Creates a webhook handler that verifies deliveries with `verifier`.
107    ///
108    /// Use it to accept two secrets while one rotates, or to set the timestamp
109    /// tolerance; `config.webhook_secret` is not read.
110    pub fn with_verifier(config: OpenAIWebhookConfig, verifier: WebhookVerifier) -> Self {
111        let (tx, _) = broadcast::channel(64);
112        Self {
113            config: Arc::new(config),
114            verifier: Arc::new(verifier),
115            seen: Arc::new(InMemoryWebhookReplayGuard::new()),
116            tx,
117        }
118    }
119
120    /// Create an Axum router for the webhook endpoint.
121    ///
122    /// The router handles POST requests at the configured path. It returns
123    /// HTTP 401 for a delivery that fails verification and HTTP 400 for a
124    /// payload that does not parse.
125    pub fn router(&self) -> Router {
126        let handler_state = self.clone();
127        Router::new().route(&self.config.path, post(handle_webhook).with_state(handler_state))
128    }
129
130    /// Subscribe to webhook events.
131    ///
132    /// Returns a broadcast receiver that will receive all parsed webhook events.
133    /// Multiple subscribers can be active simultaneously.
134    pub fn subscribe(&self) -> broadcast::Receiver<WebhookEvent> {
135        self.tx.subscribe()
136    }
137
138    /// Verifies the timestamp and signature of one delivery.
139    ///
140    /// `body` must be the raw request body.
141    ///
142    /// # Errors
143    ///
144    /// Returns a [`WebhookError`] when the timestamp is malformed or outside the
145    /// tolerance, or the signature matches no configured secret.
146    pub fn verify(
147        &self,
148        headers: &WebhookHeaders<'_>,
149        body: &[u8],
150    ) -> Result<VerifiedWebhook, WebhookError> {
151        self.verifier.verify(headers, body)
152    }
153}
154
155/// Axum handler for incoming webhook POST requests.
156async fn handle_webhook(
157    State(handler): State<OpenAIWebhookHandler>,
158    headers: HeaderMap,
159    body: Bytes,
160) -> StatusCode {
161    let lookup = |name: &'static str| headers.get(name).and_then(|v| v.to_str().ok());
162    let verified = match WebhookHeaders::from_lookup(lookup)
163        .and_then(|parsed| handler.verify(&parsed, &body))
164    {
165        Ok(verified) => verified,
166        Err(error) => {
167            warn!(error.code = error.code(), error = %error, "webhook rejected");
168            return StatusCode::UNAUTHORIZED;
169        }
170    };
171
172    // Parse the JSON payload
173    let payload: serde_json::Value = match serde_json::from_slice(&body) {
174        Ok(v) => v,
175        Err(e) => {
176            warn!("webhook payload parse error: {e}");
177            return StatusCode::BAD_REQUEST;
178        }
179    };
180
181    // Extract event_type and response_id
182    let event_type = match payload.get("type").and_then(|v| v.as_str()) {
183        Some(t) => t.to_string(),
184        None => {
185            warn!("webhook payload missing 'type' field");
186            return StatusCode::BAD_REQUEST;
187        }
188    };
189
190    let response_id = payload
191        .get("response")
192        .and_then(|r| r.get("id"))
193        .and_then(|v| v.as_str())
194        .or_else(|| payload.get("response_id").and_then(|v| v.as_str()))
195        .unwrap_or("")
196        .to_string();
197
198    // Extract response data for completed events
199    let response = payload.get("response").cloned();
200
201    // Extract error information for failed events
202    let error = payload
203        .get("error")
204        .or_else(|| payload.get("response").and_then(|r| r.get("error")))
205        .map(|e| e.to_string());
206
207    let event = WebhookEvent { event_type, response_id, response, error };
208
209    debug!(
210        event_type = %event.event_type,
211        response_id = %event.response_id,
212        "webhook event received"
213    );
214
215    // OpenAI may deliver one event more than once; `webhook-id` identifies it.
216    let window = chrono::Duration::from_std(replay_window(handler.verifier.tolerance()))
217        .unwrap_or(chrono::Duration::MAX);
218    if !handler.seen.record(&verified.id, verified.timestamp + window) {
219        debug!(webhook.id = %verified.id, "duplicate webhook delivery acknowledged");
220        return StatusCode::OK;
221    }
222
223    // Broadcast to subscribers (ignore send errors — no subscribers is fine)
224    let _ = handler.tx.send(event);
225
226    StatusCode::OK
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use adk_core::webhook::{
233        WEBHOOK_ID_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER,
234    };
235
236    const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
237    const BODY: &[u8] = br#"{"type":"response.completed","response":{"id":"resp_123"}}"#;
238
239    fn handler() -> OpenAIWebhookHandler {
240        OpenAIWebhookHandler::new(OpenAIWebhookConfig {
241            webhook_secret: SECRET.to_string(),
242            path: "/webhooks/openai".to_string(),
243        })
244        .unwrap()
245    }
246
247    fn now() -> i64 {
248        chrono::Utc::now().timestamp()
249    }
250
251    fn signed(id: &str, timestamp: i64, body: &[u8]) -> HeaderMap {
252        let signature = WebhookSecret::from_base64(SECRET).unwrap().signature(id, timestamp, body);
253        let mut headers = HeaderMap::new();
254        headers.insert(WEBHOOK_ID_HEADER, id.parse().unwrap());
255        headers.insert(WEBHOOK_TIMESTAMP_HEADER, timestamp.to_string().parse().unwrap());
256        headers.insert(WEBHOOK_SIGNATURE_HEADER, signature.parse().unwrap());
257        headers
258    }
259
260    async fn deliver(
261        handler: &OpenAIWebhookHandler,
262        headers: HeaderMap,
263        body: &[u8],
264    ) -> StatusCode {
265        handle_webhook(State(handler.clone()), headers, Bytes::copy_from_slice(body)).await
266    }
267
268    #[tokio::test]
269    async fn a_signed_delivery_is_broadcast() {
270        let handler = handler();
271        let mut events = handler.subscribe();
272
273        assert_eq!(deliver(&handler, signed("wh_1", now(), BODY), BODY).await, StatusCode::OK);
274
275        let event = events.recv().await.unwrap();
276        assert_eq!(event.event_type, "response.completed");
277        assert_eq!(event.response_id, "resp_123");
278    }
279
280    #[tokio::test]
281    async fn a_delivery_without_the_standard_headers_is_refused() {
282        let mut headers = HeaderMap::new();
283        headers.insert("x-openai-signature", "deadbeef".parse().unwrap());
284
285        assert_eq!(deliver(&handler(), headers, BODY).await, StatusCode::UNAUTHORIZED);
286    }
287
288    #[tokio::test]
289    async fn a_changed_body_is_refused() {
290        let headers = signed("wh_1", now(), BODY);
291
292        let status = deliver(&handler(), headers, br#"{"type":"response.failed"}"#).await;
293
294        assert_eq!(status, StatusCode::UNAUTHORIZED);
295    }
296
297    #[tokio::test]
298    async fn a_delivery_signed_outside_the_tolerance_is_refused() {
299        let handler = handler();
300        let mut events = handler.subscribe();
301
302        let status = deliver(&handler, signed("wh_1", now() - 400, BODY), BODY).await;
303
304        assert_eq!(status, StatusCode::UNAUTHORIZED);
305        assert!(events.try_recv().is_err());
306    }
307
308    #[tokio::test]
309    async fn a_redelivery_is_acknowledged_and_broadcast_once() {
310        let handler = handler();
311        let mut events = handler.subscribe();
312
313        assert_eq!(deliver(&handler, signed("wh_1", now(), BODY), BODY).await, StatusCode::OK);
314        assert_eq!(deliver(&handler, signed("wh_1", now(), BODY), BODY).await, StatusCode::OK);
315
316        assert!(events.try_recv().is_ok());
317        assert!(events.try_recv().is_err());
318    }
319
320    #[test]
321    fn a_secret_that_is_not_base64_is_refused() {
322        let config = OpenAIWebhookConfig {
323            webhook_secret: "not base64!".to_string(),
324            path: "/webhooks/openai".to_string(),
325        };
326
327        assert!(matches!(OpenAIWebhookHandler::new(config), Err(WebhookError::InvalidSecret(_))));
328    }
329
330    #[test]
331    fn the_config_does_not_print_its_secret() {
332        let config = OpenAIWebhookConfig {
333            webhook_secret: SECRET.to_string(),
334            path: "/webhooks/openai".to_string(),
335        };
336
337        assert!(!format!("{config:?}").contains("MfKQ9r8"));
338    }
339}