mod api;
mod wire;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use adk_core::{AdkError, ErrorCategory, ErrorComponent};
use adk_kernel::KernelError;
use adk_kernel::channels::{
ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
StopNotice,
};
use async_trait::async_trait;
use axum::body::Bytes;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use chrono::Utc;
use hmac::{Hmac, Mac};
use serde_json::Value;
use sha2::Sha256;
use tokio::sync::mpsc;
use super::shared::{
ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
PressedCard, Taker, Update, dispatch, kit_builder, notice_words, patient, stopped_words,
};
use crate::error::{Result, SurfaceError};
use api::GraphApi;
pub const WHATSAPP_CHANNEL: &str = "whatsapp";
pub const WHATSAPP: &str = "WhatsApp";
const DEFAULT_API_BASE: &str = "https://graph.facebook.com/v23.0";
const WINDOW_SECS: i64 = 24 * 60 * 60;
const SEEN_KEPT: usize = 4096;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum WhatsAppError {
#[error(
"WhatsApp refused the access token: check WHATSAPP_ACCESS_TOKEN, a system user's token \
with `whatsapp_business_messaging`"
)]
Unauthorized,
#[error(
"outside WhatsApp's 24-hour customer-service window: the message was not sent; the \
person is reached again once they write, or by an approved template \
(`WhatsAppAdapterBuilder::template`)"
)]
OutsideWindow,
#[error("WhatsApp limited the number's sending (error {code}): try again later")]
RateLimited {
code: i64,
},
#[error("WhatsApp refused the message (error {code}): {message}")]
Refused {
code: i64,
message: String,
},
#[error("WhatsApp could not be reached: {reason}; check the network and the API address")]
Unreachable {
reason: String,
},
#[error("WhatsApp's answer could not be read: {reason}")]
InvalidResponse {
reason: String,
},
}
impl WhatsAppError {
pub fn code(&self) -> &'static str {
match self {
Self::Unauthorized => "surface.whatsapp.unauthorized",
Self::OutsideWindow => "surface.whatsapp.outside_window",
Self::RateLimited { .. } => "surface.whatsapp.rate_limited",
Self::Refused { .. } => "surface.whatsapp.refused",
Self::Unreachable { .. } => "surface.whatsapp.unreachable",
Self::InvalidResponse { .. } => "surface.whatsapp.invalid_response",
}
}
}
impl From<WhatsAppError> for AdkError {
fn from(error: WhatsAppError) -> Self {
let category = match &error {
WhatsAppError::Unauthorized => ErrorCategory::Unauthorized,
WhatsAppError::OutsideWindow => ErrorCategory::Forbidden,
WhatsAppError::RateLimited { .. } => ErrorCategory::RateLimited,
WhatsAppError::Refused { .. } => ErrorCategory::InvalidInput,
WhatsAppError::Unreachable { .. } => ErrorCategory::Unavailable,
WhatsAppError::InvalidResponse { .. } => ErrorCategory::Internal,
};
AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
.with_provider("whatsapp")
}
}
impl From<WhatsAppError> for KernelError {
fn from(error: WhatsAppError) -> Self {
Self::Core(error.into())
}
}
pub struct WhatsAppAdapterBuilder {
phone_number_id: String,
token: String,
app_secret: Option<String>,
verify_token: Option<String>,
template: Option<(String, String)>,
api_base: String,
kit: Kit,
}
impl fmt::Debug for WhatsAppAdapterBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WhatsAppAdapterBuilder")
.field("phone_number_id", &self.phone_number_id)
.field("api_base", &self.api_base)
.finish_non_exhaustive()
}
}
impl WhatsAppAdapterBuilder {
#[must_use]
pub fn app_secret(mut self, secret: impl Into<String>) -> Self {
self.app_secret = Some(secret.into());
self
}
#[must_use]
pub fn verify_token(mut self, token: impl Into<String>) -> Self {
self.verify_token = Some(token.into());
self
}
#[must_use]
pub fn template(mut self, name: impl Into<String>, language: impl Into<String>) -> Self {
self.template = Some((name.into(), language.into()));
self
}
#[must_use]
pub fn api_base(mut self, url: impl Into<String>) -> Self {
self.api_base = url.into();
self
}
kit_builder!("WhatsApp");
pub fn build(self) -> Result<WhatsAppAdapter> {
let api = GraphApi::new(&self.api_base, &self.phone_number_id, &self.token)
.map_err(SurfaceError::Invalid)?;
let secret = self.app_secret.filter(|secret| !secret.is_empty()).ok_or_else(|| {
SurfaceError::Invalid(
"the WhatsApp webhook needs the app secret (WHATSAPP_APP_SECRET) to check every \
body's signature"
.into(),
)
})?;
let verify_token =
self.verify_token.filter(|token| !token.is_empty()).ok_or_else(|| {
SurfaceError::Invalid(
"the WhatsApp webhook needs a verify token (WHATSAPP_VERIFY_TOKEN) for its \
verification handshake"
.into(),
)
})?;
Ok(WhatsAppAdapter {
inner: Arc::new(Inner {
api,
kit: self.kit,
phone_number_id: self.phone_number_id,
secret: secret.into_bytes(),
verify_token,
template: self.template,
state: Mutex::default(),
}),
})
}
}
#[derive(Clone)]
pub struct WhatsAppAdapter {
inner: Arc<Inner>,
}
struct Inner {
api: GraphApi,
kit: Kit,
phone_number_id: String,
secret: Vec<u8>,
verify_token: String,
template: Option<(String, String)>,
state: Mutex<WindowState>,
}
#[derive(Default)]
struct WindowState {
last_written: HashMap<String, i64>,
nudged: HashSet<String>,
seen: HashSet<String>,
order: VecDeque<String>,
}
impl WindowState {
fn first_time(&mut self, id: &str) -> bool {
if !self.seen.insert(id.to_string()) {
return false;
}
self.order.push_back(id.to_string());
while self.order.len() > SEEN_KEPT {
if let Some(oldest) = self.order.pop_front() {
self.seen.remove(&oldest);
}
}
true
}
fn open(&self, thread: &str, now: i64) -> Option<bool> {
self.last_written.get(thread).map(|at| now - at < WINDOW_SECS)
}
}
impl fmt::Debug for WhatsAppAdapter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WhatsAppAdapter")
.field("channel", &WHATSAPP_CHANNEL)
.field("phone_number_id", &self.inner.phone_number_id)
.finish_non_exhaustive()
}
}
#[derive(Debug)]
pub struct WhatsAppWebhook {
router: axum::Router,
connection: ChannelConnection<WhatsAppError>,
}
impl WhatsAppWebhook {
pub fn router(&self) -> axum::Router {
self.router.clone()
}
pub fn stop(&self) {
self.connection.stop();
}
pub fn is_finished(&self) -> bool {
self.connection.is_finished()
}
pub async fn join(self) -> std::result::Result<(), WhatsAppError> {
drop(self.router);
self.connection.join().await
}
}
struct Hook {
adapter: WhatsAppAdapter,
sender: mpsc::UnboundedSender<Update<Carried>>,
}
pub(crate) struct Carried {
card: Option<String>,
media: Option<(String, Option<String>)>,
}
fn same(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |diff, (x, y)| diff | (x ^ y)) == 0
}
fn unhex(text: &str) -> Option<Vec<u8>> {
if !text.len().is_multiple_of(2) {
return None;
}
(0..text.len())
.step_by(2)
.map(|index| u8::from_str_radix(text.get(index..index + 2)?, 16).ok())
.collect()
}
impl WhatsAppAdapter {
pub fn builder(
phone_number_id: impl Into<String>,
token: impl Into<String>,
) -> WhatsAppAdapterBuilder {
WhatsAppAdapterBuilder {
phone_number_id: phone_number_id.into(),
token: token.into(),
app_secret: None,
verify_token: None,
template: None,
api_base: DEFAULT_API_BASE.to_string(),
kit: Kit::default(),
}
}
pub fn inbound(&self, payload: &Value) -> Vec<ChannelInbound> {
wire::parse(payload, &self.inner.phone_number_id)
.into_iter()
.filter_map(|received| received.inbound)
.collect()
}
fn signed(&self, body: &[u8], signature: &str) -> bool {
let Some(digest) = signature.strip_prefix("sha256=").and_then(unhex) else { return false };
let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(&self.inner.secret) else { return false };
mac.update(body);
mac.verify_slice(&digest).is_ok()
}
pub fn start(&self, gateway: ChannelGateway) -> WhatsAppWebhook {
let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
let hook = Arc::new(Hook { adapter: self.clone(), sender });
let router = axum::Router::new().route("/", get(verify).post(receive)).with_state(hook);
let connection = ChannelConnection::spawn(async move {
let mut dispatcher = AbortOnDrop(task);
let _ = (&mut dispatcher.0).await;
Ok(())
});
WhatsAppWebhook { router, connection }
}
fn take_payload(
&self,
payload: &Value,
sender: &mpsc::UnboundedSender<Update<Carried>>,
) -> bool {
let now = Utc::now().timestamp();
for received in wire::parse(payload, &self.inner.phone_number_id) {
{
let mut state = self.inner.state.lock().unwrap_or_else(PoisonError::into_inner);
if !state.first_time(&received.id) {
tracing::debug!("a whatsapp message delivered again was not taken again");
continue;
}
let at = received.at.unwrap_or(now).min(now);
let last = state.last_written.entry(received.thread.clone()).or_insert(at);
*last = (*last).max(at);
state.nudged.remove(&received.thread);
}
if received.inbound.is_some()
&& sender
.send(Update {
inbound: received.inbound,
press: Some(Carried { card: received.card, media: received.media }),
})
.is_err()
{
return false;
}
}
true
}
async fn send(&self, thread: &str, body: &Value) -> adk_kernel::Result<String> {
let now = Utc::now().timestamp();
let open =
self.inner.state.lock().unwrap_or_else(PoisonError::into_inner).open(thread, now);
if open == Some(false) {
self.nudge(thread).await;
return Err(WhatsAppError::OutsideWindow.into());
}
match self.inner.api.send(body, patient(WHATSAPP_CHANNEL, thread)).await {
Err(WhatsAppError::OutsideWindow) => {
self.inner
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.last_written
.insert(thread.to_string(), 0);
self.nudge(thread).await;
Err(WhatsAppError::OutsideWindow.into())
}
sent => Ok(sent?),
}
}
async fn nudge(&self, thread: &str) {
let Some((name, language)) = &self.inner.template else { return };
let first = self
.inner
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.nudged
.insert(thread.to_string());
if !first {
return;
}
if let Err(error) = self.inner.api.send(&wire::template(thread, name, language), true).await
{
tracing::warn!(error = %error, "the whatsapp template could not be sent");
self.inner.state.lock().unwrap_or_else(PoisonError::into_inner).nudged.remove(thread);
}
}
}
async fn verify(
State(hook): State<Arc<Hook>>,
Query(query): Query<HashMap<String, String>>,
) -> Response {
let subscribe = query.get("hub.mode").map(String::as_str) == Some("subscribe");
let matches = query
.get("hub.verify_token")
.is_some_and(|token| same(token.as_bytes(), hook.adapter.inner.verify_token.as_bytes()));
match query.get("hub.challenge") {
Some(challenge) if subscribe && matches => {
(StatusCode::OK, challenge.clone()).into_response()
}
_ => StatusCode::FORBIDDEN.into_response(),
}
}
async fn receive(State(hook): State<Arc<Hook>>, headers: HeaderMap, body: Bytes) -> StatusCode {
let signature = headers.get("x-hub-signature-256").and_then(|value| value.to_str().ok());
if !signature.is_some_and(|signature| hook.adapter.signed(&body, signature)) {
tracing::warn!("a whatsapp webhook delivery without a valid signature was refused");
return StatusCode::UNAUTHORIZED;
}
let Ok(payload) = serde_json::from_slice::<Value>(&body) else {
return StatusCode::BAD_REQUEST;
};
if hook.adapter.take_payload(&payload, &hook.sender) {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
}
}
#[async_trait]
impl Taker for WhatsAppAdapter {
type Press = Carried;
fn channel_name(&self) -> &'static str {
WHATSAPP_CHANNEL
}
async fn take(
&self,
gateway: &ChannelGateway,
update: &Update<Carried>,
paired: bool,
) -> adk_kernel::Result<()> {
let Some(mut inbound) = update.inbound.clone() else { return Ok(()) };
let carried = update.press.as_ref();
if paired
&& let Some((id, declared)) = carried.and_then(|carried| carried.media.as_ref())
&& let Some(attachment) = self.inner.api.download(id, declared.as_deref()).await
{
inbound = inbound.with_attachments([attachment]);
}
let card = match &inbound.body {
InboundBody::Answer { decision, .. } => Some(PressedCard {
card: carried.and_then(|carried| carried.card.clone()),
decision: decision.clone(),
}),
_ => None,
};
let handling = Handling::of(WHATSAPP_CHANNEL, gateway, &inbound, paired, card);
HANDLING.scope(handling, gateway.receive(inbound)).await.map(drop)
}
async fn not_taken(&self, update: &Update<Carried>) {
let Some(inbound) = &update.inbound else { return };
let card = update.press.as_ref().and_then(|carried| carried.card.as_deref());
let (text, reply_to) = match card {
Some(card) => (ANSWER_NOT_TAKEN, Some(card)),
None => (MESSAGE_NOT_TAKEN, Some(inbound.message_id.as_str())),
};
let body = wire::text(&inbound.thread, text, reply_to);
if let Err(error) = self.send(&inbound.thread, &body).await {
tracing::debug!(error = %error, "a person could not be told their message was not taken");
}
}
}
#[async_trait]
impl ChannelSink for WhatsAppAdapter {
fn channel(&self) -> &str {
WHATSAPP_CHANNEL
}
async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
for body in wire::plain(thread, text) {
self.send(thread, &body).await?;
}
Ok(())
}
async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
let (heading, card) = self.inner.kit.prepare(card).await;
self.send(thread, &wire::card(thread, &card, &heading, self.inner.kit.offset))
.await
.map(drop)
}
async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
self.send(thread, &wire::message(thread, &stopped_words(notice), None)).await.map(drop)
}
async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
let card = self.inner.kit.before_notice(WHATSAPP_CHANNEL, WHATSAPP, thread, notice).await;
let card = card.filter(|card| !card.is_empty());
let words = notice_words(notice, self.inner.kit.offset, Utc::now(), card.is_some());
self.send(thread, &wire::message(thread, &words, card.as_deref())).await.map(drop)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn adapter() -> WhatsAppAdapter {
WhatsAppAdapter::builder("1001", "EAAG-secret")
.app_secret("app-secret")
.verify_token("verify-me")
.build()
.unwrap()
}
#[test]
fn a_body_is_taken_only_with_the_app_secrets_signature() {
let adapter = adapter();
let body = br#"{"object":"whatsapp_business_account"}"#;
let mut mac = Hmac::<Sha256>::new_from_slice(b"app-secret").unwrap();
mac.update(body);
let hex: String = mac.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect();
assert!(adapter.signed(body, &format!("sha256={hex}")));
assert!(!adapter.signed(b"{}", &format!("sha256={hex}")), "another body");
assert!(!adapter.signed(body, &hex), "no scheme");
assert!(!adapter.signed(body, "sha256=zz"), "not hex");
assert!(!adapter.signed(body, &format!("sha256={}", "0".repeat(64))));
assert!(same(b"abc", b"abc") && !same(b"abc", b"abd") && !same(b"abc", b"ab"));
}
#[test]
fn the_builder_needs_the_webhooks_secrets_and_never_echoes_them() {
let missing =
WhatsAppAdapter::builder("1001", "EAAG-secret").verify_token("v").build().unwrap_err();
assert!(missing.to_string().contains("WHATSAPP_APP_SECRET"), "{missing}");
let missing =
WhatsAppAdapter::builder("1001", "EAAG-secret").app_secret("s").build().unwrap_err();
assert!(missing.to_string().contains("WHATSAPP_VERIFY_TOKEN"), "{missing}");
let bad = WhatsAppAdapter::builder("+1 555", "EAAG-secret")
.app_secret("s")
.verify_token("v")
.build()
.unwrap_err();
assert!(!bad.to_string().contains("secret"), "{bad}");
assert!(!format!("{:?}", adapter()).contains("secret"));
assert_eq!(ChannelSink::channel(&adapter()), "whatsapp");
}
#[test]
fn the_window_is_open_for_a_day_after_the_person_writes() {
let mut state = WindowState::default();
assert_eq!(state.open("t", 1000), None, "unknown: WhatsApp decides");
state.last_written.insert("t".into(), 1000);
assert_eq!(state.open("t", 1000 + WINDOW_SECS - 1), Some(true));
assert_eq!(state.open("t", 1000 + WINDOW_SECS), Some(false));
assert!(state.first_time("wamid.1") && !state.first_time("wamid.1"));
for index in 0..SEEN_KEPT + 1 {
state.first_time(&format!("wamid.x{index}"));
}
assert!(state.first_time("wamid.1"), "forgotten after {SEEN_KEPT}");
}
}