adk-server 3.0.0

HTTP server for ADK-Rust agents: REST and SSE, A2A v1.0, background runs and cron, approvals, and the AWP agent edge
Documentation
//! OpenAI webhook event handler.
//!
//! Receives signed webhook events from OpenAI for background task completion
//! and other asynchronous notifications. OpenAI signs deliveries with the
//! [Standard Webhooks](https://www.standardwebhooks.com/) scheme, so the handler
//! verifies the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers
//! over the raw body, refuses a delivery outside the timestamp tolerance, and
//! broadcasts each delivery once.
//!
//! # Example
//!
//! ```rust
//! use adk_server::webhooks::{OpenAIWebhookConfig, OpenAIWebhookHandler};
//!
//! let config = OpenAIWebhookConfig {
//!     webhook_secret: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw".to_string(),
//!     path: "/webhooks/openai".to_string(),
//! };
//!
//! let handler = OpenAIWebhookHandler::new(config)?;
//! let mut events = handler.subscribe();
//! let router = handler.router();
//! # let _ = (&mut events, router);
//! # Ok::<(), adk_core::webhook::WebhookError>(())
//! ```

use std::sync::Arc;

use adk_core::webhook::{
    InMemoryWebhookReplayGuard, VerifiedWebhook, WebhookError, WebhookHeaders, WebhookSecret,
    WebhookVerifier, replay_window,
};
use axum::{
    Router,
    body::Bytes,
    extract::State,
    http::{HeaderMap, StatusCode},
    routing::post,
};
use tokio::sync::broadcast;
use tracing::{debug, warn};

/// Configuration for the OpenAI webhook handler.
#[derive(Clone)]
pub struct OpenAIWebhookConfig {
    /// The endpoint's signing secret, as the OpenAI dashboard shows it (`whsec_...`).
    pub webhook_secret: String,
    /// Path to mount the webhook endpoint (e.g., "/webhooks/openai").
    pub path: String,
}

impl std::fmt::Debug for OpenAIWebhookConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenAIWebhookConfig")
            .field("webhook_secret", &"[REDACTED]")
            .field("path", &self.path)
            .finish()
    }
}

/// A parsed webhook event from OpenAI.
#[derive(Debug, Clone)]
pub struct WebhookEvent {
    /// The type of event (e.g., "response.completed", "response.failed").
    pub event_type: String,
    /// The response ID associated with this event.
    pub response_id: String,
    /// The raw response payload as JSON, if present.
    /// Consumers with access to `adk-model` can convert this to `LlmResponse`
    /// via `responses_convert::from_response`.
    pub response: Option<serde_json::Value>,
    /// Error information, if the event represents a failure.
    pub error: Option<String>,
}

/// OpenAI webhook event handler.
///
/// Provides an Axum router that receives POST requests at the configured path,
/// verifies each delivery's Standard Webhooks signature and timestamp, parses the
/// event payload, and broadcasts parsed events to subscribers via a tokio
/// broadcast channel. A redelivery of a `webhook-id` already broadcast is
/// acknowledged and not broadcast again.
#[derive(Clone)]
pub struct OpenAIWebhookHandler {
    config: Arc<OpenAIWebhookConfig>,
    verifier: Arc<WebhookVerifier>,
    seen: Arc<InMemoryWebhookReplayGuard>,
    tx: broadcast::Sender<WebhookEvent>,
}

impl OpenAIWebhookHandler {
    /// Creates a webhook handler with the given configuration.
    ///
    /// The broadcast channel has a capacity of 64 events. If subscribers
    /// fall behind, older events will be dropped.
    ///
    /// # Errors
    ///
    /// Returns [`WebhookError::InvalidSecret`] when `webhook_secret` is not a
    /// `whsec_`-prefixed or bare base64 secret.
    pub fn new(config: OpenAIWebhookConfig) -> Result<Self, WebhookError> {
        let secret = WebhookSecret::from_base64(&config.webhook_secret)?;
        Ok(Self::with_verifier(config, WebhookVerifier::new(secret)))
    }

    /// Creates a webhook handler that verifies deliveries with `verifier`.
    ///
    /// Use it to accept two secrets while one rotates, or to set the timestamp
    /// tolerance; `config.webhook_secret` is not read.
    pub fn with_verifier(config: OpenAIWebhookConfig, verifier: WebhookVerifier) -> Self {
        let (tx, _) = broadcast::channel(64);
        Self {
            config: Arc::new(config),
            verifier: Arc::new(verifier),
            seen: Arc::new(InMemoryWebhookReplayGuard::new()),
            tx,
        }
    }

    /// Create an Axum router for the webhook endpoint.
    ///
    /// The router handles POST requests at the configured path. It returns
    /// HTTP 401 for a delivery that fails verification and HTTP 400 for a
    /// payload that does not parse.
    pub fn router(&self) -> Router {
        let handler_state = self.clone();
        Router::new().route(&self.config.path, post(handle_webhook).with_state(handler_state))
    }

    /// Subscribe to webhook events.
    ///
    /// Returns a broadcast receiver that will receive all parsed webhook events.
    /// Multiple subscribers can be active simultaneously.
    pub fn subscribe(&self) -> broadcast::Receiver<WebhookEvent> {
        self.tx.subscribe()
    }

    /// Verifies the timestamp and signature of one delivery.
    ///
    /// `body` must be the raw request body.
    ///
    /// # Errors
    ///
    /// Returns a [`WebhookError`] when the timestamp is malformed or outside the
    /// tolerance, or the signature matches no configured secret.
    pub fn verify(
        &self,
        headers: &WebhookHeaders<'_>,
        body: &[u8],
    ) -> Result<VerifiedWebhook, WebhookError> {
        self.verifier.verify(headers, body)
    }
}

/// Axum handler for incoming webhook POST requests.
async fn handle_webhook(
    State(handler): State<OpenAIWebhookHandler>,
    headers: HeaderMap,
    body: Bytes,
) -> StatusCode {
    let lookup = |name: &'static str| headers.get(name).and_then(|v| v.to_str().ok());
    let verified = match WebhookHeaders::from_lookup(lookup)
        .and_then(|parsed| handler.verify(&parsed, &body))
    {
        Ok(verified) => verified,
        Err(error) => {
            warn!(error.code = error.code(), error = %error, "webhook rejected");
            return StatusCode::UNAUTHORIZED;
        }
    };

    // Parse the JSON payload
    let payload: serde_json::Value = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => {
            warn!("webhook payload parse error: {e}");
            return StatusCode::BAD_REQUEST;
        }
    };

    // Extract event_type and response_id
    let event_type = match payload.get("type").and_then(|v| v.as_str()) {
        Some(t) => t.to_string(),
        None => {
            warn!("webhook payload missing 'type' field");
            return StatusCode::BAD_REQUEST;
        }
    };

    let response_id = payload
        .get("response")
        .and_then(|r| r.get("id"))
        .and_then(|v| v.as_str())
        .or_else(|| payload.get("response_id").and_then(|v| v.as_str()))
        .unwrap_or("")
        .to_string();

    // Extract response data for completed events
    let response = payload.get("response").cloned();

    // Extract error information for failed events
    let error = payload
        .get("error")
        .or_else(|| payload.get("response").and_then(|r| r.get("error")))
        .map(|e| e.to_string());

    let event = WebhookEvent { event_type, response_id, response, error };

    debug!(
        event_type = %event.event_type,
        response_id = %event.response_id,
        "webhook event received"
    );

    // OpenAI may deliver one event more than once; `webhook-id` identifies it.
    let window = chrono::Duration::from_std(replay_window(handler.verifier.tolerance()))
        .unwrap_or(chrono::Duration::MAX);
    if !handler.seen.record(&verified.id, verified.timestamp + window) {
        debug!(webhook.id = %verified.id, "duplicate webhook delivery acknowledged");
        return StatusCode::OK;
    }

    // Broadcast to subscribers (ignore send errors — no subscribers is fine)
    let _ = handler.tx.send(event);

    StatusCode::OK
}

#[cfg(test)]
mod tests {
    use super::*;
    use adk_core::webhook::{
        WEBHOOK_ID_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER,
    };

    const SECRET: &str = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw";
    const BODY: &[u8] = br#"{"type":"response.completed","response":{"id":"resp_123"}}"#;

    fn handler() -> OpenAIWebhookHandler {
        OpenAIWebhookHandler::new(OpenAIWebhookConfig {
            webhook_secret: SECRET.to_string(),
            path: "/webhooks/openai".to_string(),
        })
        .unwrap()
    }

    fn now() -> i64 {
        chrono::Utc::now().timestamp()
    }

    fn signed(id: &str, timestamp: i64, body: &[u8]) -> HeaderMap {
        let signature = WebhookSecret::from_base64(SECRET).unwrap().signature(id, timestamp, body);
        let mut headers = HeaderMap::new();
        headers.insert(WEBHOOK_ID_HEADER, id.parse().unwrap());
        headers.insert(WEBHOOK_TIMESTAMP_HEADER, timestamp.to_string().parse().unwrap());
        headers.insert(WEBHOOK_SIGNATURE_HEADER, signature.parse().unwrap());
        headers
    }

    async fn deliver(
        handler: &OpenAIWebhookHandler,
        headers: HeaderMap,
        body: &[u8],
    ) -> StatusCode {
        handle_webhook(State(handler.clone()), headers, Bytes::copy_from_slice(body)).await
    }

    #[tokio::test]
    async fn a_signed_delivery_is_broadcast() {
        let handler = handler();
        let mut events = handler.subscribe();

        assert_eq!(deliver(&handler, signed("wh_1", now(), BODY), BODY).await, StatusCode::OK);

        let event = events.recv().await.unwrap();
        assert_eq!(event.event_type, "response.completed");
        assert_eq!(event.response_id, "resp_123");
    }

    #[tokio::test]
    async fn a_delivery_without_the_standard_headers_is_refused() {
        let mut headers = HeaderMap::new();
        headers.insert("x-openai-signature", "deadbeef".parse().unwrap());

        assert_eq!(deliver(&handler(), headers, BODY).await, StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn a_changed_body_is_refused() {
        let headers = signed("wh_1", now(), BODY);

        let status = deliver(&handler(), headers, br#"{"type":"response.failed"}"#).await;

        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn a_delivery_signed_outside_the_tolerance_is_refused() {
        let handler = handler();
        let mut events = handler.subscribe();

        let status = deliver(&handler, signed("wh_1", now() - 400, BODY), BODY).await;

        assert_eq!(status, StatusCode::UNAUTHORIZED);
        assert!(events.try_recv().is_err());
    }

    #[tokio::test]
    async fn a_redelivery_is_acknowledged_and_broadcast_once() {
        let handler = handler();
        let mut events = handler.subscribe();

        assert_eq!(deliver(&handler, signed("wh_1", now(), BODY), BODY).await, StatusCode::OK);
        assert_eq!(deliver(&handler, signed("wh_1", now(), BODY), BODY).await, StatusCode::OK);

        assert!(events.try_recv().is_ok());
        assert!(events.try_recv().is_err());
    }

    #[test]
    fn a_secret_that_is_not_base64_is_refused() {
        let config = OpenAIWebhookConfig {
            webhook_secret: "not base64!".to_string(),
            path: "/webhooks/openai".to_string(),
        };

        assert!(matches!(OpenAIWebhookHandler::new(config), Err(WebhookError::InvalidSecret(_))));
    }

    #[test]
    fn the_config_does_not_print_its_secret() {
        let config = OpenAIWebhookConfig {
            webhook_secret: SECRET.to_string(),
            path: "/webhooks/openai".to_string(),
        };

        assert!(!format!("{config:?}").contains("MfKQ9r8"));
    }
}