Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat(chatwoot): verify signed webhooks with per-device secrets (#914)

gobeyondptyf7c8fcd8069d
diff --git a/docs/chatwoot.md b/docs/chatwoot.md
index 2bedcfa1..0b3bedb7 100644
--- a/docs/chatwoot.md
+++ b/docs/chatwoot.md
@@ -38,8 +38,9 @@ Before setting up the integration, ensure you have:
| `CHATWOOT_IMPORT_MEDIA_WITH_REST` | No | `false` | Direct-DB import media mode. `true` sends downloadable media rows through Chatwoot REST so ActiveStorage attachments are created; non-media rows still use direct DB. Media uploaded this way gets Chatwoot's upload timestamp. |
| `CHATWOOT_AUTO_CREATE` | No | `false` | Startup provisioning mode. When `true`, the app lists inboxes, reuses an API-channel inbox named `CHATWOOT_INBOX_NAME`, or creates one using `CHATWOOT_WEBHOOK_URL`; then it fills `CHATWOOT_INBOX_ID` in memory. |
| `CHATWOOT_INBOX_NAME` | No | `WhatsApp` | Inbox name used only by auto-provisioning. The app reuses a same-name `Channel::Api` inbox, but ignores same-name non-API inboxes because they cannot receive API-channel reply webhooks. |
-| `CHATWOOT_WEBHOOK_URL` | Reply webhook | - | Public URL Chatwoot should call for agent replies: `https://your-gowa.example.com/chatwoot/webhook`. Used when creating an API inbox automatically, and useful as the value to place in an existing API channel's `webhook_url`. Include `?secret=...` when using `CHATWOOT_WEBHOOK_SECRET` and Chatwoot cannot send custom headers. |
-| `CHATWOOT_WEBHOOK_SECRET` | Recommended | - | Shared secret expected by GOWA for incoming Chatwoot webhook calls. If empty, webhooks are accepted without this extra check. If set, the request must send the value via `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`, `?secret=...`, or an `X-Hub-Signature-256` HMAC signature. |
+| `CHATWOOT_WEBHOOK_URL` | Reply webhook | - | Public URL Chatwoot should call for agent replies: `https://your-gowa.example.com/chatwoot/webhook`. Used when creating an API inbox automatically, and useful as the value to place in an existing API channel's `webhook_url`. Keep the secret out of this URL when Chatwoot signs its webhooks; see [Webhook Secret](#webhook-secret). |
+| `CHATWOOT_WEBHOOK_SECRET` | Recommended | - | Secret that authenticates incoming Chatwoot webhook calls. If empty, webhooks are accepted without this check. If set, the request must carry Chatwoot's own signature (`X-Chatwoot-Signature` + `X-Chatwoot-Timestamp`, recommended) or present the secret through `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`, `?secret=...`, or an `X-Hub-Signature-256` HMAC signature. |
+| `CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE` | No | `5m` | Maximum age (and clock difference) of the `X-Chatwoot-Timestamp` accepted with Chatwoot's signature. Older or further-ahead requests are rejected, which limits replay of a captured request. |
| `CHATWOOT_REOPEN_CONVERSATION` | No | `true` | When a contact has a resolved conversation and messages again, reopen/reuse that conversation instead of starting a new thread. Keeps REST and direct-DB behavior aligned. |
| `CHATWOOT_CONVERSATION_PENDING` | No | `false` | Create new conversations with status `pending` instead of `open`, so they land in the unassigned queue. Applies to REST and direct-DB paths. |
| `CHATWOOT_IGNORE_JIDS` | No | - | Comma-separated exact JIDs or wildcards to never mirror to Chatwoot. Supports exact values plus `@g.us`, `@s.whatsapp.net`, and `@lid`. System JIDs such as `status@broadcast` are already ignored. |
@@ -60,8 +61,9 @@ CHATWOOT_API_TOKEN=your_api_token_here
CHATWOOT_ACCOUNT_ID=12345
CHATWOOT_INBOX_ID=67890
CHATWOOT_DEVICE_ID=my-whatsapp-device
-CHATWOOT_WEBHOOK_SECRET=strong-shared-secret
-CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
+# The API channel's webhook secret from Chatwoot; Chatwoot signs every webhook with it.
+CHATWOOT_WEBHOOK_SECRET=secret-shown-by-chatwoot
+CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook
# Optional: History sync settings
CHATWOOT_IMPORT_MESSAGES=true
@@ -81,9 +83,9 @@ CHATWOOT_INBOX_ID=1
# Local GOWA device id or device JID.
-# Agent reply callback from Chatwoot to GOWA.
-CHATWOOT_WEBHOOK_SECRET=strong-shared-secret
-CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
+# Agent reply callback from Chatwoot to GOWA, verified by Chatwoot's signature.
+CHATWOOT_WEBHOOK_SECRET=secret-shown-by-chatwoot
+CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook
# Optional history import.
CHATWOOT_IMPORT_MESSAGES=true
@@ -110,8 +112,8 @@ services:
- CHATWOOT_ACCOUNT_ID=12345
- CHATWOOT_INBOX_ID=67890
- CHATWOOT_DEVICE_ID=my-device
- - CHATWOOT_WEBHOOK_SECRET=strong-shared-secret
- - CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
+ - CHATWOOT_WEBHOOK_SECRET=secret-shown-by-chatwoot
+ - CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook
command: rest
```
@@ -124,7 +126,7 @@ services:
5. Choose the WhatsApp device for agent replies and set `CHATWOOT_DEVICE_ID` when more than one device exists.
6. Make GOWA publicly reachable at `https://your-gowa.example.com/chatwoot/webhook`.
7. Set the API channel inbox webhook URL to that public GOWA webhook URL.
-8. Set `CHATWOOT_WEBHOOK_SECRET` and send the same value through the webhook URL query string or a supported header.
+8. Set `CHATWOOT_WEBHOOK_SECRET` to the API channel's webhook secret so GOWA verifies Chatwoot's signature (see [Webhook Secret](#webhook-secret)). On a Chatwoot version that does not sign webhooks, send the secret through a supported header or, as a last resort, the webhook URL query string.
9. Restart GOWA after changing `.env`; the webhook and sync routes are registered at process startup.
10. Verify with `/chatwoot/sync/status` and a webhook curl before going live.
@@ -163,9 +165,10 @@ For agent replies from Chatwoot to WhatsApp, configure the webhook URL on the **
2. Open the API-channel inbox used for WhatsApp.
3. Set the API channel webhook URL to:
```text
- https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
+ https://your-gowa.example.com/chatwoot/webhook
```
4. Save the inbox.
+5. Copy the inbox's webhook secret into `CHATWOOT_WEBHOOK_SECRET` so GOWA can verify that each call really comes from Chatwoot. If your Chatwoot version shows no webhook secret, see [Webhook Secret](#webhook-secret) for the alternatives.
> **Important:** The webhook URL must be publicly accessible. If GOWA runs locally, use a tunneling service such as ngrok and set the full tunnel URL, including `/chatwoot/webhook`.
@@ -184,8 +187,8 @@ CHATWOOT_API_TOKEN=your_api_token
CHATWOOT_ACCOUNT_ID=12345
CHATWOOT_AUTO_CREATE=true
CHATWOOT_INBOX_NAME=WhatsApp # optional, defaults to "WhatsApp"
-CHATWOOT_WEBHOOK_SECRET=super-secret-key # optional, but recommended
-CHATWOOT_WEBHOOK_URL=https://your-api.com/chatwoot/webhook?secret=super-secret-key
+CHATWOOT_WEBHOOK_URL=https://your-api.com/chatwoot/webhook
+CHATWOOT_WEBHOOK_SECRET= # recommended; see the note below
```
On startup the app will:
@@ -199,28 +202,71 @@ Notes:
- If `CHATWOOT_INBOX_ID` is already set, it takes precedence and auto-create is skipped (your explicit value wins).
- If `CHATWOOT_WEBHOOK_URL` is empty, the inbox is still created but **agent replies won't reach WhatsApp** until you set the webhook — a warning is logged.
- Provisioning failures are non-fatal; the app keeps running and you can fall back to manual setup.
+- Chatwoot generates the webhook secret of a new inbox, so it cannot be known before the inbox exists. After the first start, copy the secret from the created inbox into `CHATWOOT_WEBHOOK_SECRET` and restart. Until then the webhook endpoint is unauthenticated. See [Webhook Secret](#webhook-secret).
## Webhook Secret
-`CHATWOOT_WEBHOOK_SECRET` protects GOWA's public `/chatwoot/webhook` endpoint. It is the value GOWA expects to receive from Chatwoot on every agent-reply webhook.
+`CHATWOOT_WEBHOOK_SECRET` protects GOWA's public `/chatwoot/webhook` endpoint, which sits outside basic auth so Chatwoot can reach it. When it is empty, GOWA accepts Chatwoot webhooks without this check. When it is set, a request is accepted only if it proves knowledge of the secret in one of these ways:
-When `CHATWOOT_WEBHOOK_SECRET` is empty, GOWA accepts Chatwoot webhooks without this extra check. When it is set, GOWA accepts the request only if the same secret arrives in one of these forms:
+| Method | What Chatwoot (or a proxy) sends | Notes |
+|--------|----------------------------------|-------|
+| **Chatwoot signature** (recommended) | `X-Chatwoot-Timestamp: <unix seconds>` and `X-Chatwoot-Signature: sha256=<hex HMAC-SHA256 of "<timestamp>.<raw body>">` | Sent by Chatwoot itself (v4.x) when the API channel has a webhook secret. The secret never travels with the request, the body cannot be altered, and a captured request stops working after `CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE` (5 minutes by default). |
+| HMAC of the body | `X-Hub-Signature-256: sha256=<hex HMAC-SHA256 of the raw body>` | For an intermediate system that signs the body. No timestamp, so no replay protection. |
+| Header | `X-Chatwoot-Webhook-Secret: <secret>` or `X-Gowa-Chatwoot-Secret: <secret>` | For a reverse proxy that adds a header. The secret travels with every request. |
+| Query string | `/chatwoot/webhook?secret=<secret>` | Works with any Chatwoot version, but **the secret is part of the URL** — see the warning below. |
-| Method | Example | When to use |
-|--------|---------|-------------|
-| Header | `X-Chatwoot-Webhook-Secret: strong-shared-secret` | Best when a proxy or webhook sender can set custom headers. |
-| Header | `X-Gowa-Chatwoot-Secret: strong-shared-secret` | Same as above; provided as a GOWA-specific header name. |
-| Query string | `/chatwoot/webhook?secret=strong-shared-secret` | Practical for Chatwoot API-channel inbox webhook URLs because the inbox stores a URL, not custom headers. |
-| HMAC signature | `X-Hub-Signature-256: sha256=<digest>` | Use when an intermediate system can sign the raw request body with the shared secret. |
+### Recommended: Chatwoot's signed webhooks
+
+1. In Chatwoot, open the API-channel inbox and copy its webhook secret. Chatwoot generates one per API channel on versions that sign webhooks.
+2. Set it in GOWA and keep the webhook URL free of secrets:
+
+ ```bash
+ CHATWOOT_WEBHOOK_SECRET=secret-shown-by-chatwoot
+ CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook
+ ```
+3. Set the inbox's webhook URL to the plain `https://your-gowa.example.com/chatwoot/webhook`.
+
+GOWA recomputes the HMAC over the timestamp and the raw request body, compares it in constant time, and rejects timestamps more than the tolerance away from its own clock in either direction. Keep both hosts' clocks synchronized (NTP); a `401` with `timestamp outside the tolerance window` in the GOWA log means they have drifted apart.
+
+With [per-device configs](#per-device--multi-inbox-routing), each inbox is a different API channel with its own secret. Store it on the device config as `webhook_secret`; it then protects that device instead of the global secret.
+
+### Which secret protects a delivery
+
+The secret that applies is the secret of the device the webhook is routed to, on both endpoints:
+
+- The device has its own `webhook_secret`: the request must prove that secret. The global secret is not accepted for it, and neither is another device's secret.
+- The device has no `webhook_secret`: the global `CHATWOOT_WEBHOOK_SECRET` applies; when that is empty too, the device accepts unauthenticated webhooks.
+- No device resolves (unknown inbox, or an event GOWA ignores such as `conversation_updated`): the global secret applies. Nothing is sent for such a request either way.
+
+This holds for the shared `/chatwoot/webhook` endpoint as well, which picks the device from the payload: nothing is sent, revoked, marked as read, or written before the request has been verified against the routed device's secret. A request signed with a device's secret is accepted there for that device's inbox, so several inboxes with different secrets can share the one URL. Events GOWA ignores are still checked against the global secret only, so prefer the per-device URL when devices have their own secrets and a global secret is also set.
-For a plain Chatwoot API-channel inbox, use:
+When `CHATWOOT_WEBHOOK_SECRET` is empty and at least one device has its own secret, an agent reply that resolves to no device is answered `401`, the same as a wrong secret, so the response does not show which account/inbox pairs are mapped to a protected device. Without any device secret such a request is acknowledged with `200` and dropped, as before.
+
+### Replayed requests
+
+What a captured, valid request can do depends on how it was authenticated:
+
+- **Chatwoot signature:** GOWA remembers the timestamp and signature of every verified request it accepted (answered `2xx`) for the tolerance window. A second copy of such a request is acknowledged with `200` and not acted on, and after the window the timestamp check rejects it. A request that was not accepted, for example one answered `503` while storage was unavailable, is not remembered, so the identical request sent again is handled. A copy that arrives while the first is still being handled waits for it: it is acknowledged as a repeat when the first is accepted, handled in its place when the first fails, and answered `503` without being acted on if the first is still not finished after 30 seconds.
+
+ This memory is held in the GOWA process: it is lost on a restart, so a captured request can be delivered once more if GOWA restarts while the request is still inside the window, and it is not shared between several GOWA instances behind one URL. It holds up to 65,536 accepted requests. Beyond that GOWA keeps accepting webhooks and forgets the oldest request of whichever secret has the most remembered, so a forgotten request could be replayed inside its window. Only verified requests are remembered, so reaching the limit takes a valid secret, and a flood signed with one device's secret pushes out that device's own entries: each other secret keeps at least its newest 65,536 / (number of secrets in use) requests.
+- **`X-Hub-Signature-256`, secret header, `?secret=`:** nothing in the request identifies one delivery, so a captured request can be sent again for as long as the secret is unchanged. The secret header and query string also hand the secret itself to whoever captures the request.
+
+GOWA does not otherwise deduplicate agent replies: if Chatwoot delivers the same message twice in two separately signed requests, it is sent to WhatsApp twice.
+
+### Query-string secret
+
+> **Warning:** a secret in the URL is written wherever URLs are written: reverse-proxy and load-balancer access logs, Chatwoot's own logs and error reports, monitoring tools, and the inbox settings page that every Chatwoot administrator can open. Treat it as exposed once it has been used, and prefer the signature above.
+
+Use `?secret=` only when your Chatwoot version does not sign webhooks and you cannot put a proxy in front of GOWA that adds a header:
```bash
CHATWOOT_WEBHOOK_SECRET=strong-shared-secret
CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
```
-The query-string form is less ideal than a header because URLs may appear in logs. If that is a concern, put a reverse proxy in front of GOWA: let Chatwoot call a secret-free URL on the proxy, then have the proxy add `X-Chatwoot-Webhook-Secret` before forwarding to GOWA.
+GOWA logs a one-time warning when a webhook is authenticated this way. To move an existing deployment to signatures: set `CHATWOOT_WEBHOOK_SECRET` to the channel's webhook secret and restart GOWA — Chatwoot's signature is accepted from then on — then remove `?secret=...` from the inbox webhook URL and treat the old secret as exposed.
+
+All methods stay accepted side by side: a request that carries a Chatwoot signature made with a different secret is still accepted if it also presents the configured secret in another way.
## Multi-Device Setup
@@ -278,6 +324,7 @@ curl -X PUT http://your-api:3000/devices/<device_id>/chatwoot/config \
"account_id": 12345,
"inbox_id": 67890,
"api_token": "device-specific-token",
+ "webhook_secret": "secret-of-this-inbox-api-channel",
"enabled": true
}'
@@ -298,6 +345,12 @@ through another's path.
- **api_token** is stored as-is in the local database and is masked (last 4 chars) in all API
reads. Treat the GOWA database as a secret store.
+- **webhook_secret** (optional) is the webhook secret of this inbox's API channel. When set, it
+ protects every webhook routed to this device, on `/chatwoot/webhook/<device_id>` and on the
+ shared `/chatwoot/webhook`, in place of the global `CHATWOOT_WEBHOOK_SECRET` and with the same
+ accepted methods (see [Which secret protects a delivery](#which-secret-protects-a-delivery)).
+ It is never returned: reads only report `webhook_secret_set`. Omit the field on update to keep
+ the stored value; send an empty string to remove it.
- **`chatwoot_url`** is validated: only `http`/`https`, no embedded credentials, and hosts that
resolve to private/loopback/link-local/metadata addresses are rejected (SSRF hardening). Set
`CHATWOOT_ALLOWED_HOSTS` to a comma-separated allowlist to restrict it further.
@@ -700,16 +753,17 @@ Look for log entries starting with:
| `device id is required` | No device ID and multiple devices exist | Set `CHATWOOT_DEVICE_ID` |
| `failed to create contact` | Chatwoot API error | Verify API token and account permissions |
| `Invalid payload` | Malformed webhook request | Check Chatwoot webhook configuration |
-| `401 Unauthorized` on `/chatwoot/webhook` | `CHATWOOT_WEBHOOK_SECRET` is set but the request did not send the expected secret | Add `?secret=<value>` to the API-channel webhook URL, send `X-Chatwoot-Webhook-Secret`, send `X-Gowa-Chatwoot-Secret`, or send a valid `X-Hub-Signature-256` |
+| `401 Unauthorized` on `/chatwoot/webhook` | `CHATWOOT_WEBHOOK_SECRET` is set but the request did not prove it | Set `CHATWOOT_WEBHOOK_SECRET` (or the device's `webhook_secret`) to the API channel's webhook secret so Chatwoot's `X-Chatwoot-Signature` verifies. The GOWA log says why a signature was rejected: `signature does not match` is a different secret, `timestamp outside the tolerance window` is clock drift between the hosts. Otherwise send `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`, a valid `X-Hub-Signature-256`, or `?secret=<value>` |
| `CHATWOOT_NOT_CONFIGURED` | Missing URL, token, account ID, or inbox ID | Set `CHATWOOT_URL`, `CHATWOOT_API_TOKEN`, numeric `CHATWOOT_ACCOUNT_ID`, and numeric `CHATWOOT_INBOX_ID`, or enable auto-provisioning |
### Verifying Webhook Connectivity
-Test your webhook endpoint. If `CHATWOOT_WEBHOOK_SECRET` is set, include it in the query string or a supported header:
+Test your webhook endpoint. If `CHATWOOT_WEBHOOK_SECRET` is set, present it in a header for the test (to test the signed form, see the snippet below):
```bash
-curl -X POST "https://your-api.com/chatwoot/webhook?secret=strong-shared-secret" \
+curl -X POST "https://your-api.com/chatwoot/webhook" \
-H "Content-Type: application/json" \
+ -H "X-Chatwoot-Webhook-Secret: strong-shared-secret" \
-d '{
"event": "message_created",
"message_type": "outgoing",
@@ -729,6 +783,20 @@ curl -X POST "https://your-api.com/chatwoot/webhook?secret=strong-shared-secret"
Expected response: `200 OK` or error with details
+To send a request signed the way Chatwoot signs it:
+
+```bash
+SECRET='secret-shown-by-chatwoot'
+BODY='{"event":"conversation_updated"}'
+TS=$(date +%s)
+SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}')
+curl -X POST "https://your-api.com/chatwoot/webhook" \
+ -H "Content-Type: application/json" \
+ -H "X-Chatwoot-Timestamp: $TS" \
+ -H "X-Chatwoot-Signature: sha256=$SIG" \
+ -d "$BODY"
+```
+
Test the authenticated sync status endpoint:
```bash
@@ -756,7 +824,7 @@ Expected response: `200 OK` with `status` such as `idle`, `running`, or `complet
- Monitor for unusual activity in Chatwoot logs
- Use strong authentication for the WhatsApp API (`APP_BASIC_AUTH`)
- **Note:** The `/chatwoot/webhook` endpoint is excluded from basic auth to allow Chatwoot to send webhooks without credentials. The `/chatwoot/sync` endpoints require authentication.
-- Set `CHATWOOT_WEBHOOK_SECRET` for the unauthenticated webhook route. Prefer headers or HMAC signatures when possible; use `?secret=...` for Chatwoot API-channel inboxes when no custom header injection is available.
+- Set `CHATWOOT_WEBHOOK_SECRET` for the unauthenticated webhook route and let GOWA verify Chatwoot's own signature (`X-Chatwoot-Signature`). Avoid `?secret=...`: a secret in the URL leaks into access logs and into Chatwoot's inbox settings.
## API Reference
@@ -766,17 +834,17 @@ Expected response: `200 OK` with `status` such as `idle`, `running`, or `complet
**Headers:**
- `Content-Type: application/json`
-- Optional when `CHATWOOT_WEBHOOK_SECRET` is set: `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`, or `X-Hub-Signature-256`
+- When `CHATWOOT_WEBHOOK_SECRET` is set, one of: `X-Chatwoot-Signature` with `X-Chatwoot-Timestamp` (Chatwoot's signature, recommended), `X-Hub-Signature-256`, `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`
**Query Parameters:**
-- Optional when `CHATWOOT_WEBHOOK_SECRET` is set: `secret=<CHATWOOT_WEBHOOK_SECRET>`
+- Alternative when `CHATWOOT_WEBHOOK_SECRET` is set and no header can be sent: `secret=<CHATWOOT_WEBHOOK_SECRET>` (discouraged: the secret ends up in logs)
**Request Body:** Standard Chatwoot webhook payload
**Response Codes:**
-- `200 OK` - Message processed (or skipped)
-- `401 Unauthorized` - Webhook secret or signature is missing/invalid
-- `503 Service Unavailable` - No device available
+- `200 OK` - Message processed (or skipped, including a repeated copy of an already handled signed request)
+- `401 Unauthorized` - Webhook secret or signature is missing/invalid for the device the request is routed to, or the signature's timestamp is outside the tolerance window
+- `503 Service Unavailable` - No device available, or the routed device's config could not be read to authenticate the request, or an identical signed request is still being handled
### Related Endpoints
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index f9face5f..19abc313 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -4146,6 +4146,41 @@ paths:
description: |
Receives webhook events from Chatwoot and sends messages to WhatsApp.
Configure this URL in your Chatwoot inbox webhook settings.
+
+ When CHATWOOT_WEBHOOK_SECRET is set the request must prove knowledge of
+ it. Recommended: Chatwoot's own signature, sent by Chatwoot when the API
+ channel has a webhook secret — `X-Chatwoot-Timestamp` (unix seconds) and
+ `X-Chatwoot-Signature: sha256=<hex HMAC-SHA256 of "<timestamp>.<raw body>">`.
+ The timestamp must be within CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE (5m by
+ default) of the server clock. Also accepted: `X-Hub-Signature-256`
+ (HMAC-SHA256 of the raw body), the secret in `X-Chatwoot-Webhook-Secret`
+ or `X-Gowa-Chatwoot-Secret`, or the `secret` query parameter (discouraged:
+ the secret then appears in URLs and logs).
+
+ The secret that applies is the secret of the device the payload is
+ routed to: that device config's `webhook_secret` when it has one (the
+ global secret is then not accepted for it), CHATWOOT_WEBHOOK_SECRET
+ otherwise and when no device resolves. A Chatwoot-signed request that
+ was already accepted (answered 2xx) inside the tolerance window is
+ acknowledged with 200 and not acted on again. One that was answered
+ with any other status is not remembered, so sending the identical
+ request again is handled.
+ parameters:
+ - name: X-Chatwoot-Signature
+ in: header
+ description: 'Chatwoot signature: sha256=<hex HMAC-SHA256 of "<timestamp>.<raw body>" keyed with the webhook secret>'
+ schema:
+ type: string
+ - name: X-Chatwoot-Timestamp
+ in: header
+ description: Unix time (seconds) the webhook was signed at
+ schema:
+ type: string
+ - name: secret
+ in: query
+ description: The webhook secret. Discouraged; prefer the signature headers.
+ schema:
+ type: string
requestBody:
content:
application/json:
@@ -4155,8 +4190,10 @@ paths:
responses:
'200':
description: Webhook processed
+ '401':
+ description: Secret or signature missing or invalid for the device the request is routed to, or the signature timestamp is outside the tolerance window
'503':
- description: Device not available
+ description: Device not available, the routed device's config could not be read, or an identical signed request is still being handled
content:
application/json:
schema:
@@ -4172,10 +4209,13 @@ paths:
Per-device variant of the Chatwoot webhook: configure each device's Chatwoot
inbox to POST here (the URL is returned as `webhook_url` by the device config
endpoints) so agent replies route deterministically to that device.
- Route-by-config: in addition to the optional shared secret, the payload's
+ Route-by-config: in addition to the optional secret, the payload's
account and inbox must match the device's stored config or the request is
rejected with 401. Unknown device ids and non-message events are acknowledged
with 200 and ignored.
+ The request is authenticated like `/chatwoot/webhook`, with the device
+ config's `webhook_secret` when it has one and CHATWOOT_WEBHOOK_SECRET
+ otherwise.
parameters:
- name: device_id
in: path
@@ -4193,7 +4233,9 @@ paths:
'200':
description: Webhook processed (or acknowledged and ignored)
'401':
- description: Invalid secret, or payload account/inbox does not match the device's config
+ description: Invalid secret or signature, or payload account/inbox does not match the device's config
+ '503':
+ description: The device's config could not be read, so the request could not be authenticated, or an identical signed request is still being handled
/chatwoot/configs:
get:
@@ -4292,6 +4334,14 @@ paths:
api_token:
type: string
description: Chatwoot agent/bot API token. Required on create; empty (or the masked value) keeps the stored token on update.
+ webhook_secret:
+ type: string
+ description: |
+ Webhook secret of this inbox's API channel. When set it protects every
+ webhook routed to this device (on `/chatwoot/webhook/{device_id}` and on
+ the shared `/chatwoot/webhook`) instead of
+ CHATWOOT_WEBHOOK_SECRET. Omit to keep the stored value; send an empty
+ string to remove it. Never returned by the API.
enabled:
type: boolean
default: true
@@ -4426,6 +4476,10 @@ components:
type: string
description: URL to set on this device's Chatwoot inbox so agent replies route back to this device
example: 'https://gowa.example.com/chatwoot/webhook/my-device-id'
+ webhook_secret_set:
+ type: boolean
+ description: Whether this device has its own webhook secret (the secret itself is never returned)
+ example: true
created_at:
type: string
format: date-time
diff --git a/readme.md b/readme.md
index 5d1bb7fb..3fca6e00 100644
--- a/readme.md
+++ b/readme.md
@@ -292,8 +292,9 @@ To use environment variables:
| `CHATWOOT_IMPORT_MEDIA_WITH_REST` | Upload direct-DB import media rows through Chatwoot REST | `false` | `CHATWOOT_IMPORT_MEDIA_WITH_REST=true` |
| `CHATWOOT_AUTO_CREATE` | Auto-create or reuse the Chatwoot API inbox at startup | `false` | `CHATWOOT_AUTO_CREATE=true` |
| `CHATWOOT_INBOX_NAME` | Inbox name used when auto-create is enabled | `WhatsApp` | `CHATWOOT_INBOX_NAME=WhatsApp Support` |
-| `CHATWOOT_WEBHOOK_URL` | Public GOWA Chatwoot reply webhook URL | - | `CHATWOOT_WEBHOOK_URL=https://api.example.com/chatwoot/webhook?secret=shared` |
-| `CHATWOOT_WEBHOOK_SECRET` | Shared secret required for incoming Chatwoot webhooks | - | `CHATWOOT_WEBHOOK_SECRET=shared` |
+| `CHATWOOT_WEBHOOK_URL` | Public GOWA Chatwoot reply webhook URL | - | `CHATWOOT_WEBHOOK_URL=https://api.example.com/chatwoot/webhook` |
+| `CHATWOOT_WEBHOOK_SECRET` | Secret for incoming Chatwoot webhooks (verifies Chatwoot's signature) | - | `CHATWOOT_WEBHOOK_SECRET=channel-webhook-secret` |
+| `CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE` | Maximum age of a signed Chatwoot webhook's timestamp | `5m` | `CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE=2m` |
| `CHATWOOT_REOPEN_CONVERSATION` | Reopen resolved Chatwoot conversations for returning contacts | `true` | `CHATWOOT_REOPEN_CONVERSATION=false` |
| `CHATWOOT_CONVERSATION_PENDING` | Create new Chatwoot conversations as pending | `false` | `CHATWOOT_CONVERSATION_PENDING=true` |
| `CHATWOOT_IGNORE_JIDS` | JIDs or wildcards to exclude from Chatwoot forwarding | - | `[email protected],[email protected]` |
diff --git a/src/.env.example b/src/.env.example
index 4d8dc1c6..d457f231 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -90,7 +90,10 @@ CHATWOOT_IMPORT_MEDIA_WITH_REST=false
CHATWOOT_AUTO_CREATE=false
CHATWOOT_INBOX_NAME=WhatsApp
CHATWOOT_WEBHOOK_URL=
+# The API channel's webhook secret: GOWA then verifies Chatwoot's X-Chatwoot-Signature.
+# Keep the secret out of CHATWOOT_WEBHOOK_URL (no ?secret=...): URLs end up in logs.
CHATWOOT_WEBHOOK_SECRET=
+CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE=5m
# Conversation handling
CHATWOOT_REOPEN_CONVERSATION=true
CHATWOOT_CONVERSATION_PENDING=false
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index f801793b..9ee6c1a5 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -97,6 +97,9 @@ func restServer(_ *cobra.Command, _ []string) {
if config.AppBasePath != "" {
webhookPath = config.AppBasePath + webhookPath
}
+ // In front of both webhook routes: a Chatwoot-signed request is only
+ // remembered as delivered once it has been answered 2xx.
+ app.Use(webhookPath, rest.ChatwootWebhookReplayGuard())
app.Post(webhookPath, chatwootHandler.HandleWebhook)
// Per-device webhook: each device's Chatwoot inbox is configured to POST
// here so agent replies route deterministically to the right device.
diff --git a/src/cmd/root.go b/src/cmd/root.go
index c199a187..4275ea65 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -276,6 +276,11 @@ func initEnvConfig() {
if envChatwootWebhookSecret := viper.GetString("chatwoot_webhook_secret"); envChatwootWebhookSecret != "" {
config.ChatwootWebhookSecret = envChatwootWebhookSecret
}
+ if viper.IsSet("chatwoot_webhook_signature_tolerance") {
+ if tolerance := viper.GetDuration("chatwoot_webhook_signature_tolerance"); tolerance > 0 {
+ config.ChatwootWebhookSignatureTolerance = tolerance
+ }
+ }
if envChatwootAllowedHosts := viper.GetString("chatwoot_allowed_hosts"); envChatwootAllowedHosts != "" {
config.ChatwootAllowedHosts = splitCommaTrimmed(envChatwootAllowedHosts)
}
@@ -593,6 +598,12 @@ func initFlags() {
config.ChatwootWebhookSecret,
`shared secret required for incoming Chatwoot webhooks --chatwoot-webhook-secret <string> | example: --chatwoot-webhook-secret="super-secret-key"`,
)
+ rootCmd.PersistentFlags().DurationVarP(
+ &config.ChatwootWebhookSignatureTolerance,
+ "chatwoot-webhook-signature-tolerance", "",
+ config.ChatwootWebhookSignatureTolerance,
+ `maximum age (and clock skew) of the timestamp on Chatwoot's signed webhooks --chatwoot-webhook-signature-tolerance <duration> | example: --chatwoot-webhook-signature-tolerance=5m`,
+ )
rootCmd.PersistentFlags().StringSliceVarP(
&config.ChatwootAllowedHosts,
"chatwoot-allowed-hosts", "",
diff --git a/src/config/settings.go b/src/config/settings.go
index 9d2f70ed..ef7e6fb4 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -125,6 +125,10 @@ var (
// Optional shared secret for incoming Chatwoot webhooks. When empty, inbound
// webhook requests remain unauthenticated for backward compatibility.
ChatwootWebhookSecret = ""
+ // ChatwootWebhookSignatureTolerance bounds the age (and clock skew) of the
+ // X-Chatwoot-Timestamp accepted with Chatwoot's signed webhooks, which
+ // limits how long a captured request can be replayed.
+ ChatwootWebhookSignatureTolerance = 5 * time.Minute
// ChatwootAllowedHosts optionally restricts which Chatwoot hosts a
// per-device config may point at. When non-empty, a config's chatwoot_url
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index 35aa00f4..d28cc83d 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -113,6 +113,9 @@ type ChatwootDeviceConfig struct {
Enabled bool `db:"enabled"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
+ // WebhookSecret authenticates Chatwoot's webhooks on this device's own
+ // endpoint. Empty means the global CHATWOOT_WEBHOOK_SECRET applies.
+ WebhookSecret string `db:"webhook_secret"`
}
// ChatwootForwardEvent is a durable retry record for a live WhatsApp event
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index 70b46866..456ededb 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -1302,14 +1302,14 @@ func (r *SQLiteRepository) DeleteChatwootMessageLinksByConfig(configID int64) er
return err
}
-const chatwootDeviceConfigColumns = `id, device_id, device_jid, chatwoot_url, account_id, inbox_id, api_token, enabled, created_at, updated_at`
+const chatwootDeviceConfigColumns = `id, device_id, device_jid, chatwoot_url, account_id, inbox_id, api_token, enabled, created_at, updated_at, webhook_secret`
func (r *SQLiteRepository) scanChatwootDeviceConfig(scanner interface{ Scan(...any) error }) (*domainChatStorage.ChatwootDeviceConfig, error) {
cfg := &domainChatStorage.ChatwootDeviceConfig{}
err := scanner.Scan(
&cfg.ID, &cfg.DeviceID, &cfg.DeviceJID, &cfg.ChatwootURL,
&cfg.AccountID, &cfg.InboxID, &cfg.APIToken, &cfg.Enabled,
- &cfg.CreatedAt, &cfg.UpdatedAt,
+ &cfg.CreatedAt, &cfg.UpdatedAt, &cfg.WebhookSecret,
)
return cfg, err
}
@@ -1332,10 +1332,10 @@ func (r *SQLiteRepository) SaveChatwootDeviceConfig(cfg *domainChatStorage.Chatw
result, err := r.db.Exec(`
UPDATE chatwoot_device_configs
SET device_jid = ?, chatwoot_url = ?, account_id = ?, inbox_id = ?,
- api_token = ?, enabled = ?, updated_at = ?
+ api_token = ?, enabled = ?, webhook_secret = ?, updated_at = ?
WHERE device_id = ?
`, cfg.DeviceJID, cfg.ChatwootURL, cfg.AccountID, cfg.InboxID,
- cfg.APIToken, cfg.Enabled, cfg.UpdatedAt, cfg.DeviceID)
+ cfg.APIToken, cfg.Enabled, cfg.WebhookSecret, cfg.UpdatedAt, cfg.DeviceID)
if err != nil {
return err
}
@@ -1345,11 +1345,11 @@ func (r *SQLiteRepository) SaveChatwootDeviceConfig(cfg *domainChatStorage.Chatw
res, err := r.db.Exec(`
INSERT INTO chatwoot_device_configs (
device_id, device_jid, chatwoot_url, account_id, inbox_id,
- api_token, enabled, created_at, updated_at
+ api_token, enabled, webhook_secret, created_at, updated_at
)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`, cfg.DeviceID, cfg.DeviceJID, cfg.ChatwootURL, cfg.AccountID, cfg.InboxID,
- cfg.APIToken, cfg.Enabled, cfg.CreatedAt, cfg.UpdatedAt)
+ cfg.APIToken, cfg.Enabled, cfg.WebhookSecret, cfg.CreatedAt, cfg.UpdatedAt)
if err != nil {
return err
}
@@ -3167,5 +3167,8 @@ func (r *SQLiteRepository) getMigrations() []string {
// Migration 49: Persist reply context for live, sent, and history messages.
`ALTER TABLE messages ADD COLUMN context_metadata TEXT DEFAULT ''`,
+
+ // Migration 50: Per-device secret for Chatwoot's signed webhooks (each API channel has its own)
+ `ALTER TABLE chatwoot_device_configs ADD COLUMN webhook_secret TEXT NOT NULL DEFAULT ''`,
}
}
diff --git a/src/infrastructure/chatstorage/sqlite_repository_chatwoot_config_test.go b/src/infrastructure/chatstorage/sqlite_repository_chatwoot_config_test.go
index 5c2fd86b..346efbee 100644
--- a/src/infrastructure/chatstorage/sqlite_repository_chatwoot_config_test.go
+++ b/src/infrastructure/chatstorage/sqlite_repository_chatwoot_config_test.go
@@ -1,9 +1,14 @@
package chatstorage
import (
+ "database/sql"
+ "path/filepath"
+ "strings"
"testing"
+ "time"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"
)
func TestSQLiteRepositoryChatwootDeviceConfigCRUD(t *testing.T) {
@@ -315,3 +320,156 @@ func TestSQLiteRepositoryDeleteChatwootMessageLinksByConfig(t *testing.T) {
t.Fatal("legacy link must survive")
}
}
+
+// TestSQLiteRepositoryChatwootDeviceConfigWebhookSecret covers the per-device
+// webhook secret through insert, update and every lookup that reads a config.
+func TestSQLiteRepositoryChatwootDeviceConfigWebhookSecret(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+
+ cfg := &domainChatStorage.ChatwootDeviceConfig{
+ DeviceID: "busine",
+ DeviceJID: "[email protected]",
+ ChatwootURL: "https://chat.example.com",
+ AccountID: 1,
+ InboxID: 5,
+ APIToken: "tok-a",
+ Enabled: true,
+ WebhookSecret: "channel-secret",
+ }
+ if err := repo.SaveChatwootDeviceConfig(cfg); err != nil {
+ t.Fatalf("save config: %v", err)
+ }
+
+ byDevice, err := repo.GetChatwootDeviceConfig("busine")
+ if err != nil || byDevice == nil || byDevice.WebhookSecret != "channel-secret" {
+ t.Fatalf("get by device: %v (%+v)", err, byDevice)
+ }
+ byJID, err := repo.GetChatwootDeviceConfigByIdentifier("[email protected]")
+ if err != nil || byJID == nil || byJID.WebhookSecret != "channel-secret" {
+ t.Fatalf("get by identifier: %v (%+v)", err, byJID)
+ }
+ byInbox, err := repo.GetChatwootDeviceConfigByInbox(1, 5)
+ if err != nil || byInbox == nil || byInbox.WebhookSecret != "channel-secret" {
+ t.Fatalf("get by inbox: %v (%+v)", err, byInbox)
+ }
+ all, err := repo.ListChatwootDeviceConfigs()
+ if err != nil || len(all) != 1 || all[0].WebhookSecret != "channel-secret" {
+ t.Fatalf("list: %v (%+v)", err, all)
+ }
+
+ cfg.WebhookSecret = ""
+ if err := repo.SaveChatwootDeviceConfig(cfg); err != nil {
+ t.Fatalf("update config: %v", err)
+ }
+ cleared, err := repo.GetChatwootDeviceConfig("busine")
+ if err != nil || cleared == nil || cleared.WebhookSecret != "" {
+ t.Fatalf("after clearing: %v (%+v)", err, cleared)
+ }
+
+ // A config saved without a secret (every existing row after the migration)
+ // reads back empty, which means "use the global secret".
+ plain := &domainChatStorage.ChatwootDeviceConfig{
+ DeviceID: "other", ChatwootURL: "https://chat.example.com", AccountID: 1, InboxID: 6, APIToken: "tok-b", Enabled: true,
+ }
+ if err := repo.SaveChatwootDeviceConfig(plain); err != nil {
+ t.Fatalf("save plain config: %v", err)
+ }
+ got, err := repo.GetChatwootDeviceConfig("other")
+ if err != nil || got == nil || got.WebhookSecret != "" {
+ t.Fatalf("plain config: %v (%+v)", err, got)
+ }
+}
+
+// TestSQLiteRepositoryWebhookSecretMigrationKeepsExistingConfigs upgrades a
+// database that already held device configs before the webhook_secret column
+// existed: the schema is built up to the migration before it, rows are written
+// with that older schema, and only then is the rest migrated.
+func TestSQLiteRepositoryWebhookSecretMigrationKeepsExistingConfigs(t *testing.T) {
+ db, err := sql.Open(sqlite.DriverName, filepath.Join(t.TempDir(), "chatstorage.db"))
+ if err != nil {
+ t.Fatalf("open sqlite database: %v", err)
+ }
+ t.Cleanup(func() { _ = db.Close() })
+ repo := &SQLiteRepository{db: db}
+
+ // Locate the migration by what it does, so migrations added around it do
+ // not invalidate the test.
+ migrations := repo.getMigrations()
+ secretMigration := -1
+ for i, migration := range migrations {
+ if strings.Contains(migration, "chatwoot_device_configs ADD COLUMN webhook_secret") {
+ secretMigration = i
+ }
+ }
+ if secretMigration < 0 {
+ t.Fatal("webhook_secret migration not found")
+ }
+ if _, err := repo.getSchemaVersion(); err != nil {
+ t.Fatalf("create schema_info: %v", err)
+ }
+ for i := 0; i < secretMigration; i++ {
+ if err := repo.runMigration(migrations[i], i+1); err != nil {
+ t.Fatalf("migration %d: %v", i+1, err)
+ }
+ }
+
+ var columns int
+ if err := db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('chatwoot_device_configs') WHERE name = 'webhook_secret'`).Scan(&columns); err != nil || columns != 0 {
+ t.Fatalf("pre-change schema already has webhook_secret (count=%d err=%v)", columns, err)
+ }
+
+ created := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
+ for _, row := range []struct {
+ deviceID, deviceJID string
+ inboxID int
+ enabled bool
+ }{
+ {"busine", "[email protected]", 5, true},
+ {"unpaired", "", 6, false},
+ } {
+ if _, err := db.Exec(`
+ INSERT INTO chatwoot_device_configs (
+ device_id, device_jid, chatwoot_url, account_id, inbox_id,
+ api_token, enabled, created_at, updated_at
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `, row.deviceID, row.deviceJID, "https://chat.example.com", 1, row.inboxID, "tok-"+row.deviceID, row.enabled, created, created); err != nil {
+ t.Fatalf("insert pre-change row %s: %v", row.deviceID, err)
+ }
+ }
+
+ // The upgrade: the same call the application makes at startup.
+ if err := repo.InitializeSchema(); err != nil {
+ t.Fatalf("upgrade: %v", err)
+ }
+ if version, err := repo.getSchemaVersion(); err != nil || version != len(migrations) {
+ t.Fatalf("schema version = %d err=%v, want %d", version, err, len(migrations))
+ }
+
+ all, err := repo.ListChatwootDeviceConfigs()
+ if err != nil || len(all) != 2 {
+ t.Fatalf("list after upgrade: %v (%d rows, want 2)", err, len(all))
+ }
+ busine, err := repo.GetChatwootDeviceConfigByIdentifier("[email protected]")
+ if err != nil || busine == nil {
+ t.Fatalf("get upgraded row: %v (%+v)", err, busine)
+ }
+ if busine.DeviceID != "busine" || busine.InboxID != 5 || busine.APIToken != "tok-busine" || !busine.Enabled ||
+ !busine.CreatedAt.Equal(created) || busine.WebhookSecret != "" {
+ t.Fatalf("upgraded row changed or has a non-empty secret: %+v", busine)
+ }
+ unpaired, err := repo.GetChatwootDeviceConfig("unpaired")
+ if err != nil || unpaired == nil || unpaired.Enabled || unpaired.WebhookSecret != "" {
+ t.Fatalf("second upgraded row: %v (%+v)", err, unpaired)
+ }
+
+ // An upgraded row accepts a secret like a new one.
+ busine.WebhookSecret = "channel-secret"
+ if err := repo.SaveChatwootDeviceConfig(busine); err != nil {
+ t.Fatalf("save secret on upgraded row: %v", err)
+ }
+ got, err := repo.GetChatwootDeviceConfig("busine")
+ if err != nil || got == nil || got.WebhookSecret != "channel-secret" || got.ID != busine.ID {
+ t.Fatalf("secret on upgraded row: %v (%+v)", err, got)
+ }
+}
diff --git a/src/infrastructure/chatwoot/AGENTS.md b/src/infrastructure/chatwoot/AGENTS.md
index 27a9d5b0..00e91c2e 100644
--- a/src/infrastructure/chatwoot/AGENTS.md
+++ b/src/infrastructure/chatwoot/AGENTS.md
@@ -11,7 +11,8 @@ Direct Postgres changes have a [scoped guide](pgimport/AGENTS.md).
exist, `ClientRegistry` must not fall back to the global env inbox for an unmapped
or disabled device. Numeric account/inbox IDs differ from API-channel identifiers.
- Webhooks in `../../ui/rest/chatwoot.go` bypass app Basic Auth and check
- `CHATWOOT_WEBHOOK_SECRET` when configured. Only outgoing messages send back to
+ `CHATWOOT_WEBHOOK_SECRET` when configured; a routed device's own `webhook_secret`
+ takes its place, on the shared endpoint too (`chatwootWebhookRouteGate`). Only outgoing messages send back to
WhatsApp; preserve `source_id = WAID:<message_id>` and sent-message echo guards.
- Persistent links support idempotency, replies, read/delete sync, and reverse
routing. Preserve device/account/config scope; separate servers can reuse numeric
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
index a966f9eb..53888cbe 100644
--- a/src/ui/AGENTS.md
+++ b/src/ui/AGENTS.md
@@ -11,7 +11,12 @@ usecases. REST and MCP share the `rest` process and device manager.
outside it. Pass `whatsapp.ContextWithDevice(c.Context(), getDeviceFromCtx(c))`
to device-bound usecases. Browser websockets select a device with `?device_id=`.
- Route/auth order lives in `../cmd/rest.go`. Chatwoot webhooks are mounted before
- Basic Auth but enforce `CHATWOOT_WEBHOOK_SECRET` when configured. Keep manual
+ Basic Auth but enforce `CHATWOOT_WEBHOOK_SECRET` when configured. A device config's own
+ `webhook_secret` replaces it for that device on both endpoints: call
+ `chatwootWebhookRouteGate` with the final route before acting on a webhook. Mount
+ `ChatwootWebhookReplayGuard` in front of the webhook routes: it remembers a signed
+ request only once the whole handler chain answered 2xx, so answer non-2xx for a
+ delivery that must be sent again. Keep manual
sync/config routes authenticated and preserve webhook device routing and echo guards.
New public routes need an explicit public contract, such as a health check or webhook.
diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.go
index 6e3516f7..e533f716 100644
--- a/src/ui/rest/chatwoot.go
+++ b/src/ui/rest/chatwoot.go
@@ -95,35 +95,6 @@ func chatwootSecretMatches(expected, candidate string) bool {
return subtle.ConstantTimeCompare([]byte(expected), []byte(candidate)) == 1
}
-func chatwootWebhookAuthorized(c fiber.Ctx) bool {
- secret := strings.TrimSpace(config.ChatwootWebhookSecret)
- if secret == "" {
- return true
- }
-
- for _, candidate := range []string{
- c.Get("X-Chatwoot-Webhook-Secret"),
- c.Get("X-Gowa-Chatwoot-Secret"),
- c.Query("secret"),
- } {
- if chatwootSecretMatches(secret, candidate) {
- return true
- }
- }
-
- signature := strings.TrimSpace(c.Get("X-Hub-Signature-256"))
- if signature == "" {
- return false
- }
-
- digest, err := utils.GetMessageDigestOrSignature(c.Body(), []byte(secret))
- if err != nil {
- logrus.Errorf("Chatwoot Webhook: Failed to compute webhook signature: %v", err)
- return false
- }
- return chatwootSecretMatches("sha256="+digest, signature)
-}
-
func chatwootLinkChatJID(destination string) string {
clean := utils.CleanPhoneForWhatsApp(destination)
if clean == "" {
@@ -335,27 +306,62 @@ func (h *ChatwootHandler) resolveChatwootForDevice(deviceID string) *chatwoot.Re
// device is resolved from the payload (conversation link, contact attrs, inbox
// map, or env fallback).
func (h *ChatwootHandler) HandleWebhook(c fiber.Ctx) error {
- if !chatwootWebhookAuthorized(c) {
- logrus.Warn("Chatwoot Webhook: Rejected request with invalid secret")
- return c.SendStatus(fiber.StatusUnauthorized)
+ // The global secret is the default here, not the last word: a delivery is
+ // protected by the secret of the device it is routed to
+ // (chatwootWebhookRouteGate, applied once the route is known). A request
+ // the global secret does not cover is only let through when it resolves to
+ // a device and verifies against that device's secret.
+ globalOK, nativeErr := chatwootWebhookVerify(c, config.ChatwootWebhookSecret)
+
+ var payload chatwoot.WebhookPayload
+ bindErr := c.Bind().Body(&payload)
+
+ if !globalOK {
+ route, routed := h.chatwootSharedWebhookRoute(payload, bindErr)
+ if !routed {
+ logChatwootSignatureRejection(nativeErr)
+ logrus.Warn("Chatwoot Webhook: Rejected request with invalid secret")
+ return c.SendStatus(fiber.StatusUnauthorized)
+ }
+ if status := h.chatwootWebhookRouteGate(c, route); status != 0 && status != fiber.StatusOK {
+ return c.SendStatus(status)
+ }
}
logrus.Debugf("Chatwoot Webhook raw body: %s", string(c.Body()))
- var payload chatwoot.WebhookPayload
- if err := c.Bind().Body(&payload); err != nil {
+ if bindErr != nil {
return utils.ResponseError(c, "Invalid payload")
}
return h.processChatwootWebhook(c, payload, nil)
}
+// chatwootSharedWebhookRoute resolves the device a shared-endpoint payload is
+// for, so a request the global secret does not cover can be checked against
+// that device's secret. Only message events name an account and inbox to
+// resolve; everything else stays under the global secret.
+func (h *ChatwootHandler) chatwootSharedWebhookRoute(payload chatwoot.WebhookPayload, bindErr error) (chatwootWebhookRoute, bool) {
+ if bindErr != nil || (payload.Event != "message_created" && payload.Event != "message_updated") {
+ return chatwootWebhookRoute{}, false
+ }
+ route := h.resolveChatwootWebhookRoute(payload, nil)
+ return route, !route.Unroutable
+}
+
// HandleDeviceWebhook is the per-device endpoint (/chatwoot/webhook/:device_id)
// provisioned on each device's Chatwoot inbox. It is route-BY-config, not
// trust-by-path: in addition to the shared secret it verifies that the payload's
// account and inbox match the device's configured account and inbox, so a
// webhook for one device cannot be delivered through another device's path.
func (h *ChatwootHandler) HandleDeviceWebhook(c fiber.Ctx) error {
- if !chatwootWebhookAuthorized(c) {
+ secret, err := h.deviceWebhookSecret(c)
+ if err != nil {
+ // Fail closed: without the device's config it is unknown whether the
+ // device has its own secret, and the global one may be empty.
+ logrus.Errorf("Chatwoot Webhook: cannot authenticate per-device request: %v", err)
+ return c.SendStatus(fiber.StatusServiceUnavailable)
+ }
+ if !chatwootWebhookAuthorizedWith(c, secret) {
logrus.Warn("Chatwoot Webhook: Rejected per-device request with invalid secret")
return c.SendStatus(fiber.StatusUnauthorized)
}
@@ -409,6 +415,28 @@ func (h *ChatwootHandler) HandleDeviceWebhook(c fiber.Ctx) error {
return h.processChatwootWebhook(c, payload, forced)
}
+// deviceWebhookSecret returns the secret that authenticates the per-device
+// endpoint for the device named in the path: the device config's own
+// webhook_secret when it has one (each Chatwoot API channel has its own
+// secret), otherwise the global CHATWOOT_WEBHOOK_SECRET. An unknown device
+// uses the global secret, so it is authenticated exactly as before per-device
+// secrets existed. A storage error is returned so the caller can refuse the
+// request instead of guessing.
+func (h *ChatwootHandler) deviceWebhookSecret(c fiber.Ctx) (string, error) {
+ if h == nil || h.ChatStorageRepo == nil {
+ return config.ChatwootWebhookSecret, nil
+ }
+ deviceID := pathDeviceID(c)
+ if h.DeviceManager != nil {
+ resolved, ok := h.resolveConfigDeviceID(c)
+ if !ok {
+ return config.ChatwootWebhookSecret, nil
+ }
+ deviceID = resolved
+ }
+ return h.chatwootRouteWebhookSecret(chatwootWebhookRoute{DeviceID: deviceID})
+}
+
// processChatwootWebhook performs the event gating shared by both webhook
// endpoints, then delivers an agent reply using either the forced route (when
// set by the per-device endpoint) or one resolved from the payload.
@@ -456,6 +484,11 @@ func (h *ChatwootHandler) processChatwootWebhook(c fiber.Ctx, payload chatwoot.W
route.InboxID = forced.InboxID
route.Unroutable = false
}
+ // Nothing below may act on the request before this: the delivery is
+ // protected by the routed device's secret, whichever endpoint it came in on.
+ if status := h.chatwootWebhookRouteGate(c, route); status != 0 {
+ return c.SendStatus(status)
+ }
if route.Unroutable {
// Fail-fast for real: without this, the empty DeviceID would resolve to
// the default device below and the reply would go out from the wrong
@@ -580,6 +613,10 @@ func (h *ChatwootHandler) handleDeletedChatwootMessage(c fiber.Ctx, payload chat
route.DeviceID = forced.DeviceID
route.Unroutable = false
}
+ // A delete revokes a WhatsApp message: same gate as a send.
+ if status := h.chatwootWebhookRouteGate(c, route); status != 0 {
+ return c.SendStatus(status)
+ }
if route.Unroutable {
return c.SendStatus(fiber.StatusOK)
}
diff --git a/src/ui/rest/chatwoot_config.go b/src/ui/rest/chatwoot_config.go
index 6ccadb7b..59bcd8ba 100644
--- a/src/ui/rest/chatwoot_config.go
+++ b/src/ui/rest/chatwoot_config.go
@@ -22,6 +22,10 @@ type chatwootConfigRequest struct {
InboxID int `json:"inbox_id"`
APIToken string `json:"api_token"`
Enabled *bool `json:"enabled"`
+ // WebhookSecret is the secret Chatwoot signs this inbox's webhooks with.
+ // Omitted keeps the stored value; an empty string clears it (the global
+ // CHATWOOT_WEBHOOK_SECRET then applies).
+ WebhookSecret *string `json:"webhook_secret"`
}
// maskAPIToken redacts a stored token for read responses, revealing only the
@@ -60,8 +64,10 @@ func chatwootConfigView(cfg *domainChatStorage.ChatwootDeviceConfig) map[string]
"api_token": maskAPIToken(cfg.APIToken),
"enabled": cfg.Enabled,
"webhook_url": perDeviceWebhookURL(cfg.DeviceID),
- "created_at": cfg.CreatedAt,
- "updated_at": cfg.UpdatedAt,
+ // The secret itself is never returned, only whether one is set.
+ "webhook_secret_set": strings.TrimSpace(cfg.WebhookSecret) != "",
+ "created_at": cfg.CreatedAt,
+ "updated_at": cfg.UpdatedAt,
}
}
@@ -167,14 +173,22 @@ func (h *ChatwootHandler) UpsertChatwootConfig(c fiber.Ctx) error {
enabled = existing.Enabled
}
+ webhookSecret := ""
+ if req.WebhookSecret != nil {
+ webhookSecret = strings.TrimSpace(*req.WebhookSecret)
+ } else if existing != nil {
+ webhookSecret = existing.WebhookSecret
+ }
+
cfg := &domainChatStorage.ChatwootDeviceConfig{
- DeviceID: deviceID,
- DeviceJID: h.deviceJID(deviceID),
- ChatwootURL: canonicalURL,
- AccountID: req.AccountID,
- InboxID: req.InboxID,
- APIToken: apiToken,
- Enabled: enabled,
+ DeviceID: deviceID,
+ DeviceJID: h.deviceJID(deviceID),
+ ChatwootURL: canonicalURL,
+ AccountID: req.AccountID,
+ InboxID: req.InboxID,
+ APIToken: apiToken,
+ Enabled: enabled,
+ WebhookSecret: webhookSecret,
}
if existing != nil {
cfg.ID = existing.ID
diff --git a/src/ui/rest/chatwoot_device_webhook_test.go b/src/ui/rest/chatwoot_device_webhook_test.go
index ba96c66f..bc545fa7 100644
--- a/src/ui/rest/chatwoot_device_webhook_test.go
+++ b/src/ui/rest/chatwoot_device_webhook_test.go
@@ -27,6 +27,13 @@ func (r *deviceWebhookTestRepo) GetChatwootDeviceConfigByIdentifier(identifier s
return nil, nil
}
+func (r *deviceWebhookTestRepo) ListChatwootDeviceConfigs() ([]*domainChatStorage.ChatwootDeviceConfig, error) {
+ if r.cfg == nil {
+ return nil, nil
+ }
+ return []*domainChatStorage.ChatwootDeviceConfig{r.cfg}, nil
+}
+
func (r *deviceWebhookTestRepo) GetChatwootDeviceConfigByInbox(accountID, inboxID int) (*domainChatStorage.ChatwootDeviceConfig, error) {
return nil, nil
}
diff --git a/src/ui/rest/chatwoot_webhook_auth.go b/src/ui/rest/chatwoot_webhook_auth.go
new file mode 100644
index 00000000..327cfd68
--- /dev/null
+++ b/src/ui/rest/chatwoot_webhook_auth.go
@@ -0,0 +1,288 @@
+package rest
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/gofiber/fiber/v3"
+ "github.com/sirupsen/logrus"
+)
+
+// Headers Chatwoot sets when the API channel has a webhook secret (Chatwoot
+// lib/webhooks/trigger.rb): the unix time of the delivery and
+// "sha256=<hex HMAC-SHA256 of '<timestamp>.<raw body>' keyed with the secret>".
+const (
+ chatwootSignatureHeader = "X-Chatwoot-Signature"
+ chatwootTimestampHeader = "X-Chatwoot-Timestamp"
+)
+
+var (
+ errChatwootSignatureMissing = errors.New("signature or timestamp header missing")
+ errChatwootSignatureTimestamp = errors.New("timestamp is not a unix time")
+ errChatwootSignatureExpired = errors.New("timestamp outside the tolerance window")
+ errChatwootSignatureMalformed = errors.New("signature is not sha256=<hex>")
+ errChatwootSignatureMismatch = errors.New("signature does not match")
+)
+
+// verifyChatwootSignature checks Chatwoot's native webhook signature. The
+// timestamp is part of the signed string, so it cannot be changed without
+// invalidating the signature; rejecting timestamps outside tolerance (in
+// either direction, to allow for clock differences) bounds how long a captured
+// request can be replayed.
+func verifyChatwootSignature(secret, timestamp, signature string, body []byte, now time.Time, tolerance time.Duration) error {
+ timestamp = strings.TrimSpace(timestamp)
+ signature = strings.TrimSpace(signature)
+ if secret == "" || timestamp == "" || signature == "" {
+ return errChatwootSignatureMissing
+ }
+
+ seconds, err := strconv.ParseInt(timestamp, 10, 64)
+ if err != nil {
+ return errChatwootSignatureTimestamp
+ }
+ if age := now.Sub(time.Unix(seconds, 0)); age > tolerance || age < -tolerance {
+ return errChatwootSignatureExpired
+ }
+
+ hexDigest, ok := strings.CutPrefix(signature, "sha256=")
+ if !ok {
+ return errChatwootSignatureMalformed
+ }
+ provided, err := hex.DecodeString(hexDigest)
+ if err != nil {
+ return errChatwootSignatureMalformed
+ }
+
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write([]byte(timestamp))
+ mac.Write([]byte{'.'})
+ mac.Write(body)
+ // hmac.Equal compares in constant time.
+ if !hmac.Equal(mac.Sum(nil), provided) {
+ return errChatwootSignatureMismatch
+ }
+ return nil
+}
+
+// chatwootQuerySecretWarning makes the query-string warning a one-off: the
+// point is to tell the operator once, not to add a line per webhook.
+var chatwootQuerySecretWarning sync.Once
+
+// chatwootWebhookAuthorizedWith authenticates an incoming Chatwoot webhook
+// with the given secret. An empty secret accepts every request (the check is
+// opt-in). Otherwise the request must satisfy one of:
+//
+// 1. Chatwoot's own signature: X-Chatwoot-Timestamp + X-Chatwoot-Signature.
+// 2. The secret itself in X-Chatwoot-Webhook-Secret or X-Gowa-Chatwoot-Secret.
+// 3. The secret itself in the ?secret= query parameter.
+// 4. X-Hub-Signature-256: sha256=<hex HMAC-SHA256 of the raw body>.
+//
+// A request that carries a Chatwoot signature which does not verify is still
+// accepted when another scheme does: Chatwoot signs with the channel's own
+// secret, which an existing deployment authenticating through the URL may
+// never have copied into GOWA.
+func chatwootWebhookAuthorizedWith(c fiber.Ctx, secret string) bool {
+ ok, nativeErr := chatwootWebhookVerify(c, secret)
+ if !ok {
+ logChatwootSignatureRejection(nativeErr)
+ }
+ return ok
+}
+
+// logChatwootSignatureRejection says why the Chatwoot signature failed when
+// one was sent: an expired timestamp (clock drift) and a wrong secret need
+// different fixes.
+func logChatwootSignatureRejection(nativeErr error) {
+ if nativeErr != nil && !errors.Is(nativeErr, errChatwootSignatureMissing) {
+ logrus.Warnf("Chatwoot Webhook: %s rejected: %v", chatwootSignatureHeader, nativeErr)
+ }
+}
+
+// chatwootVerifiedSecretKey is the request-local slot remembering the secret
+// this request already verified against, so a second check against the same
+// secret (the per-device endpoint authenticates before parsing, then again
+// once the route is known) neither repeats the work nor mistakes the request
+// for a replay of itself.
+type chatwootVerifiedSecretKey struct{}
+
+// chatwootWebhookVerify is chatwootWebhookAuthorizedWith without the rejection
+// log. The returned error is the outcome of the Chatwoot-signature check, for
+// the caller to log when the request ends up rejected.
+func chatwootWebhookVerify(c fiber.Ctx, secret string) (bool, error) {
+ secret = strings.TrimSpace(secret)
+ if secret == "" {
+ return true, nil
+ }
+ if verified, ok := c.Locals(chatwootVerifiedSecretKey{}).(string); ok && chatwootSecretMatches(secret, verified) {
+ return true, nil
+ }
+
+ now := time.Now()
+ timestamp, signature := c.Get(chatwootTimestampHeader), c.Get(chatwootSignatureHeader)
+ nativeErr := verifyChatwootSignature(secret, timestamp, signature, c.BodyRaw(), now, config.ChatwootWebhookSignatureTolerance)
+ if nativeErr == nil {
+ chatwootReplayAdmit(c, secret, timestamp, signature)
+ c.Locals(chatwootVerifiedSecretKey{}, secret)
+ return true, nil
+ }
+
+ for _, candidate := range []string{
+ c.Get("X-Chatwoot-Webhook-Secret"),
+ c.Get("X-Gowa-Chatwoot-Secret"),
+ } {
+ if chatwootSecretMatches(secret, candidate) {
+ c.Locals(chatwootVerifiedSecretKey{}, secret)
+ return true, nativeErr
+ }
+ }
+
+ if chatwootSecretMatches(secret, c.Query("secret")) {
+ chatwootQuerySecretWarning.Do(func() {
+ logrus.Warn("Chatwoot Webhook: authenticated by the ?secret= query parameter. URLs end up in proxy and access logs; " +
+ "prefer Chatwoot's signed webhooks (set CHATWOOT_WEBHOOK_SECRET to the API channel's webhook secret and drop ?secret= from the URL).")
+ })
+ c.Locals(chatwootVerifiedSecretKey{}, secret)
+ return true, nativeErr
+ }
+
+ if signature := strings.TrimSpace(c.Get("X-Hub-Signature-256")); signature != "" {
+ digest, err := utils.GetMessageDigestOrSignature(c.Body(), []byte(secret))
+ if err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to compute webhook signature: %v", err)
+ return false, nativeErr
+ }
+ if chatwootSecretMatches("sha256="+digest, signature) {
+ c.Locals(chatwootVerifiedSecretKey{}, secret)
+ return true, nativeErr
+ }
+ }
+
+ return false, nativeErr
+}
+
+// chatwootRouteWebhookSecret returns the secret that protects a delivery
+// through the given route: the routed device's own webhook_secret when its
+// config has one (each Chatwoot API channel has its own secret), otherwise the
+// global CHATWOOT_WEBHOOK_SECRET. A route with no device (unroutable) and a
+// device without a config use the global secret.
+//
+// The device is looked up the way delivery resolves it (alias, JID, or the
+// default device for an empty id in legacy mode), under every identifier it is
+// known by, so a route that names the device by its storage JID finds a config
+// stored under the alias. A storage error is returned so the caller can refuse
+// the request instead of guessing.
+func (h *ChatwootHandler) chatwootRouteWebhookSecret(route chatwootWebhookRoute) (string, error) {
+ if h == nil || h.ChatStorageRepo == nil || route.Unroutable {
+ return config.ChatwootWebhookSecret, nil
+ }
+ identifiers := []string{route.DeviceID}
+ if h.DeviceManager != nil {
+ if instance, resolvedID, err := h.DeviceManager.ResolveDevice(route.DeviceID); err == nil {
+ identifiers = append(identifiers, resolvedID)
+ if instance != nil {
+ identifiers = append(identifiers, instance.ID(), instance.JID())
+ }
+ }
+ }
+ tried := make(map[string]struct{}, len(identifiers))
+ for _, identifier := range identifiers {
+ identifier = strings.TrimSpace(identifier)
+ if _, done := tried[identifier]; done || identifier == "" {
+ continue
+ }
+ tried[identifier] = struct{}{}
+ cfg, err := h.ChatStorageRepo.GetChatwootDeviceConfigByIdentifier(identifier)
+ if err != nil {
+ return "", fmt.Errorf("load device config: %w", err)
+ }
+ if cfg == nil {
+ continue
+ }
+ if strings.TrimSpace(cfg.WebhookSecret) != "" {
+ return cfg.WebhookSecret, nil
+ }
+ break
+ }
+ return config.ChatwootWebhookSecret, nil
+}
+
+// anyChatwootDeviceWebhookSecret reports whether any device config carries its
+// own webhook secret.
+func (h *ChatwootHandler) anyChatwootDeviceWebhookSecret() (bool, error) {
+ if h == nil || h.ChatStorageRepo == nil {
+ return false, nil
+ }
+ configs, err := h.ChatStorageRepo.ListChatwootDeviceConfigs()
+ if err != nil {
+ return false, fmt.Errorf("list device configs: %w", err)
+ }
+ for _, cfg := range configs {
+ if cfg != nil && strings.TrimSpace(cfg.WebhookSecret) != "" {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+
+// chatwootWebhookRouteGate is the one authorization decision for acting on a
+// Chatwoot webhook (WhatsApp send or revoke, mark-as-read, Chatwoot note,
+// stored link). It must be called with the final route, after resolution and
+// any forced override, and before anything is acted on. It returns 0 to
+// proceed, or the HTTP status to answer with instead.
+//
+// The request must verify against the secret of the device the delivery is
+// routed to, whichever endpoint it arrived on: a request that only satisfies
+// the global secret is refused for a device that has its own, and one device's
+// secret cannot deliver through another device.
+//
+// When nothing resolves and there is no global secret, no secret applies and
+// the request is acknowledged as before (nothing is acted on for it) - unless
+// some device has its own secret. Then it is answered like a wrong secret, so
+// the status does not tell a caller which account/inbox pairs are protected.
+//
+// A Chatwoot-signed request that was already accepted inside the tolerance
+// window is authentic but handled: it is acknowledged (200) and not acted on.
+// One whose identical copy is still being handled, and stays so for
+// chatwootReplayInFlightWait, is answered 503 and not acted on either.
+func (h *ChatwootHandler) chatwootWebhookRouteGate(c fiber.Ctx, route chatwootWebhookRoute) int {
+ secret, err := h.chatwootRouteWebhookSecret(route)
+ if err != nil {
+ // Fail closed: it is unknown whether the device has its own secret,
+ // and the global one may be empty.
+ logrus.Errorf("Chatwoot Webhook: cannot authenticate request: %v", err)
+ return fiber.StatusServiceUnavailable
+ }
+ if strings.TrimSpace(secret) == "" && route.Unroutable {
+ protected, err := h.anyChatwootDeviceWebhookSecret()
+ if err != nil {
+ logrus.Errorf("Chatwoot Webhook: cannot authenticate request: %v", err)
+ return fiber.StatusServiceUnavailable
+ }
+ if protected {
+ logrus.Warn("Chatwoot Webhook: Rejected request that resolves to no device while devices have their own webhook secret")
+ return fiber.StatusUnauthorized
+ }
+ }
+ if !chatwootWebhookAuthorizedWith(c, secret) {
+ logrus.Warn("Chatwoot Webhook: Rejected request not signed with the routed device's webhook secret")
+ return fiber.StatusUnauthorized
+ }
+ switch outcome, _ := c.Locals(chatwootReplayOutcomeKey{}).(chatwootReplayState); outcome {
+ case chatwootReplayAccepted:
+ logrus.Warnf("Chatwoot Webhook: Ignoring repeated delivery of a signed request (%s already accepted)", chatwootSignatureHeader)
+ return fiber.StatusOK
+ case chatwootReplayInFlight:
+ logrus.Warnf("Chatwoot Webhook: Refusing a signed request whose identical copy is still being handled (%s)", chatwootSignatureHeader)
+ return fiber.StatusServiceUnavailable
+ }
+ return 0
+}
diff --git a/src/ui/rest/chatwoot_webhook_auth_test.go b/src/ui/rest/chatwoot_webhook_auth_test.go
new file mode 100644
index 00000000..8192b1db
--- /dev/null
+++ b/src/ui/rest/chatwoot_webhook_auth_test.go
@@ -0,0 +1,436 @@
+package rest
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/gofiber/fiber/v3"
+)
+
+// chatwootSign signs a body the way Chatwoot does (lib/webhooks/trigger.rb).
+func chatwootSign(secret, timestamp, body string) string {
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write([]byte(timestamp + "." + body))
+ return "sha256=" + hex.EncodeToString(mac.Sum(nil))
+}
+
+// TestVerifyChatwootSignatureKnownVectors pins the scheme against digests
+// computed independently (Python hmac/hashlib), so a change to what is signed
+// — separator, field order, encoding — fails here.
+func TestVerifyChatwootSignatureKnownVectors(t *testing.T) {
+ vectors := []struct {
+ name, secret, timestamp, body, digest string
+ }{
+ {
+ name: "plain payload",
+ secret: "test-secret",
+ timestamp: "1700000000",
+ body: `{"event":"message_created"}`,
+ digest: "9dcdcaaadf7652a518bc7d9ec7403c6cbae2abfba9cf20f561683beec1e34b81",
+ },
+ {
+ name: "non-ascii payload",
+ secret: "whsec_3f9c1a7e",
+ timestamp: "1767225600",
+ body: `{"id":42,"event":"message_created","message_type":"outgoing","content":"hello é"}`,
+ digest: "0bc42c6cb3cae772cdf9274cf326a611f42ecf82daec6fe35e80ae1f3da140c9",
+ },
+ {
+ name: "empty body",
+ secret: "k",
+ timestamp: "0",
+ body: "",
+ digest: "6b4a4b8b3c40f1e8f53a3d36682e5f99f7ad2ac1df1c93dfe336f329167641e7",
+ },
+ }
+ for _, v := range vectors {
+ t.Run(v.name, func(t *testing.T) {
+ seconds, _ := strconv.ParseInt(v.timestamp, 10, 64)
+ now := time.Unix(seconds, 0).Add(30 * time.Second)
+ if err := verifyChatwootSignature(v.secret, v.timestamp, "sha256="+v.digest, []byte(v.body), now, 5*time.Minute); err != nil {
+ t.Fatalf("known vector rejected: %v", err)
+ }
+ // Hex case is not significant.
+ if err := verifyChatwootSignature(v.secret, v.timestamp, "sha256="+strings.ToUpper(v.digest), []byte(v.body), now, 5*time.Minute); err != nil {
+ t.Fatalf("upper-case digest rejected: %v", err)
+ }
+ if got := chatwootSign(v.secret, v.timestamp, v.body); got != "sha256="+v.digest {
+ t.Fatalf("test signer = %s, want the known digest", got)
+ }
+ })
+ }
+}
+
+func TestVerifyChatwootSignatureRejections(t *testing.T) {
+ const (
+ secret = "test-secret"
+ timestamp = "1700000000"
+ body = `{"event":"message_created"}`
+ )
+ signedAt := time.Unix(1700000000, 0)
+ valid := chatwootSign(secret, timestamp, body)
+ tolerance := 5 * time.Minute
+
+ tests := []struct {
+ name string
+ secret string
+ timestamp string
+ signature string
+ body string
+ now time.Time
+ want error
+ }{
+ {"valid at the edge of the window", secret, timestamp, valid, body, signedAt.Add(tolerance), nil},
+ {"valid with the sender's clock ahead", secret, timestamp, valid, body, signedAt.Add(-tolerance), nil},
+ {"expired", secret, timestamp, valid, body, signedAt.Add(tolerance + time.Second), errChatwootSignatureExpired},
+ {"too far in the future", secret, timestamp, valid, body, signedAt.Add(-tolerance - time.Second), errChatwootSignatureExpired},
+ {"wrong secret", "other-secret", timestamp, valid, body, signedAt, errChatwootSignatureMismatch},
+ {"tampered body", secret, timestamp, valid, body + " ", signedAt, errChatwootSignatureMismatch},
+ // A replay with a fresh timestamp: the timestamp is part of what is signed.
+ {"timestamp replaced", secret, "1700000100", valid, body, signedAt.Add(100 * time.Second), errChatwootSignatureMismatch},
+ {"missing signature", secret, timestamp, "", body, signedAt, errChatwootSignatureMissing},
+ {"missing timestamp", secret, "", valid, body, signedAt, errChatwootSignatureMissing},
+ {"no secret configured", "", timestamp, valid, body, signedAt, errChatwootSignatureMissing},
+ {"timestamp not a number", secret, "yesterday", valid, body, signedAt, errChatwootSignatureTimestamp},
+ {"millisecond timestamp", secret, "1700000000000", chatwootSign(secret, "1700000000000", body), body, signedAt, errChatwootSignatureExpired},
+ {"missing sha256 prefix", secret, timestamp, strings.TrimPrefix(valid, "sha256="), body, signedAt, errChatwootSignatureMalformed},
+ {"digest not hex", secret, timestamp, "sha256=not-hex", body, signedAt, errChatwootSignatureMalformed},
+ {"truncated digest", secret, timestamp, valid[:len(valid)-2], body, signedAt, errChatwootSignatureMismatch},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := verifyChatwootSignature(tt.secret, tt.timestamp, tt.signature, []byte(tt.body), tt.now, tolerance)
+ if !errors.Is(err, tt.want) {
+ t.Fatalf("error = %v, want %v", err, tt.want)
+ }
+ })
+ }
+}
+
+type webhookAuthRequest struct {
+ path string
+ body string
+ headers map[string]string
+}
+
+func postChatwootWebhook(t *testing.T, app *fiber.App, r webhookAuthRequest) int {
+ t.Helper()
+ path := r.path
+ if path == "" {
+ path = "/chatwoot/webhook"
+ }
+ req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(r.body))
+ req.Header.Set("Content-Type", "application/json")
+ for name, value := range r.headers {
+ req.Header.Set(name, value)
+ }
+ resp, err := app.Test(req)
+ if err != nil {
+ t.Fatalf("app.Test: %v", err)
+ }
+ return resp.StatusCode
+}
+
+func nowUnix(offset time.Duration) string {
+ return strconv.FormatInt(time.Now().Add(offset).Unix(), 10)
+}
+
+// TestChatwootWebhookAcceptsChatwootSignature drives the real handler. The
+// body is a conversation event, which the handler acknowledges without any
+// device, so the status reflects authentication alone.
+func TestChatwootWebhookAcceptsChatwootSignature(t *testing.T) {
+ const (
+ secret = "channel-secret"
+ body = `{"event":"conversation_updated","account":{"id":1}}`
+ )
+ withChatwootWebhookSecret(t, secret)
+
+ app := fiber.New()
+ app.Post("/chatwoot/webhook", (&ChatwootHandler{}).HandleWebhook)
+
+ signed := func(secret, timestamp, body string) map[string]string {
+ return map[string]string{chatwootTimestampHeader: timestamp, chatwootSignatureHeader: chatwootSign(secret, timestamp, body)}
+ }
+ fresh := nowUnix(0)
+ stale := nowUnix(-6 * time.Minute)
+ ahead := nowUnix(6 * time.Minute)
+
+ tests := []struct {
+ name string
+ request webhookAuthRequest
+ want int
+ }{
+ {"valid signature", webhookAuthRequest{body: body, headers: signed(secret, fresh, body)}, fiber.StatusOK},
+ {"valid signature slightly old", webhookAuthRequest{body: body, headers: signed(secret, nowUnix(-4*time.Minute), body)}, fiber.StatusOK},
+ {"expired timestamp", webhookAuthRequest{body: body, headers: signed(secret, stale, body)}, fiber.StatusUnauthorized},
+ {"timestamp in the future", webhookAuthRequest{body: body, headers: signed(secret, ahead, body)}, fiber.StatusUnauthorized},
+ {"wrong secret", webhookAuthRequest{body: body, headers: signed("other-secret", fresh, body)}, fiber.StatusUnauthorized},
+ {"signed for another body", webhookAuthRequest{body: body, headers: signed(secret, fresh, `{"event":"x"}`)}, fiber.StatusUnauthorized},
+ {"signature without timestamp", webhookAuthRequest{body: body, headers: map[string]string{chatwootSignatureHeader: chatwootSign(secret, fresh, body)}}, fiber.StatusUnauthorized},
+ {"timestamp without signature", webhookAuthRequest{body: body, headers: map[string]string{chatwootTimestampHeader: fresh}}, fiber.StatusUnauthorized},
+ {"no credentials at all", webhookAuthRequest{body: body}, fiber.StatusUnauthorized},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := postChatwootWebhook(t, app, tt.request); got != tt.want {
+ t.Fatalf("status = %d, want %d", got, tt.want)
+ }
+ })
+ }
+}
+
+// TestChatwootWebhookKeepsOlderSchemes: every way of presenting the secret
+// that worked before still works, including next to a Chatwoot signature that
+// does not verify (Chatwoot signs with the channel's own secret, which an
+// existing deployment authenticating through the URL may not use).
+func TestChatwootWebhookKeepsOlderSchemes(t *testing.T) {
+ const (
+ secret = "shared-secret"
+ body = `{"event":"conversation_updated","account":{"id":1}}`
+ )
+ withChatwootWebhookSecret(t, secret)
+
+ app := fiber.New()
+ app.Post("/chatwoot/webhook", (&ChatwootHandler{}).HandleWebhook)
+
+ hub := func(secret, body string) string {
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write([]byte(body))
+ return "sha256=" + hex.EncodeToString(mac.Sum(nil))
+ }
+ foreignSignature := map[string]string{
+ chatwootTimestampHeader: nowUnix(0),
+ chatwootSignatureHeader: chatwootSign("chatwoot-generated-secret", nowUnix(0), body),
+ }
+
+ tests := []struct {
+ name string
+ request webhookAuthRequest
+ want int
+ }{
+ {"X-Chatwoot-Webhook-Secret", webhookAuthRequest{body: body, headers: map[string]string{"X-Chatwoot-Webhook-Secret": secret}}, fiber.StatusOK},
+ {"X-Gowa-Chatwoot-Secret", webhookAuthRequest{body: body, headers: map[string]string{"X-Gowa-Chatwoot-Secret": secret}}, fiber.StatusOK},
+ {"query string", webhookAuthRequest{path: "/chatwoot/webhook?secret=" + secret, body: body}, fiber.StatusOK},
+ {"X-Hub-Signature-256", webhookAuthRequest{body: body, headers: map[string]string{"X-Hub-Signature-256": hub(secret, body)}}, fiber.StatusOK},
+ {"wrong header secret", webhookAuthRequest{body: body, headers: map[string]string{"X-Chatwoot-Webhook-Secret": "nope"}}, fiber.StatusUnauthorized},
+ {"wrong query secret", webhookAuthRequest{path: "/chatwoot/webhook?secret=nope", body: body}, fiber.StatusUnauthorized},
+ {"wrong X-Hub-Signature-256", webhookAuthRequest{body: body, headers: map[string]string{"X-Hub-Signature-256": hub("nope", body)}}, fiber.StatusUnauthorized},
+ {"query string next to a foreign Chatwoot signature", webhookAuthRequest{path: "/chatwoot/webhook?secret=" + secret, body: body, headers: foreignSignature}, fiber.StatusOK},
+ {"foreign Chatwoot signature alone", webhookAuthRequest{body: body, headers: foreignSignature}, fiber.StatusUnauthorized},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := postChatwootWebhook(t, app, tt.request); got != tt.want {
+ t.Fatalf("status = %d, want %d", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestChatwootWebhookWithoutSecretAcceptsEverything(t *testing.T) {
+ withChatwootWebhookSecret(t, "")
+ app := fiber.New()
+ app.Post("/chatwoot/webhook", (&ChatwootHandler{}).HandleWebhook)
+
+ body := `{"event":"conversation_updated"}`
+ for name, headers := range map[string]map[string]string{
+ "no headers": nil,
+ "unverifiable sign": {chatwootTimestampHeader: "1", chatwootSignatureHeader: "sha256=00"},
+ } {
+ if got := postChatwootWebhook(t, app, webhookAuthRequest{body: body, headers: headers}); got != fiber.StatusOK {
+ t.Fatalf("%s: status = %d, want 200 when no secret is configured", name, got)
+ }
+ }
+}
+
+func TestChatwootWebhookSignatureToleranceIsConfigurable(t *testing.T) {
+ const (
+ secret = "channel-secret"
+ body = `{"event":"conversation_updated"}`
+ )
+ withChatwootWebhookSecret(t, secret)
+ prev := config.ChatwootWebhookSignatureTolerance
+ t.Cleanup(func() { config.ChatwootWebhookSignatureTolerance = prev })
+
+ app := fiber.New()
+ app.Post("/chatwoot/webhook", (&ChatwootHandler{}).HandleWebhook)
+
+ timestamp := nowUnix(-2 * time.Minute)
+ request := webhookAuthRequest{body: body, headers: map[string]string{
+ chatwootTimestampHeader: timestamp,
+ chatwootSignatureHeader: chatwootSign(secret, timestamp, body),
+ }}
+
+ config.ChatwootWebhookSignatureTolerance = 5 * time.Minute
+ if got := postChatwootWebhook(t, app, request); got != fiber.StatusOK {
+ t.Fatalf("status = %d, want 200 inside the default window", got)
+ }
+ config.ChatwootWebhookSignatureTolerance = time.Minute
+ if got := postChatwootWebhook(t, app, request); got != fiber.StatusUnauthorized {
+ t.Fatalf("status = %d, want 401 once the window is narrower than the request's age", got)
+ }
+}
+
+// TestChatwootDeviceWebhookUsesDeviceSecret: each Chatwoot API channel has
+// its own secret, so a device config can carry one. It replaces the global
+// secret on that device's endpoint only.
+func TestChatwootDeviceWebhookUsesDeviceSecret(t *testing.T) {
+ const (
+ globalSecret = "global-secret"
+ deviceSecret = "device-channel-secret"
+ body = `{"event":"conversation_updated","account":{"id":1}}`
+ )
+ withChatwootWebhookSecret(t, globalSecret)
+
+ repo := &deviceWebhookTestRepo{
+ cfg: &domainChatStorage.ChatwootDeviceConfig{
+ ID: 1, DeviceID: "d", ChatwootURL: "https://chat.example.com", AccountID: 1, InboxID: 2,
+ APIToken: "t", Enabled: true, WebhookSecret: deviceSecret,
+ },
+ count: 1,
+ }
+ chatwoot.InitClientRegistry(repo)
+ t.Cleanup(func() { chatwoot.InitClientRegistry(nil) })
+
+ app := fiber.New()
+ handler := &ChatwootHandler{ChatStorageRepo: repo}
+ app.Post("/chatwoot/webhook", handler.HandleWebhook)
+ app.Post("/chatwoot/webhook/:device_id", handler.HandleDeviceWebhook)
+
+ signed := func(secret string) map[string]string {
+ timestamp := nowUnix(0)
+ return map[string]string{chatwootTimestampHeader: timestamp, chatwootSignatureHeader: chatwootSign(secret, timestamp, body)}
+ }
+
+ tests := []struct {
+ name string
+ request webhookAuthRequest
+ want int
+ }{
+ {"device endpoint, device secret", webhookAuthRequest{path: "/chatwoot/webhook/d", body: body, headers: signed(deviceSecret)}, fiber.StatusOK},
+ {"device endpoint, global secret is not accepted", webhookAuthRequest{path: "/chatwoot/webhook/d", body: body, headers: signed(globalSecret)}, fiber.StatusUnauthorized},
+ {"device endpoint, device secret in the old header", webhookAuthRequest{path: "/chatwoot/webhook/d", body: body, headers: map[string]string{"X-Chatwoot-Webhook-Secret": deviceSecret}}, fiber.StatusOK},
+ {"device endpoint, no credentials", webhookAuthRequest{path: "/chatwoot/webhook/d", body: body}, fiber.StatusUnauthorized},
+ {"another device falls back to the global secret", webhookAuthRequest{path: "/chatwoot/webhook/other", body: body, headers: signed(globalSecret)}, fiber.StatusOK},
+ {"another device does not accept this device's secret", webhookAuthRequest{path: "/chatwoot/webhook/other", body: body, headers: signed(deviceSecret)}, fiber.StatusUnauthorized},
+ {"shared endpoint keeps the global secret", webhookAuthRequest{body: body, headers: signed(globalSecret)}, fiber.StatusOK},
+ {"shared endpoint does not accept a device secret", webhookAuthRequest{body: body, headers: signed(deviceSecret)}, fiber.StatusUnauthorized},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := postChatwootWebhook(t, app, tt.request); got != tt.want {
+ t.Fatalf("status = %d, want %d", got, tt.want)
+ }
+ })
+ }
+
+ // A device without its own secret keeps using the global one.
+ repo.cfg.WebhookSecret = ""
+ if got := postChatwootWebhook(t, app, webhookAuthRequest{path: "/chatwoot/webhook/d", body: body, headers: signed(globalSecret)}); got != fiber.StatusOK {
+ t.Fatalf("status = %d, want 200 with the global secret when the device has none", got)
+ }
+}
+
+// TestChatwootDeviceSecretProtectsDeviceEndpointWithoutGlobalSecret: with no
+// global secret, a device that has its own is still protected.
+func TestChatwootDeviceSecretProtectsDeviceEndpointWithoutGlobalSecret(t *testing.T) {
+ withChatwootWebhookSecret(t, "")
+ repo := &deviceWebhookTestRepo{
+ cfg: &domainChatStorage.ChatwootDeviceConfig{
+ ID: 1, DeviceID: "d", ChatwootURL: "https://chat.example.com", AccountID: 1, InboxID: 2,
+ APIToken: "t", Enabled: true, WebhookSecret: "device-channel-secret",
+ },
+ count: 1,
+ }
+ chatwoot.InitClientRegistry(repo)
+ t.Cleanup(func() { chatwoot.InitClientRegistry(nil) })
+
+ app := fiber.New()
+ app.Post("/chatwoot/webhook/:device_id", (&ChatwootHandler{ChatStorageRepo: repo}).HandleDeviceWebhook)
+
+ body := `{"event":"conversation_updated"}`
+ if got := postChatwootWebhook(t, app, webhookAuthRequest{path: "/chatwoot/webhook/d", body: body}); got != fiber.StatusUnauthorized {
+ t.Fatalf("unsigned request status = %d, want 401", got)
+ }
+ timestamp := nowUnix(0)
+ headers := map[string]string{chatwootTimestampHeader: timestamp, chatwootSignatureHeader: chatwootSign("device-channel-secret", timestamp, body)}
+ if got := postChatwootWebhook(t, app, webhookAuthRequest{path: "/chatwoot/webhook/d", body: body, headers: headers}); got != fiber.StatusOK {
+ t.Fatalf("signed request status = %d, want 200", got)
+ }
+}
+
+func TestChatwootConfigWebhookSecretIsWriteOnly(t *testing.T) {
+ store := newFakeConfigStore()
+ app := newConfigTestApp(t, store)
+ const base = `"chatwoot_url":"https://203.0.113.10","account_id":1,"inbox_id":5,"api_token":"token-one"`
+
+ resp, body := doJSON(t, app, http.MethodPut, "/devices/dev/chatwoot/config", `{`+base+`,"webhook_secret":" channel-secret "}`)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("create status = %d: %s", resp.StatusCode, body)
+ }
+ if strings.Contains(body, "channel-secret") {
+ t.Fatalf("response leaks the webhook secret: %s", body)
+ }
+ if !strings.Contains(body, `"webhook_secret_set":true`) {
+ t.Fatalf("response must report that a secret is set: %s", body)
+ }
+ if got := store.configs["dev"].WebhookSecret; got != "channel-secret" {
+ t.Fatalf("stored secret = %q, want it trimmed and stored", got)
+ }
+
+ // Omitted on update: the stored secret stays.
+ if resp, body := doJSON(t, app, http.MethodPut, "/devices/dev/chatwoot/config", `{`+base+`,"enabled":false}`); resp.StatusCode != http.StatusOK {
+ t.Fatalf("update status = %d: %s", resp.StatusCode, body)
+ }
+ if got := store.configs["dev"].WebhookSecret; got != "channel-secret" {
+ t.Fatalf("stored secret = %q after an update that omitted it, want it kept", got)
+ }
+ for _, path := range []string{"/devices/dev/chatwoot/config", "/chatwoot/configs"} {
+ _, body := doJSON(t, app, http.MethodGet, path, "")
+ if strings.Contains(body, "channel-secret") || !strings.Contains(body, `"webhook_secret_set":true`) {
+ t.Fatalf("GET %s = %s, want the secret hidden and reported as set", path, body)
+ }
+ }
+
+ // An explicit empty string clears it.
+ resp, body = doJSON(t, app, http.MethodPut, "/devices/dev/chatwoot/config", `{`+base+`,"webhook_secret":""}`)
+ if resp.StatusCode != http.StatusOK || !strings.Contains(body, `"webhook_secret_set":false`) {
+ t.Fatalf("clear status = %d: %s", resp.StatusCode, body)
+ }
+ if got := store.configs["dev"].WebhookSecret; got != "" {
+ t.Fatalf("stored secret = %q, want it cleared", got)
+ }
+}
+
+// failingConfigRepo makes the device config lookup fail.
+type failingConfigRepo struct {
+ domainChatStorage.IChatStorageRepository
+}
+
+func (failingConfigRepo) GetChatwootDeviceConfigByIdentifier(string) (*domainChatStorage.ChatwootDeviceConfig, error) {
+ return nil, errors.New("database is locked")
+}
+
+// TestChatwootDeviceWebhookFailsClosedOnStorageError: when the device config
+// cannot be read it is unknown whether the device has its own secret, so the
+// request is refused even with no global secret configured.
+func TestChatwootDeviceWebhookFailsClosedOnStorageError(t *testing.T) {
+ withChatwootWebhookSecret(t, "")
+ app := fiber.New()
+ app.Post("/chatwoot/webhook/:device_id", (&ChatwootHandler{ChatStorageRepo: failingConfigRepo{}}).HandleDeviceWebhook)
+
+ if got := postChatwootWebhook(t, app, webhookAuthRequest{path: "/chatwoot/webhook/d", body: `{"event":"conversation_updated"}`}); got != fiber.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want 503", got)
+ }
+}
diff --git a/src/ui/rest/chatwoot_webhook_replay.go b/src/ui/rest/chatwoot_webhook_replay.go
new file mode 100644
index 00000000..0e5b1382
--- /dev/null
+++ b/src/ui/rest/chatwoot_webhook_replay.go
@@ -0,0 +1,335 @@
+package rest
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/gofiber/fiber/v3"
+ "github.com/sirupsen/logrus"
+)
+
+// chatwootReplayGuardMaxEntries bounds how many accepted signatures the replay
+// guard remembers. See chatwootReplayGuard for what happens at the bound.
+const chatwootReplayGuardMaxEntries = 1 << 16
+
+// chatwootReplayInFlightWait is how long a signed request waits for an
+// identical request that is still being handled before it is answered 503. It
+// stays below the request timeout so the wait ends with an answer.
+var chatwootReplayInFlightWait = 30 * time.Second
+
+// chatwootReplayState is what the guard knows about a signed request.
+type chatwootReplayState int
+
+const (
+ // chatwootReplayNew: not seen; the caller now holds the reservation and
+ // must commit or release it.
+ chatwootReplayNew chatwootReplayState = iota
+ // chatwootReplayAccepted: an identical request was already accepted.
+ chatwootReplayAccepted
+ // chatwootReplayInFlight: an identical request is being handled right now.
+ chatwootReplayInFlight
+)
+
+// chatwootReplayKey identifies one signed delivery: the signature covers the
+// timestamp and the body and is keyed with the secret.
+type chatwootReplayKey struct {
+ timestamp int64
+ digest [sha256.Size]byte
+}
+
+// chatwootReplayOwner partitions the guard's memory by the secret a request
+// verified against (its SHA-256, so the secret itself is not kept here).
+type chatwootReplayOwner [sha256.Size]byte
+
+type chatwootReplayEntry struct {
+ key chatwootReplayKey
+ expires time.Time
+}
+
+// chatwootReplayGuard keeps a captured Chatwoot-signed request from being
+// acted on twice, without swallowing a request that was never handled.
+//
+// A verified request first reserves its (timestamp, signature) pair. The
+// reservation is committed only when the request was accepted (a 2xx answer)
+// and released on any other outcome, so the same request sent again after a
+// failure is handled. While a reservation is held, an identical request is not
+// handled alongside it.
+//
+// Memory is bounded two ways:
+//
+// - by age: an accepted pair is kept for twice the signature tolerance, which
+// covers every moment the timestamp check could still accept it;
+// - by count: at most max accepted pairs. Past that, the oldest pair of the
+// secret that currently holds the most pairs is forgotten.
+//
+// The count bound trades replay protection for availability: when it is hit,
+// a pair is forgotten early (and could be replayed) rather than new webhooks
+// being refused. Evicting from the largest holder limits who pays for that.
+// Only verified signatures are remembered, so filling the guard takes a valid
+// secret, and whoever does it evicts their own pairs once they hold the most:
+// every other secret keeps at least its newest max/N pairs, N being the number
+// of secrets with remembered pairs. A deployment with a single secret has one
+// holder, and a flood under that secret forgets that secret's oldest pairs.
+//
+// Reservations are not counted against max and are never evicted; there is at
+// most one per request being handled.
+//
+// It is in-process memory: it does not survive a restart and is not shared
+// between instances.
+type chatwootReplayGuard struct {
+ mu sync.Mutex
+ max int
+ size int
+ accepted map[chatwootReplayKey]struct{}
+ // queues hold each owner's accepted pairs in commit order, which is also
+ // expiry order.
+ queues map[chatwootReplayOwner][]chatwootReplayEntry
+ // inFlight maps a reserved pair to a channel closed when it is settled.
+ inFlight map[chatwootReplayKey]chan struct{}
+}
+
+var chatwootReplays = &chatwootReplayGuard{max: chatwootReplayGuardMaxEntries}
+
+// chatwootReplayKeyFor parses a verified timestamp/signature pair.
+func chatwootReplayKeyFor(timestamp, signature string) (chatwootReplayKey, bool) {
+ var key chatwootReplayKey
+ seconds, err := strconv.ParseInt(strings.TrimSpace(timestamp), 10, 64)
+ if err != nil {
+ return key, false
+ }
+ digest, err := hex.DecodeString(strings.TrimPrefix(strings.TrimSpace(signature), "sha256="))
+ if err != nil || len(digest) != len(key.digest) {
+ return key, false
+ }
+ key.timestamp = seconds
+ copy(key.digest[:], digest)
+ return key, true
+}
+
+// reserve reports what is known about key. On chatwootReplayNew the caller
+// holds the reservation and must commit or release it. On
+// chatwootReplayInFlight the returned channel is closed when the holder
+// settles, after which reserve can be tried again.
+func (g *chatwootReplayGuard) reserve(key chatwootReplayKey, now time.Time) (chatwootReplayState, <-chan struct{}) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.forgetExpired(now)
+ if _, ok := g.accepted[key]; ok {
+ return chatwootReplayAccepted, nil
+ }
+ if settled, ok := g.inFlight[key]; ok {
+ return chatwootReplayInFlight, settled
+ }
+ if g.inFlight == nil {
+ g.inFlight = make(map[chatwootReplayKey]chan struct{})
+ }
+ g.inFlight[key] = make(chan struct{})
+ return chatwootReplayNew, nil
+}
+
+// commit turns a reservation into a remembered pair.
+func (g *chatwootReplayGuard) commit(key chatwootReplayKey, owner chatwootReplayOwner, now time.Time, tolerance time.Duration) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.settle(key)
+ g.forgetExpired(now)
+ if _, ok := g.accepted[key]; ok {
+ return
+ }
+ if g.accepted == nil {
+ g.accepted = make(map[chatwootReplayKey]struct{})
+ g.queues = make(map[chatwootReplayOwner][]chatwootReplayEntry)
+ }
+ g.accepted[key] = struct{}{}
+ // A timestamp may be up to tolerance ahead of this clock and is then
+ // accepted until tolerance past it, so twice the tolerance from now covers
+ // every accepted timestamp and keeps expiry in commit order.
+ g.queues[owner] = append(g.queues[owner], chatwootReplayEntry{key: key, expires: now.Add(2 * tolerance)})
+ g.size++
+ for g.max > 0 && g.size > g.max {
+ g.forgetOldestOf(g.largestOwner())
+ }
+}
+
+// release drops a reservation without remembering the pair.
+func (g *chatwootReplayGuard) release(key chatwootReplayKey) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.settle(key)
+}
+
+func (g *chatwootReplayGuard) settle(key chatwootReplayKey) {
+ if settled, ok := g.inFlight[key]; ok {
+ delete(g.inFlight, key)
+ close(settled)
+ }
+}
+
+// forgetExpired drops what the timestamp check now rejects by itself.
+func (g *chatwootReplayGuard) forgetExpired(now time.Time) {
+ for owner, queue := range g.queues {
+ for len(queue) > 0 && !queue[0].expires.After(now) {
+ g.forgetOldestOf(owner)
+ queue = g.queues[owner]
+ }
+ }
+}
+
+func (g *chatwootReplayGuard) largestOwner() chatwootReplayOwner {
+ var largest chatwootReplayOwner
+ most := 0
+ for owner, queue := range g.queues {
+ if len(queue) > most {
+ largest, most = owner, len(queue)
+ }
+ }
+ return largest
+}
+
+func (g *chatwootReplayGuard) forgetOldestOf(owner chatwootReplayOwner) {
+ queue := g.queues[owner]
+ if len(queue) == 0 {
+ return
+ }
+ delete(g.accepted, queue[0].key)
+ g.size--
+ if len(queue) == 1 {
+ delete(g.queues, owner)
+ return
+ }
+ g.queues[owner] = queue[1:]
+}
+
+// reset forgets every accepted pair. Reservations are left to their holders.
+func (g *chatwootReplayGuard) reset() {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.accepted = nil
+ g.queues = nil
+ g.size = 0
+}
+
+// chatwootReplayRequestKey is the request-local slot ChatwootWebhookReplayGuard
+// installs; it carries the reservation the request holds, if any.
+type chatwootReplayRequestKey struct{}
+
+type chatwootReplayRequest struct {
+ held bool
+ key chatwootReplayKey
+ owner chatwootReplayOwner
+}
+
+// chatwootReplayOutcomeKey is the request-local chatwootReplayState set when
+// the request must not be acted on: chatwootReplayAccepted or
+// chatwootReplayInFlight. chatwootWebhookRouteGate turns it into the answer.
+type chatwootReplayOutcomeKey struct{}
+
+// ChatwootWebhookReplayGuard must be mounted in front of the Chatwoot webhook
+// handlers. It settles the replay reservation a Chatwoot-signed request takes
+// when its signature verifies, from the outcome of everything behind it: the
+// signature is remembered only when the request was answered 2xx, and is
+// released on any other status, a returned error, or a panic, so that the same
+// request sent again is handled. Deciding here, and not inside a handler,
+// keeps that true whatever the handlers do before they answer.
+func ChatwootWebhookReplayGuard() fiber.Handler {
+ return func(c fiber.Ctx) error {
+ request := &chatwootReplayRequest{}
+ c.Locals(chatwootReplayRequestKey{}, request)
+
+ accepted := false
+ defer func() {
+ // Runs on a panic too, with accepted still false.
+ if !request.held {
+ return
+ }
+ if accepted {
+ chatwootReplays.commit(request.key, request.owner, time.Now(), config.ChatwootWebhookSignatureTolerance)
+ } else {
+ chatwootReplays.release(request.key)
+ }
+ }()
+
+ err := c.Next()
+ accepted = chatwootResponseAccepted(c, err)
+ return err
+ }
+}
+
+// chatwootResponseAccepted reports whether the request ends in a 2xx answer.
+// A returned error is answered by the error handler: with its own status when
+// it is a *fiber.Error, otherwise as a server error.
+func chatwootResponseAccepted(c fiber.Ctx, err error) bool {
+ status := c.Response().StatusCode()
+ if err != nil {
+ var fiberErr *fiber.Error
+ if !errors.As(err, &fiberErr) {
+ return false
+ }
+ status = fiberErr.Code
+ }
+ return status >= 200 && status < 300
+}
+
+// chatwootReplayUnguardedWarning reports a missing ChatwootWebhookReplayGuard
+// once instead of on every webhook.
+var chatwootReplayUnguardedWarning sync.Once
+
+// chatwootReplayAdmit is called once a request's Chatwoot signature verified
+// against secret. It reserves the signature for this request, or records why
+// the request must not be acted on. While an identical request is being
+// handled it waits for that one to finish: accepted makes this one a repeat,
+// anything else lets this one take its place.
+func chatwootReplayAdmit(c fiber.Ctx, secret, timestamp, signature string) {
+ key, ok := chatwootReplayKeyFor(timestamp, signature)
+ if !ok {
+ return
+ }
+ request, _ := c.Locals(chatwootReplayRequestKey{}).(*chatwootReplayRequest)
+ if request != nil && request.held && request.key == key {
+ // Verified a second time in the same request (another secret check).
+ return
+ }
+
+ var deadline <-chan time.Time
+ for {
+ state, settled := chatwootReplays.reserve(key, time.Now())
+ switch state {
+ case chatwootReplayNew:
+ owner := chatwootReplayOwner(sha256.Sum256([]byte(secret)))
+ if request == nil {
+ // No ChatwootWebhookReplayGuard in front of this handler, so
+ // nothing would settle a reservation: remember the signature
+ // now. A request that then fails is not handled when resent.
+ chatwootReplayUnguardedWarning.Do(func() {
+ logrus.Error("Chatwoot Webhook: ChatwootWebhookReplayGuard is not mounted in front of the webhook handler; " +
+ "a signed request that fails will not be handled when it is sent again")
+ })
+ chatwootReplays.commit(key, owner, time.Now(), config.ChatwootWebhookSignatureTolerance)
+ return
+ }
+ request.held, request.key, request.owner = true, key, owner
+ return
+ case chatwootReplayAccepted:
+ c.Locals(chatwootReplayOutcomeKey{}, chatwootReplayAccepted)
+ return
+ }
+
+ if deadline == nil {
+ timer := time.NewTimer(chatwootReplayInFlightWait)
+ defer timer.Stop()
+ deadline = timer.C
+ }
+ select {
+ case <-settled:
+ case <-deadline:
+ c.Locals(chatwootReplayOutcomeKey{}, chatwootReplayInFlight)
+ return
+ }
+ }
+}
diff --git a/src/ui/rest/chatwoot_webhook_replay_test.go b/src/ui/rest/chatwoot_webhook_replay_test.go
new file mode 100644
index 00000000..23252026
--- /dev/null
+++ b/src/ui/rest/chatwoot_webhook_replay_test.go
@@ -0,0 +1,445 @@
+package rest
+
+import (
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/middleware"
+ "github.com/gofiber/fiber/v3"
+)
+
+const replayTestSecret = "channel-secret"
+
+// newReplayGuardApp mounts the replay guard in front of a stand-in webhook
+// handler: it authorizes the request the way the real handlers do, then hands
+// over to handle, which decides the answer. The guard has to work from that
+// answer alone.
+func newReplayGuardApp(t *testing.T, handle fiber.Handler) *fiber.App {
+ t.Helper()
+ withChatwootWebhookSecret(t, replayTestSecret)
+ chatwootReplays.reset()
+ t.Cleanup(chatwootReplays.reset)
+
+ app := fiber.New()
+ app.Use(middleware.Recovery())
+ app.Use("/chatwoot/webhook", ChatwootWebhookReplayGuard())
+ app.Post("/chatwoot/webhook", func(c fiber.Ctx) error {
+ if status := (&ChatwootHandler{}).chatwootWebhookRouteGate(c, chatwootWebhookRoute{Unroutable: true}); status != 0 {
+ return c.SendStatus(status)
+ }
+ return handle(c)
+ })
+ return app
+}
+
+// replayTestBody makes every test's signed request distinct.
+var replayTestBody atomic.Int64
+
+func signedReplayRequest() webhookAuthRequest {
+ body := fmt.Sprintf(`{"event":"message_created","id":%d}`, replayTestBody.Add(1))
+ return webhookAuthRequest{body: body, headers: chatwootSigned(replayTestSecret, body)}
+}
+
+// postReplayRequest is postChatwootWebhook for requests that are held open on
+// purpose, usable from several goroutines.
+func postReplayRequest(app *fiber.App, r webhookAuthRequest) (int, error) {
+ req := httptest.NewRequest(http.MethodPost, "/chatwoot/webhook", strings.NewReader(r.body))
+ req.Header.Set("Content-Type", "application/json")
+ for name, value := range r.headers {
+ req.Header.Set(name, value)
+ }
+ resp, err := app.Test(req, fiber.TestConfig{Timeout: 30 * time.Second, FailOnTimeout: true})
+ if err != nil {
+ return 0, err
+ }
+ return resp.StatusCode, nil
+}
+
+// TestChatwootReplayGuardRemembersOnlyAcceptedRequests: whatever stands behind
+// the guard, a signed request that was not answered 2xx was not handled, so
+// the identical request sent again reaches the handler. Once it is answered
+// 2xx, a further copy is acknowledged without reaching the handler.
+func TestChatwootReplayGuardRemembersOnlyAcceptedRequests(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ fail func(c fiber.Ctx) error
+ wantStatus int
+ }{
+ {name: "answers 503", fail: func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusServiceUnavailable) }, wantStatus: 503},
+ {name: "answers 400", fail: func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusBadRequest) }, wantStatus: 400},
+ {name: "returns an HTTP error", fail: func(fiber.Ctx) error { return fiber.NewError(fiber.StatusServiceUnavailable, "queue unavailable") }, wantStatus: 503},
+ {name: "returns an error", fail: func(fiber.Ctx) error { return errors.New("database is locked") }, wantStatus: 500},
+ {name: "returns an error after writing 200", fail: func(c fiber.Ctx) error {
+ c.Status(fiber.StatusOK)
+ return errors.New("database is locked")
+ }, wantStatus: 500},
+ {name: "panics", fail: func(fiber.Ctx) error { panic("handler crashed") }, wantStatus: 500},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ handled := 0
+ app := newReplayGuardApp(t, func(c fiber.Ctx) error {
+ handled++
+ if handled == 1 {
+ return tt.fail(c)
+ }
+ return c.SendStatus(fiber.StatusOK)
+ })
+ request := signedReplayRequest()
+
+ if got := postChatwootWebhook(t, app, request); got != tt.wantStatus {
+ t.Fatalf("first delivery: status = %d, want %d", got, tt.wantStatus)
+ }
+ if got := postChatwootWebhook(t, app, request); got != fiber.StatusOK {
+ t.Fatalf("redelivery: status = %d, want 200", got)
+ }
+ if handled != 2 {
+ t.Fatalf("handler ran %d times, want 2: the redelivery of a failed request must be handled", handled)
+ }
+ if got := postChatwootWebhook(t, app, request); got != fiber.StatusOK {
+ t.Fatalf("repeat: status = %d, want 200", got)
+ }
+ if handled != 2 {
+ t.Fatalf("handler ran %d times, want 2: a copy of an accepted request must not be handled", handled)
+ }
+ })
+ }
+}
+
+// TestChatwootReplayGuardConcurrentDuplicates: identical signed requests
+// arriving while the first is still being handled are not handled alongside
+// it. They wait for its outcome and are acknowledged as repeats.
+func TestChatwootReplayGuardConcurrentDuplicates(t *testing.T) {
+ var handled atomic.Int32
+ entered := make(chan struct{}, 16)
+ finish := make(chan struct{})
+ app := newReplayGuardApp(t, func(c fiber.Ctx) error {
+ handled.Add(1)
+ entered <- struct{}{}
+ <-finish
+ return c.SendStatus(fiber.StatusOK)
+ })
+ request := signedReplayRequest()
+
+ const copies = 8
+ statuses := make(chan int, copies)
+ failures := make(chan error, copies)
+ var wg sync.WaitGroup
+ for i := 0; i < copies; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ status, err := postReplayRequest(app, request)
+ if err != nil {
+ failures <- err
+ return
+ }
+ statuses <- status
+ }()
+ }
+
+ <-entered
+ // Give the other copies time to reach the guard while the first is held;
+ // the assertions below hold whether or not they have.
+ time.Sleep(50 * time.Millisecond)
+ if got := handled.Load(); got != 1 {
+ t.Errorf("%d copies were being handled at once, want 1", got)
+ }
+ close(finish)
+ wg.Wait()
+ close(statuses)
+ close(failures)
+
+ for err := range failures {
+ t.Fatalf("request failed: %v", err)
+ }
+ for status := range statuses {
+ if status != fiber.StatusOK {
+ t.Errorf("status = %d, want 200", status)
+ }
+ }
+ if got := handled.Load(); got != 1 {
+ t.Fatalf("handler ran %d times for %d identical requests, want 1", got, copies)
+ }
+}
+
+// TestChatwootReplayGuardDuplicateTakesOverAfterFailure: a duplicate waiting
+// on a request that then fails is handled in its place.
+func TestChatwootReplayGuardDuplicateTakesOverAfterFailure(t *testing.T) {
+ var handled atomic.Int32
+ entered := make(chan struct{}, 2)
+ finish := make(chan struct{})
+ app := newReplayGuardApp(t, func(c fiber.Ctx) error {
+ if handled.Add(1) == 1 {
+ entered <- struct{}{}
+ <-finish
+ return c.SendStatus(fiber.StatusServiceUnavailable)
+ }
+ return c.SendStatus(fiber.StatusOK)
+ })
+ request := signedReplayRequest()
+
+ type result struct {
+ status int
+ err error
+ }
+ first, second := make(chan result, 1), make(chan result, 1)
+ go func() {
+ status, err := postReplayRequest(app, request)
+ first <- result{status, err}
+ }()
+ <-entered
+ go func() {
+ status, err := postReplayRequest(app, request)
+ second <- result{status, err}
+ }()
+ time.Sleep(50 * time.Millisecond)
+ if got := handled.Load(); got != 1 {
+ t.Errorf("%d copies were being handled at once, want 1", got)
+ }
+ close(finish)
+
+ if got := <-first; got.err != nil || got.status != fiber.StatusServiceUnavailable {
+ t.Fatalf("first: status = %d, err = %v, want 503", got.status, got.err)
+ }
+ if got := <-second; got.err != nil || got.status != fiber.StatusOK {
+ t.Fatalf("second: status = %d, err = %v, want 200", got.status, got.err)
+ }
+ if got := handled.Load(); got != 2 {
+ t.Fatalf("handler ran %d times, want 2: the duplicate must be handled after the first failed", got)
+ }
+}
+
+// TestChatwootReplayGuardDuplicateDoesNotWaitForever: a duplicate of a request
+// that stays in flight is refused, not handled and not acknowledged.
+func TestChatwootReplayGuardDuplicateDoesNotWaitForever(t *testing.T) {
+ previous := chatwootReplayInFlightWait
+ chatwootReplayInFlightWait = 20 * time.Millisecond
+ t.Cleanup(func() { chatwootReplayInFlightWait = previous })
+
+ var handled atomic.Int32
+ entered := make(chan struct{}, 2)
+ finish := make(chan struct{})
+ app := newReplayGuardApp(t, func(c fiber.Ctx) error {
+ handled.Add(1)
+ entered <- struct{}{}
+ <-finish
+ return c.SendStatus(fiber.StatusOK)
+ })
+ request := signedReplayRequest()
+
+ first := make(chan error, 1)
+ go func() {
+ status, err := postReplayRequest(app, request)
+ if err == nil && status != fiber.StatusOK {
+ err = fmt.Errorf("status = %d, want 200", status)
+ }
+ first <- err
+ }()
+ <-entered
+
+ status, err := postReplayRequest(app, request)
+ if err != nil || status != fiber.StatusServiceUnavailable {
+ t.Errorf("duplicate of an in-flight request: status = %d, err = %v, want 503", status, err)
+ }
+ if got := handled.Load(); got != 1 {
+ t.Errorf("handler ran %d times, want 1", got)
+ }
+ close(finish)
+ if err := <-first; err != nil {
+ t.Fatalf("first: %v", err)
+ }
+}
+
+func replayTestKey(t *testing.T, timestamp string, n int) chatwootReplayKey {
+ t.Helper()
+ key, ok := chatwootReplayKeyFor(timestamp, chatwootSign("secret", timestamp, fmt.Sprintf("body-%d", n)))
+ if !ok {
+ t.Fatalf("no key for body %d", n)
+ }
+ return key
+}
+
+// accept runs a pair through the guard as an accepted request would.
+func (g *chatwootReplayGuard) accept(t *testing.T, key chatwootReplayKey, owner chatwootReplayOwner, now time.Time, tolerance time.Duration) {
+ t.Helper()
+ if state, _ := g.reserve(key, now); state != chatwootReplayNew {
+ t.Fatalf("reserve = %v, want a new reservation", state)
+ }
+ g.commit(key, owner, now, tolerance)
+}
+
+func (g *chatwootReplayGuard) remembers(key chatwootReplayKey, now time.Time) bool {
+ state, _ := g.reserve(key, now)
+ if state == chatwootReplayNew {
+ g.release(key)
+ }
+ return state == chatwootReplayAccepted
+}
+
+func TestChatwootReplayGuard(t *testing.T) {
+ const tolerance = 5 * time.Minute
+ now := time.Unix(1700000000, 0)
+ ownerA := chatwootReplayOwner(sha256.Sum256([]byte("secret-a")))
+ ownerB := chatwootReplayOwner(sha256.Sum256([]byte("secret-b")))
+ key := func(n int) chatwootReplayKey { return replayTestKey(t, "1700000000", n) }
+
+ t.Run("a reservation is exclusive until it is settled", func(t *testing.T) {
+ g := &chatwootReplayGuard{max: 8}
+ if state, _ := g.reserve(key(1), now); state != chatwootReplayNew {
+ t.Fatalf("first reserve = %v, want new", state)
+ }
+ state, settled := g.reserve(key(1), now)
+ if state != chatwootReplayInFlight {
+ t.Fatalf("second reserve = %v, want in flight", state)
+ }
+ select {
+ case <-settled:
+ t.Fatal("reservation reported settled while held")
+ default:
+ }
+
+ g.release(key(1))
+ select {
+ case <-settled:
+ default:
+ t.Fatal("release did not wake the waiting request")
+ }
+ if g.size != 0 || len(g.inFlight) != 0 {
+ t.Fatalf("a released reservation left size=%d inFlight=%d, want nothing", g.size, len(g.inFlight))
+ }
+
+ // Released, so the pair can be reserved again, and committed this time.
+ if state, _ := g.reserve(key(1), now); state != chatwootReplayNew {
+ t.Fatalf("reserve after release = %v, want new", state)
+ }
+ _, settled = g.reserve(key(1), now)
+ g.commit(key(1), ownerA, now, tolerance)
+ select {
+ case <-settled:
+ default:
+ t.Fatal("commit did not wake the waiting request")
+ }
+ if state, _ := g.reserve(key(1), now); state != chatwootReplayAccepted {
+ t.Fatalf("reserve after commit = %v, want accepted", state)
+ }
+ if len(g.inFlight) != 0 {
+ t.Fatalf("%d reservations left behind", len(g.inFlight))
+ }
+ })
+
+ t.Run("remembers a pair until the timestamp check rejects it", func(t *testing.T) {
+ g := &chatwootReplayGuard{max: 8}
+ g.accept(t, key(1), ownerA, now, tolerance)
+ if !g.remembers(key(1), now.Add(tolerance)) {
+ t.Fatal("accepted pair not remembered inside the window")
+ }
+ if g.remembers(replayTestKey(t, "1700000001", 1), now) {
+ t.Fatal("same body with another timestamp reported as a repeat")
+ }
+ // A timestamp tolerance ahead of this clock is accepted until
+ // 2*tolerance from now; the entry must live that long.
+ if !g.remembers(key(1), now.Add(2*tolerance-time.Second)) {
+ t.Fatal("pair forgotten while its timestamp could still be accepted")
+ }
+ if g.remembers(key(1), now.Add(2*tolerance)) {
+ t.Fatal("expired pair reported as a repeat")
+ }
+ if g.size != 0 || len(g.accepted) != 0 || len(g.queues) != 0 {
+ t.Fatalf("expired pairs kept: size=%d accepted=%d queues=%d, want none", g.size, len(g.accepted), len(g.queues))
+ }
+ })
+
+ t.Run("is bounded and forgets a secret's oldest pairs first", func(t *testing.T) {
+ g := &chatwootReplayGuard{max: 3}
+ for n := 1; n <= 50; n++ {
+ g.accept(t, key(n), ownerA, now, tolerance)
+ if g.size > 3 || len(g.accepted) > 3 || len(g.queues[ownerA]) > 3 {
+ t.Fatalf("guard grew to size=%d accepted=%d queue=%d, want at most 3", g.size, len(g.accepted), len(g.queues[ownerA]))
+ }
+ }
+ if !g.remembers(key(50), now) || !g.remembers(key(48), now) {
+ t.Fatal("newest pairs were forgotten")
+ }
+ if g.remembers(key(47), now) {
+ t.Fatal("oldest pair survived past the bound")
+ }
+ })
+
+ t.Run("a flood under one secret does not evict another secret's recent pairs", func(t *testing.T) {
+ g := &chatwootReplayGuard{max: 8}
+ for n := 1; n <= 6; n++ {
+ g.accept(t, key(n), ownerA, now, tolerance)
+ }
+ for n := 100; n < 1100; n++ {
+ g.accept(t, key(n), ownerB, now, tolerance)
+ if g.size > 8 || len(g.accepted) > 8 {
+ t.Fatalf("guard grew to size=%d accepted=%d, want at most 8", g.size, len(g.accepted))
+ }
+ }
+ // Two secrets share eight slots: the flooded-out secret keeps its
+ // newest four, and the flood has been evicting its own pairs since.
+ for n := 3; n <= 6; n++ {
+ if !g.remembers(key(n), now) {
+ t.Fatalf("pair %d of the other secret was evicted by the flood", n)
+ }
+ }
+ if g.remembers(key(1), now) || g.remembers(key(2), now) {
+ t.Fatal("the other secret kept more than its share")
+ }
+ if got := len(g.queues[ownerA]); got != 4 {
+ t.Fatalf("the other secret keeps %d pairs, want 4", got)
+ }
+ })
+
+ t.Run("reservations are not evicted", func(t *testing.T) {
+ g := &chatwootReplayGuard{max: 2}
+ if state, _ := g.reserve(key(1), now); state != chatwootReplayNew {
+ t.Fatalf("reserve = %v, want new", state)
+ }
+ for n := 2; n <= 20; n++ {
+ g.accept(t, key(n), ownerA, now, tolerance)
+ }
+ if state, _ := g.reserve(key(1), now); state != chatwootReplayInFlight {
+ t.Fatalf("reserve of a held pair = %v, want in flight", state)
+ }
+ })
+
+ t.Run("ignores what cannot have verified", func(t *testing.T) {
+ for _, pair := range [][2]string{{"yesterday", chatwootSign("secret", "1700000000", "body")}, {"1700000000", "sha256=zz"}, {"1700000000", "sha256=00"}} {
+ if _, ok := chatwootReplayKeyFor(pair[0], pair[1]); ok {
+ t.Fatalf("malformed pair %v produced a key", pair)
+ }
+ }
+ spaced, ok := chatwootReplayKeyFor(" 1700000000 ", " "+chatwootSign("secret", "1700000000", "body-1")+" ")
+ if !ok || spaced != key(1) {
+ t.Fatal("surrounding whitespace changed the key")
+ }
+ })
+
+ t.Run("concurrent reservations yield exactly one holder", func(t *testing.T) {
+ g := &chatwootReplayGuard{max: 64}
+ var wg sync.WaitGroup
+ var holders atomic.Int32
+ for i := 0; i < 32; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if state, _ := g.reserve(key(1), now); state == chatwootReplayNew {
+ holders.Add(1)
+ }
+ }()
+ }
+ wg.Wait()
+ if got := holders.Load(); got != 1 {
+ t.Fatalf("%d goroutines hold the reservation, want exactly 1", got)
+ }
+ })
+}
diff --git a/src/ui/rest/chatwoot_webhook_route_auth_test.go b/src/ui/rest/chatwoot_webhook_route_auth_test.go
new file mode 100644
index 00000000..aef0b55e
--- /dev/null
+++ b/src/ui/rest/chatwoot_webhook_route_auth_test.go
@@ -0,0 +1,527 @@
+package rest
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/gofiber/fiber/v3"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// routeAuthRepo is a storage fake with several device configs, enough for the
+// client registry, route resolution, delivery, and the delete path.
+type routeAuthRepo struct {
+ domainChatStorage.IChatStorageRepository
+ mu sync.Mutex
+ configs []*domainChatStorage.ChatwootDeviceConfig
+ // links are returned by conversation (route resolution) and by Chatwoot
+ // message id (delete path).
+ links []*domainChatStorage.ChatwootMessageLink
+ stored []*domainChatStorage.ChatwootMessageLink
+ // lookupErr, when set, fails device config lookups by identifier.
+ lookupErr error
+}
+
+func (r *routeAuthRepo) failLookups(err error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.lookupErr = err
+}
+
+func (r *routeAuthRepo) GetChatwootDeviceConfigByIdentifier(identifier string) (*domainChatStorage.ChatwootDeviceConfig, error) {
+ r.mu.Lock()
+ err := r.lookupErr
+ r.mu.Unlock()
+ if err != nil {
+ return nil, err
+ }
+ for _, cfg := range r.configs {
+ if identifier != "" && (identifier == cfg.DeviceID || identifier == cfg.DeviceJID) {
+ return cfg, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *routeAuthRepo) GetChatwootDeviceConfigByInbox(accountID, inboxID int) (*domainChatStorage.ChatwootDeviceConfig, error) {
+ for _, cfg := range r.configs {
+ if cfg.AccountID == accountID && cfg.InboxID == inboxID {
+ return cfg, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *routeAuthRepo) ListChatwootDeviceConfigs() ([]*domainChatStorage.ChatwootDeviceConfig, error) {
+ return r.configs, nil
+}
+
+func (r *routeAuthRepo) CountChatwootDeviceConfigs() (int, error) {
+ return len(r.configs), nil
+}
+
+func (r *routeAuthRepo) GetLatestChatwootMessageLinkByConversation(conversationID, accountID int, _ bool, configID int64) (*domainChatStorage.ChatwootMessageLink, error) {
+ for _, link := range r.links {
+ if link.ChatwootConversationID == conversationID && link.ChatwootAccountID == accountID &&
+ (configID == 0 || link.ChatwootConfigID == configID) {
+ cloned := *link
+ return &cloned, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *routeAuthRepo) GetChatwootMessageLinkByChatwootID(deviceID string, chatwootMessageID int) (*domainChatStorage.ChatwootMessageLink, error) {
+ for _, link := range r.links {
+ if link.DeviceID == deviceID && link.ChatwootMessageID == chatwootMessageID {
+ cloned := *link
+ return &cloned, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *routeAuthRepo) UpsertChatwootMessageLink(link *domainChatStorage.ChatwootMessageLink) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.stored = append(r.stored, link)
+ return nil
+}
+
+// routeAuthSend records every text send and the device it would go out from.
+type routeAuthSend struct {
+ domainSend.ISendUsecase
+ mu sync.Mutex
+ sends []string // "<device alias> -> <phone>"
+}
+
+func (s *routeAuthSend) SendText(ctx context.Context, request domainSend.MessageRequest) (domainSend.GenericResponse, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ device := "<no device>"
+ if instance, ok := whatsapp.DeviceFromContext(ctx); ok && instance != nil {
+ device = instance.ID()
+ }
+ s.sends = append(s.sends, device+" -> "+request.Phone)
+ return domainSend.GenericResponse{MessageID: fmt.Sprintf("WA-%d", len(s.sends)), Status: "ok"}, nil
+}
+
+func (s *routeAuthSend) taken() []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ sends := s.sends
+ s.sends = nil
+ return sends
+}
+
+// routeAuthMessage records revokes.
+type routeAuthMessage struct {
+ domainMessage.IMessageUsecase
+ revoked []string
+}
+
+func (m *routeAuthMessage) RevokeMessage(ctx context.Context, request domainMessage.RevokeRequest) (domainMessage.GenericResponse, error) {
+ device := "<no device>"
+ if instance, ok := whatsapp.DeviceFromContext(ctx); ok && instance != nil {
+ device = instance.ID()
+ }
+ m.revoked = append(m.revoked, device+" revokes "+request.MessageID)
+ return domainMessage.GenericResponse{}, nil
+}
+
+const (
+ routeAuthSalesSecret = "sales-channel-secret"
+ routeAuthSupportSecret = "support-channel-secret"
+ routeAuthSalesJID = "[email protected]"
+ routeAuthSupportJID = "[email protected]"
+ routeAuthOpenJID = "[email protected]"
+)
+
+type routeAuthFixture struct {
+ app *fiber.App
+ repo *routeAuthRepo
+ send *routeAuthSend
+ message *routeAuthMessage
+}
+
+// newRouteAuthFixture wires both webhook endpoints to three paired devices on
+// account 1: "sales" (inbox 2) and "support" (inbox 3) each have their own
+// webhook secret, "open" (inbox 4) has none. The "sales" config has no stored
+// JID, as when it was saved before the device was paired.
+func newRouteAuthFixture(t *testing.T, globalSecret string) *routeAuthFixture {
+ t.Helper()
+ withChatwootWebhookSecret(t, globalSecret)
+ chatwootReplays.reset()
+ t.Cleanup(chatwootReplays.reset)
+
+ repo := &routeAuthRepo{configs: []*domainChatStorage.ChatwootDeviceConfig{
+ {ID: 1, DeviceID: "sales", ChatwootURL: "https://chat.example.com", AccountID: 1, InboxID: 2, APIToken: "t", Enabled: true, WebhookSecret: routeAuthSalesSecret},
+ {ID: 2, DeviceID: "support", DeviceJID: routeAuthSupportJID, ChatwootURL: "https://chat.example.com", AccountID: 1, InboxID: 3, APIToken: "t", Enabled: true, WebhookSecret: routeAuthSupportSecret},
+ {ID: 3, DeviceID: "open", DeviceJID: routeAuthOpenJID, ChatwootURL: "https://chat.example.com", AccountID: 1, InboxID: 4, APIToken: "t", Enabled: true},
+ }}
+ chatwoot.InitClientRegistry(repo)
+ t.Cleanup(func() { chatwoot.InitClientRegistry(nil) })
+
+ dm := whatsapp.NewDeviceManager(nil, nil, nil)
+ for alias, jid := range map[string]string{"sales": routeAuthSalesJID, "support": routeAuthSupportJID, "open": routeAuthOpenJID} {
+ parsed, err := types.ParseJID(jid)
+ if err != nil {
+ t.Fatalf("parse %s: %v", jid, err)
+ }
+ dm.AddDevice(whatsapp.NewDeviceInstance(alias, &whatsmeow.Client{Store: &store.Device{ID: &parsed}}, nil))
+ }
+
+ f := &routeAuthFixture{repo: repo, send: &routeAuthSend{}, message: &routeAuthMessage{}}
+ handler := &ChatwootHandler{SendUsecase: f.send, MessageUsecase: f.message, DeviceManager: dm, ChatStorageRepo: repo}
+ f.app = fiber.New()
+ f.app.Use("/chatwoot/webhook", ChatwootWebhookReplayGuard())
+ f.app.Post("/chatwoot/webhook", handler.HandleWebhook)
+ f.app.Post("/chatwoot/webhook/:device_id", handler.HandleDeviceWebhook)
+ return f
+}
+
+// routeAuthMessageID makes every reply body (and so every signature) distinct.
+var routeAuthMessageID = 1000
+
+func agentReplyBody(inboxID, conversationID int) string {
+ routeAuthMessageID++
+ return fmt.Sprintf(`{"event":"message_created","message_type":"outgoing","id":%d,"content":"hi","account":{"id":1},`+
+ `"conversation":{"id":%d,"inbox_id":%d,"meta":{"sender":{"phone_number":"+628999999999"}}}}`,
+ routeAuthMessageID, conversationID, inboxID)
+}
+
+func chatwootSigned(secret, body string) map[string]string {
+ if secret == "" {
+ return nil
+ }
+ timestamp := nowUnix(0)
+ return map[string]string{chatwootTimestampHeader: timestamp, chatwootSignatureHeader: chatwootSign(secret, timestamp, body)}
+}
+
+type routeAuthCase struct {
+ name string
+ path string
+ inbox int
+ conv int
+ signWith string
+ want int
+ wantSend string // "" = nothing may be sent
+}
+
+func runRouteAuthCases(t *testing.T, f *routeAuthFixture, cases []routeAuthCase) {
+ t.Helper()
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ body := agentReplyBody(tt.inbox, tt.conv)
+ got := postChatwootWebhook(t, f.app, webhookAuthRequest{path: tt.path, body: body, headers: chatwootSigned(tt.signWith, body)})
+ sends := f.send.taken()
+ if got != tt.want {
+ t.Errorf("status = %d, want %d", got, tt.want)
+ }
+ switch {
+ case tt.wantSend == "" && len(sends) != 0:
+ t.Errorf("sent %v, want nothing sent", sends)
+ case tt.wantSend != "" && (len(sends) != 1 || sends[0] != tt.wantSend):
+ t.Errorf("sent %v, want exactly [%s]", sends, tt.wantSend)
+ }
+ })
+ }
+}
+
+// TestChatwootDeviceWebhookSignedReplyIsDelivered drives a signed agent reply
+// through the per-device endpoint to the send usecase: the alias and JID path
+// forms resolve to the same device, a wrong signature sends nothing, and one
+// device's secret cannot deliver through another device.
+func TestChatwootDeviceWebhookSignedReplyIsDelivered(t *testing.T) {
+ for _, global := range []string{"", "global-secret"} {
+ t.Run("global="+global, func(t *testing.T) {
+ f := newRouteAuthFixture(t, global)
+ salesByJID := "/chatwoot/webhook/" + url.PathEscape(routeAuthSalesJID)
+ const toContact = " -> 628999999999"
+ cases := []routeAuthCase{
+ {name: "alias path, device secret", path: "/chatwoot/webhook/sales", inbox: 2, signWith: routeAuthSalesSecret, want: 200, wantSend: "sales" + toContact},
+ {name: "JID path, device secret", path: salesByJID, inbox: 2, signWith: routeAuthSalesSecret, want: 200, wantSend: "sales" + toContact},
+ {name: "alias path, unsigned", path: "/chatwoot/webhook/sales", inbox: 2, want: 401},
+ {name: "alias path, wrong secret", path: "/chatwoot/webhook/sales", inbox: 2, signWith: "guess", want: 401},
+ {name: "JID path, wrong secret", path: salesByJID, inbox: 2, signWith: "guess", want: 401},
+ {name: "sales secret on the support endpoint", path: "/chatwoot/webhook/support", inbox: 3, signWith: routeAuthSalesSecret, want: 401},
+ {name: "sales secret on the sales endpoint, support's inbox", path: "/chatwoot/webhook/sales", inbox: 3, signWith: routeAuthSalesSecret, want: 401},
+ {name: "support secret delivers through support", path: "/chatwoot/webhook/support", inbox: 3, signWith: routeAuthSupportSecret, want: 200, wantSend: "support" + toContact},
+ }
+ if global != "" {
+ cases = append(cases,
+ routeAuthCase{name: "global secret does not open a device that has its own", path: "/chatwoot/webhook/sales", inbox: 2, signWith: global, want: 401},
+ routeAuthCase{name: "device without its own secret uses the global one", path: "/chatwoot/webhook/open", inbox: 4, signWith: global, want: 200, wantSend: "open" + toContact},
+ routeAuthCase{name: "device without its own secret refuses a device secret", path: "/chatwoot/webhook/open", inbox: 4, signWith: routeAuthSalesSecret, want: 401},
+ )
+ }
+ runRouteAuthCases(t, f, cases)
+ })
+ }
+}
+
+// TestChatwootSharedWebhookEnforcesRoutedDeviceSecret: the shared endpoint
+// routes by payload, so the secret that protects a delivery is the secret of
+// the device it is routed to. Before this was enforced, an unsigned reply for
+// a protected device's inbox was sent when CHATWOOT_WEBHOOK_SECRET was empty,
+// and the global secret opened every device.
+func TestChatwootSharedWebhookEnforcesRoutedDeviceSecret(t *testing.T) {
+ const toContact = " -> 628999999999"
+
+ t.Run("no global secret", func(t *testing.T) {
+ f := newRouteAuthFixture(t, "")
+ runRouteAuthCases(t, f, []routeAuthCase{
+ {name: "unsigned reply for a protected device", inbox: 2, want: 401},
+ {name: "wrong secret for a protected device", inbox: 2, signWith: "guess", want: 401},
+ {name: "another device's secret", inbox: 3, signWith: routeAuthSalesSecret, want: 401},
+ {name: "the routed device's secret", inbox: 2, signWith: routeAuthSalesSecret, want: 200, wantSend: "sales" + toContact},
+ // Same answer as a wrong secret, so the status does not reveal
+ // which inboxes are mapped to a protected device.
+ {name: "unsigned reply for an unknown inbox", inbox: 99, want: 401},
+ // A device with no secret at all is unauthenticated by configuration.
+ {name: "unsigned reply for a device without any secret", inbox: 4, want: 200, wantSend: "open" + toContact},
+ })
+ })
+
+ t.Run("with a global secret", func(t *testing.T) {
+ const global = "global-secret"
+ f := newRouteAuthFixture(t, global)
+ // Conversation 7 is linked to the support device (by storage JID), so
+ // it routes there whatever inbox the payload names.
+ f.repo.links = []*domainChatStorage.ChatwootMessageLink{{
+ DeviceID: routeAuthSupportJID, WhatsAppChatJID: "[email protected]",
+ ChatwootConversationID: 7, ChatwootAccountID: 1, ChatwootConfigID: 2,
+ }}
+ runRouteAuthCases(t, f, []routeAuthCase{
+ {name: "global secret for a protected device", inbox: 2, signWith: global, want: 401},
+ {name: "unsigned", inbox: 2, want: 401},
+ {name: "another device's secret", inbox: 3, signWith: routeAuthSalesSecret, want: 401},
+ {name: "the routed device's secret", inbox: 2, signWith: routeAuthSalesSecret, want: 200, wantSend: "sales" + toContact},
+ {name: "global secret for a device without its own", inbox: 4, signWith: global, want: 200, wantSend: "open" + toContact},
+ {name: "device secret for a device without its own", inbox: 4, signWith: routeAuthSalesSecret, want: 401},
+ {name: "global secret, unknown inbox: acknowledged, nothing sent", inbox: 99, signWith: global, want: 200},
+ {name: "unsigned, unknown inbox", inbox: 99, want: 401},
+ {name: "device secret, unknown inbox", inbox: 99, signWith: routeAuthSalesSecret, want: 401},
+ {name: "linked conversation, global secret", inbox: 4, conv: 7, signWith: global, want: 401},
+ {name: "linked conversation, another device's secret", inbox: 2, conv: 7, signWith: routeAuthSalesSecret, want: 401},
+ {name: "linked conversation, the linked device's secret", inbox: 3, conv: 7, signWith: routeAuthSupportSecret, want: 200, wantSend: "support" + toContact},
+ })
+ })
+
+ // The sales config has no stored JID. A route that names the device by
+ // its storage JID (as conversation links do) must still find its secret.
+ t.Run("route by JID finds a config stored under the alias", func(t *testing.T) {
+ f := newRouteAuthFixture(t, "")
+ f.repo.links = []*domainChatStorage.ChatwootMessageLink{{
+ DeviceID: routeAuthSalesJID, WhatsAppChatJID: "[email protected]",
+ ChatwootConversationID: 8, ChatwootAccountID: 1, ChatwootConfigID: 1,
+ }}
+ runRouteAuthCases(t, f, []routeAuthCase{
+ {name: "unsigned", inbox: 2, conv: 8, want: 401},
+ {name: "device secret", inbox: 2, conv: 8, signWith: routeAuthSalesSecret, want: 200, wantSend: "sales" + toContact},
+ })
+ })
+
+ // Events nothing is done for are acknowledged as before.
+ t.Run("ignored events without a global secret stay acknowledged", func(t *testing.T) {
+ f := newRouteAuthFixture(t, "")
+ for _, body := range []string{
+ `{"event":"conversation_updated","account":{"id":1}}`,
+ `{"event":"message_created","message_type":"incoming","id":1,"account":{"id":1},"conversation":{"id":5,"inbox_id":2}}`,
+ } {
+ if got := postChatwootWebhook(t, f.app, webhookAuthRequest{body: body}); got != fiber.StatusOK {
+ t.Errorf("status = %d for %s, want 200", got, body)
+ }
+ }
+ if sends := f.send.taken(); len(sends) != 0 {
+ t.Errorf("sent %v, want nothing sent", sends)
+ }
+ })
+}
+
+// TestChatwootSharedWebhookDeleteEnforcesRoutedDeviceSecret: deleting a
+// message in Chatwoot revokes it on WhatsApp, so it passes the same gate.
+func TestChatwootSharedWebhookDeleteEnforcesRoutedDeviceSecret(t *testing.T) {
+ prev := config.ChatwootMessageDelete
+ config.ChatwootMessageDelete = true
+ t.Cleanup(func() { config.ChatwootMessageDelete = prev })
+
+ for _, global := range []string{"", "global-secret"} {
+ t.Run("global="+global, func(t *testing.T) {
+ f := newRouteAuthFixture(t, global)
+ f.repo.links = []*domainChatStorage.ChatwootMessageLink{{
+ DeviceID: routeAuthSalesJID, WhatsAppMessageID: "WA-OUT-1", WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 55, Direction: "outgoing",
+ }}
+ body := `{"event":"message_updated","message_type":"outgoing","id":55,"content_attributes":{"deleted":true},` +
+ `"account":{"id":1},"conversation":{"id":5,"inbox_id":2}}`
+
+ for _, tt := range []struct {
+ name, path, signWith string
+ want int
+ wantRevoke bool
+ }{
+ {name: "shared, unsigned", want: 401},
+ {name: "shared, global secret", signWith: global, want: 401},
+ {name: "shared, another device's secret", signWith: routeAuthSupportSecret, want: 401},
+ {name: "device endpoint, another device's secret", path: "/chatwoot/webhook/sales", signWith: routeAuthSupportSecret, want: 401},
+ {name: "shared, the routed device's secret", signWith: routeAuthSalesSecret, want: 200, wantRevoke: true},
+ {name: "device endpoint, device secret", path: "/chatwoot/webhook/sales", signWith: routeAuthSalesSecret, want: 200, wantRevoke: true},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ chatwootReplays.reset()
+ f.message.revoked = nil
+ got := postChatwootWebhook(t, f.app, webhookAuthRequest{path: tt.path, body: body, headers: chatwootSigned(tt.signWith, body)})
+ if got != tt.want {
+ t.Errorf("status = %d, want %d", got, tt.want)
+ }
+ if revoked := len(f.message.revoked) == 1 && f.message.revoked[0] == "sales revokes WA-OUT-1"; revoked != tt.wantRevoke {
+ t.Errorf("revoked = %v, want revoke=%v", f.message.revoked, tt.wantRevoke)
+ }
+ })
+ }
+ })
+ }
+}
+
+// TestChatwootSignedWebhookReplayIsNotDeliveredTwice pins what a captured
+// request can do. A Chatwoot-signed request is delivered once: a second copy
+// inside the tolerance window is acknowledged and not acted on. The guard is
+// in-process memory, so a restart inside the window forgets it, and the older
+// schemes (static secret header, ?secret=, X-Hub-Signature-256) carry no
+// timestamp and are not covered at all.
+func TestChatwootSignedWebhookReplayIsNotDeliveredTwice(t *testing.T) {
+ f := newRouteAuthFixture(t, "")
+
+ for _, path := range []string{"/chatwoot/webhook/sales", "/chatwoot/webhook"} {
+ body := agentReplyBody(2, 5)
+ captured := webhookAuthRequest{path: path, body: body, headers: chatwootSigned(routeAuthSalesSecret, body)}
+ for attempt := 1; attempt <= 3; attempt++ {
+ if got := postChatwootWebhook(t, f.app, captured); got != fiber.StatusOK {
+ t.Fatalf("%s attempt %d: status = %d, want 200", path, attempt, got)
+ }
+ }
+ if sends := f.send.taken(); len(sends) != 1 {
+ t.Fatalf("%s: three copies of one signed request sent %v, want one send", path, sends)
+ }
+
+ // A new delivery of the same message (Chatwoot signs with a new
+ // timestamp) is a different request and is not held back here.
+ later := nowUnix(time.Second)
+ redelivery := webhookAuthRequest{path: path, body: body, headers: map[string]string{
+ chatwootTimestampHeader: later, chatwootSignatureHeader: chatwootSign(routeAuthSalesSecret, later, body),
+ }}
+ if got := postChatwootWebhook(t, f.app, redelivery); got != fiber.StatusOK {
+ t.Fatalf("%s redelivery: status = %d, want 200", path, got)
+ }
+ if sends := f.send.taken(); len(sends) != 1 {
+ t.Fatalf("%s: a redelivery with a new timestamp sent %v, want one send", path, sends)
+ }
+
+ // Not covered: a restart inside the window forgets what was seen.
+ chatwootReplays.reset()
+ if got := postChatwootWebhook(t, f.app, captured); got != fiber.StatusOK {
+ t.Fatalf("%s after restart: status = %d, want 200", path, got)
+ }
+ if sends := f.send.taken(); len(sends) != 1 {
+ t.Fatalf("%s: the captured request after a restart sent %v, want one send (the guard is in memory only)", path, sends)
+ }
+ }
+
+ // Not covered: the static-secret schemes have nothing that identifies one
+ // delivery, so a captured request is delivered every time it is sent.
+ body := agentReplyBody(2, 5)
+ static := webhookAuthRequest{path: "/chatwoot/webhook/sales", body: body, headers: map[string]string{"X-Chatwoot-Webhook-Secret": routeAuthSalesSecret}}
+ for attempt := 1; attempt <= 2; attempt++ {
+ if got := postChatwootWebhook(t, f.app, static); got != fiber.StatusOK {
+ t.Fatalf("static secret attempt %d: status = %d, want 200", attempt, got)
+ }
+ }
+ if sends := f.send.taken(); len(sends) != 2 {
+ t.Fatalf("two copies of a static-secret request sent %v, want two sends", sends)
+ }
+}
+
+// routeAuthFailingRepo cannot read device configs.
+type routeAuthFailingRepo struct {
+ *routeAuthRepo
+}
+
+func (routeAuthFailingRepo) GetChatwootDeviceConfigByIdentifier(string) (*domainChatStorage.ChatwootDeviceConfig, error) {
+ return nil, fmt.Errorf("database is locked")
+}
+
+// TestChatwootSharedWebhookFailsClosedOnStorageError: when the routed device's
+// config cannot be read it is unknown whether it has its own secret, so
+// nothing is sent even with no global secret configured.
+func TestChatwootSharedWebhookFailsClosedOnStorageError(t *testing.T) {
+ f := newRouteAuthFixture(t, "")
+ // A linked conversation routes without the registry, which would itself
+ // need the failing lookup.
+ f.repo.links = []*domainChatStorage.ChatwootMessageLink{{
+ DeviceID: routeAuthSalesJID, WhatsAppChatJID: "[email protected]",
+ ChatwootConversationID: 9, ChatwootAccountID: 1, ChatwootConfigID: 1,
+ }}
+ handler := &ChatwootHandler{SendUsecase: f.send, DeviceManager: whatsapp.NewDeviceManager(nil, nil, nil), ChatStorageRepo: routeAuthFailingRepo{f.repo}}
+ app := fiber.New()
+ app.Post("/chatwoot/webhook", handler.HandleWebhook)
+
+ if got := postChatwootWebhook(t, app, webhookAuthRequest{body: agentReplyBody(2, 9)}); got != fiber.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want 503", got)
+ }
+ if sends := f.send.taken(); len(sends) != 0 {
+ t.Fatalf("sent %v, want nothing sent", sends)
+ }
+}
+
+// TestChatwootSignedWebhookRedeliveryAfterFailureIsProcessed: a signed request
+// answered 503 (here the routed device's config could not be read) was not
+// handled, so the identical request sent again must be processed, not
+// acknowledged as a repeat. Once it has been accepted, a further copy is one.
+func TestChatwootSignedWebhookRedeliveryAfterFailureIsProcessed(t *testing.T) {
+ const global = "global-secret"
+ f := newRouteAuthFixture(t, global)
+ // A linked conversation routes without the registry, which would itself
+ // need the failing lookup.
+ f.repo.links = []*domainChatStorage.ChatwootMessageLink{{
+ DeviceID: routeAuthOpenJID, WhatsAppChatJID: "[email protected]",
+ ChatwootConversationID: 9, ChatwootAccountID: 1, ChatwootConfigID: 3,
+ }}
+ body := agentReplyBody(4, 9)
+ request := webhookAuthRequest{body: body, headers: chatwootSigned(global, body)}
+
+ f.repo.failLookups(fmt.Errorf("database is locked"))
+ if got := postChatwootWebhook(t, f.app, request); got != fiber.StatusServiceUnavailable {
+ t.Fatalf("while storage fails: status = %d, want 503", got)
+ }
+ if sends := f.send.taken(); len(sends) != 0 {
+ t.Fatalf("while storage fails: sent %v, want nothing sent", sends)
+ }
+
+ f.repo.failLookups(nil)
+ if got := postChatwootWebhook(t, f.app, request); got != fiber.StatusOK {
+ t.Fatalf("redelivery: status = %d, want 200", got)
+ }
+ if sends := f.send.taken(); len(sends) != 1 {
+ t.Fatalf("redelivery of a request answered 503 sent %v, want one send", sends)
+ }
+
+ if got := postChatwootWebhook(t, f.app, request); got != fiber.StatusOK {
+ t.Fatalf("repeat: status = %d, want 200", got)
+ }
+ if sends := f.send.taken(); len(sends) != 0 {
+ t.Fatalf("a copy of an accepted request sent %v, want nothing sent", sends)
+ }
+}