Verify Webhook Signatures and Prevent Duplicate Event Processing

A webhook endpoint is often a public HTTP handler that performs a business action when a provider sends an event. If the handler trusts JSON fields without proving who sent them, anyone may be able to trigger a refund, provision an account, or alter a record. If it verifies a signature but ignores retries and replays, the same valid event can still cause the action more than once. Secure webhook handling requires authenticity, freshness, idempotency, bounded processing, and safe secret rotation.

Implement the verification format documented by the provider. Providers differ in whether they sign the raw body, a timestamp plus body, or an event identifier plus timestamp and body. Do not invent a compatible-looking HMAC format or normalize the request body before verification. Re-serializing JSON changes whitespace and order and can invalidate a signature or create ambiguity between what was signed and what the application processes.

Verify raw bytes before business logic

Figure: Verify Webhook Signatures and Prevent Duplicate Event Processing
Figure: Verify Webhook Signatures and Prevent Duplicate Event Processing

Read the raw request bytes within a strict size limit, obtain the signature header, and use the provider's maintained verification library where available. The signature should be checked before parsing untrusted fields into business operations. For HMAC-based schemes, compare the expected and supplied MAC using a constant-time comparison provided by the cryptographic library. Do not use ordinary string equality for a secret-derived value.

Require HTTPS for delivery endpoints. TLS protects the payload in transit, while the message signature authenticates the sender and message integrity according to the provider's signing design. These controls are complementary. Use a unique secret per webhook subscription where supported; sharing one secret across customers or environments makes rotation and incident scoping harder.

Return a generic authentication error when verification fails. Do not echo signature contents or explain which byte differed. Keep diagnostic details in access-controlled logs using a request ID, event identifier when trustworthy, and failure category. Never log the full raw body if it can contain credentials or personal information.

Authenticate freshness and deduplicate events

A signature proves the message was signed, but a captured valid message can be replayed. If the provider signs a timestamp, validate it against a narrow freshness window and ensure clocks are synchronized. The timestamp must be part of the authenticated material. A timestamp header that is not signed can be changed by an intermediary and should not be treated as replay protection.

Persist processed event IDs to make downstream work idempotent. The event ID should be authenticated by the provider's signature or otherwise obtained from a trusted protocol field. Use a database uniqueness constraint or idempotency key so two concurrent deliveries cannot process the same event twice. Keep a durable record across the provider's retry period. A short in-memory cache can reduce immediate duplicates but is not sufficient across restarts, regions, or long retry windows.

Retries are normal. The publisher may resend after a timeout even if your application completed its work, because it did not receive the acknowledgement. Design the handler so a repeated event returns success after confirming that the first delivery was durably queued or completed. Do not repeat a payment, email, or account mutation just because the HTTP request is a retry.

Acknowledge only after durable acceptance

Webhook handlers should keep network timeouts predictable. Verify the signature and schema, then durably enqueue the event or commit the required processing record before returning success. Acknowledge after durable acceptance, not before, or a process crash can lose the event. Conversely, keep heavy work out of a long synchronous handler when it can be processed asynchronously with retries and monitoring.

Apply request body limits, rate limits, schema validation, and allowed HTTP methods. Do not trust fields such as customer_id to select a tenant without looking up the authenticated provider event and verifying its relationship. Treat webhook payloads as untrusted input even after the signature passes: a legitimate provider can send malformed or unexpected data because of configuration drift or bugs.

Rotate signing secrets safely

Store signing secrets in a managed secret store and restrict access to the delivery service. During planned rotation, follow the provider's overlap process, verify using the current and retiring secrets only for the documented window, then remove the old secret. Monitor failed signatures during the transition. If a secret is compromised, revoke it immediately and investigate the time range in which forged deliveries could have occurred.

Do not include secrets in deployment logs, dashboard screenshots, issue descriptions, or source files. Separate test and production endpoints and secrets. Ensure a developer's test event cannot trigger a real production action.

Test the delivery path

In a provider sandbox or controlled test environment, verify missing and invalid signatures fail, body modification breaks verification, stale signed timestamps are rejected, and repeated event IDs do not repeat side effects. Test concurrent duplicates, provider retries after an application timeout, invalid JSON, oversized payloads, unknown event types, and secret rotation. Confirm the handler's acknowledgement behavior after queue failure and database unavailability.

The publisher side has a separate SSRF risk if customers can configure webhook destination URLs. Validate the target at registration and connection time, restrict schemes and ports, block private and metadata address ranges, pin validated DNS results, and revalidate redirects. Signing an outgoing request does not make its destination safe.

Review checklist

  1. Verify the provider's exact signing scheme over raw bytes with its library.
  2. Compare MACs in constant time and keep secrets out of logs.
  3. Validate authenticated timestamps and persist event IDs for deduplication.
  4. Make downstream side effects idempotent under concurrent retries.
  5. Acknowledge only after durable queueing or processing.
  6. Bound payloads, schema, methods, processing time, and request rates.
  7. Use separate secrets and endpoints for test and production, with a rotation path.
  8. Apply SSRF protections to any feature that sends webhooks to user-configured URLs.

OWASP's Webhook Security Cheat Sheet describes signature, replay, idempotency, payload, and SSRF controls. RFC 2104 defines HMAC. Standard Webhooks documents a signature format designed around event identifiers, timestamps, and message bodies; follow the provider format rather than assuming all webhooks use the same headers.

References


Editorial status: Owner authorized publication without an individual reviewer. Use test endpoints and synthetic events for verification.