Skip to main content

agentmux_srv/messaging/whatsapp/
webhook.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! WhatsApp Cloud API inbound webhook receiver — axum handlers for the
5//! one-time verification handshake and the per-event delivery POST.
6//!
7//! These are the genuinely new shape versus Discord/Telegram/Slack, which
8//! only ever make *outbound* connections: this is passive HTTP the public
9//! internet (Meta's servers) can reach, so every inbound POST must be
10//! authenticated via HMAC signature (spec §3.2/§9) rather than AgentMux's
11//! own `X-AuthKey` scheme, which Meta cannot supply. **These routes must be
12//! registered outside `auth_middleware`** — see `server/mod.rs`, merged at
13//! the top level alongside the unauthenticated `health` router, not inside
14//! `authed_routes`. Putting them behind `X-AuthKey` would make Meta's calls
15//! always fail (spec §8.2).
16//!
17//! ## Credential handling
18//!
19//! Two credentials pass through this module: the webhook verify token
20//! (`hub.verify_token` on the GET handshake) and the app secret (used to
21//! validate `X-Hub-Signature-256` on every POST). Neither is ever logged —
22//! failures log only the fact of a mismatch, never the header value or the
23//! secret. This mirrors the review findings baked into
24//! `telegram/rest.rs::redact()` and `slack/rest.rs::redact_ticket()`: any
25//! error string built from a value that might embed a credential must be
26//! redacted (or, here, simply never constructed from the credential in the
27//! first place) before it can reach a log line or an HTTP response body.
28
29use std::collections::HashMap;
30
31use axum::{
32    body::Bytes,
33    extract::Query,
34    http::{HeaderMap, StatusCode},
35    response::IntoResponse,
36};
37use agentmux_common::secret_eq::secret_eq;
38use hmac::{Hmac, Mac};
39use sha2::Sha256;
40
41use super::types::WebhookPayload;
42use super::WhatsAppBridge;
43use crate::backend::reactive::types::InjectionRequest;
44
45type HmacSha256 = Hmac<Sha256>;
46
47/// `GET /webhook/whatsapp?hub.mode=subscribe&hub.verify_token=...&hub.challenge=...`
48///
49/// Meta's one-time (per-URL-change) verification handshake (spec §3.1). Must
50/// succeed before Meta starts delivering inbound POSTs, and Meta re-runs
51/// this any time the webhook URL or verify token changes in the App
52/// Dashboard.
53pub async fn handle_verify(Query(params): Query<HashMap<String, String>>) -> impl IntoResponse {
54    let Some(bridge) = WhatsAppBridge::get() else {
55        return (
56            StatusCode::SERVICE_UNAVAILABLE,
57            "whatsapp bridge not initialized".to_string(),
58        )
59            .into_response();
60    };
61
62    let mode = params.get("hub.mode").map(String::as_str).unwrap_or("");
63    let token = params
64        .get("hub.verify_token")
65        .map(String::as_str)
66        .unwrap_or("");
67    let challenge = params.get("hub.challenge").cloned().unwrap_or_default();
68
69    let token_matches = secret_eq(token.as_bytes(), bridge.verify_token().as_bytes());
70
71    if mode == "subscribe" && token_matches {
72        (StatusCode::OK, challenge).into_response()
73    } else {
74        // Never log `token` — it's the shared secret being validated.
75        tracing::warn!(
76            "whatsapp_bridge: webhook verification handshake rejected (mode={mode:?}, token_match={token_matches})"
77        );
78        (StatusCode::FORBIDDEN, "verification failed".to_string()).into_response()
79    }
80}
81
82/// `POST /webhook/whatsapp` — inbound message delivery.
83///
84/// Body MUST be read as raw bytes (`Bytes`, not `Json<T>`) so the exact
85/// signed payload is available for the HMAC check before any deserialization
86/// happens (spec §3.2/§9.1) — deserializing first and re-serializing to
87/// check the signature would validate a re-encoded payload, not what Meta
88/// actually signed.
89pub async fn handle_inbound(headers: HeaderMap, body: Bytes) -> impl IntoResponse {
90    let Some(bridge) = WhatsAppBridge::get() else {
91        return StatusCode::SERVICE_UNAVAILABLE;
92    };
93
94    let sig_header = headers
95        .get("X-Hub-Signature-256")
96        .and_then(|v| v.to_str().ok())
97        .unwrap_or("");
98
99    if !verify_signature(bridge.app_secret(), &body, sig_header) {
100        // Reject before any payload parsing or logging of body content
101        // (spec §3.2 step 4). Do not log `sig_header` — while the signature
102        // itself isn't directly reusable as a credential (it's a per-request
103        // HMAC over this specific body), treating anything derived from
104        // request headers as potentially sensitive and never echoing it into
105        // logs is the safer default, consistent with the redaction posture
106        // Telegram and Slack's bridges adopted after review.
107        tracing::warn!("whatsapp_bridge: rejected inbound webhook — signature mismatch");
108        return StatusCode::UNAUTHORIZED;
109    }
110
111    let payload: WebhookPayload = match serde_json::from_slice(&body) {
112        Ok(p) => p,
113        Err(e) => {
114            tracing::warn!("whatsapp_bridge: webhook payload parse error: {e}");
115            return StatusCode::BAD_REQUEST;
116        }
117    };
118
119    for msg in payload.extract_messages() {
120        bridge.record_inbound(&msg.from);
121
122        let Some(target) = bridge.target_agent() else {
123            tracing::debug!(
124                "whatsapp_bridge: message from {} (no target agent configured)",
125                msg.from
126            );
127            continue;
128        };
129
130        let envelope = format!("[WhatsApp {}]: {}", msg.from, msg.text);
131        let req = InjectionRequest {
132            target_agent: target.clone(),
133            message: envelope,
134            source_agent: Some("whatsapp".to_string()),
135            request_id: Some(msg.id.clone()),
136            priority: None,
137            jekt_tier: None,
138            delivery_tier: Some("wan".to_string()),
139            forward_hops: 0,
140            ..Default::default()
141        };
142        let result = crate::server::jekt_entry::inject_from_bridge(req, &msg.text);
143        if !result.success {
144            tracing::warn!(
145                "whatsapp_bridge: inject to agent {target} failed: {:?}",
146                result.error
147            );
148        }
149    }
150
151    // Always 200 for a successfully-parsed batch, even if local injection
152    // failed for one or more messages — per Meta's delivery semantics, a
153    // non-2xx response causes retries and eventual (after ~7 days of
154    // failures) event drop; local injection failures are our problem to
155    // observe via logs, not something that should make Meta think delivery
156    // itself failed (spec §5.2).
157    StatusCode::OK
158}
159
160/// Validates `X-Hub-Signature-256: sha256=<hex>` = HMAC-SHA256(app_secret,
161/// raw_body). Uses `Mac::verify_slice`, which performs a constant-time
162/// comparison internally (backed by the `subtle` crate, already present
163/// transitively via `hmac` in this workspace's dependency graph — no new
164/// crate added).
165fn verify_signature(app_secret: &str, body: &[u8], header: &str) -> bool {
166    let Some(hex_sig) = header.strip_prefix("sha256=") else {
167        return false;
168    };
169    let Ok(expected) = hex::decode(hex_sig) else {
170        return false;
171    };
172    let Ok(mut mac) = HmacSha256::new_from_slice(app_secret.as_bytes()) else {
173        return false;
174    };
175    mac.update(body);
176    mac.verify_slice(&expected).is_ok()
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182
183    fn sign(secret: &str, body: &[u8]) -> String {
184        let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
185        mac.update(body);
186        format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
187    }
188
189    #[test]
190    fn verify_signature_accepts_known_good_vector() {
191        let secret = "app_secret_123";
192        let body = b"{\"entry\":[]}";
193        let header = sign(secret, body);
194        assert!(verify_signature(secret, body, &header));
195    }
196
197    #[test]
198    fn verify_signature_rejects_wrong_secret() {
199        let header = sign("right_secret", b"hello");
200        assert!(!verify_signature("wrong_secret", b"hello", &header));
201    }
202
203    #[test]
204    fn verify_signature_rejects_tampered_body() {
205        let header = sign("secret", b"original");
206        assert!(!verify_signature("secret", b"tampered", &header));
207    }
208
209    #[test]
210    fn verify_signature_rejects_missing_sha256_prefix() {
211        assert!(!verify_signature("secret", b"hello", "deadbeef"));
212    }
213
214    #[test]
215    fn verify_signature_rejects_malformed_hex() {
216        assert!(!verify_signature("secret", b"hello", "sha256=not_valid_hex"));
217    }
218
219    #[test]
220    fn verify_signature_rejects_empty_header() {
221        assert!(!verify_signature("secret", b"hello", ""));
222    }
223}