External service webhooks: signatures, retries and time tolerance

Verify exact webhook bytes, distinguish duplicates from event conflicts, and commit the receipt and effect together in MySQL/InnoDB.

A seal and an inspected letter suggest checking an incoming message's origin and integrity.

An external service reported an event, the receiver saved the result, and the response was lost. The service sends the request again. The signature is valid both times; running the operation again may be a mistake. Another situation looks similar: an unrelated client replays a saved request. We need to check the delivery's origin and integrity, its time, and the work already completed, treating each question separately.

Consider an original teaching protocol for a notes service. An event adds a row and increments a local counter. A second increment is visible, so the example does not hide duplication behind an operation that changes nothing when repeated. Both changes are stored in one MySQL 8.4 database in InnoDB tables through native PDO MySQL. The database connection uses the network, but the exercise does not call external services to perform the effect.

Establish the provider's protocol first

The word “secret” in documentation does not define a verification method. APIs have different agreements about headers, signed bytes and retries.

Service What the receiver verifies What must not be assumed
GitHub An HMAC-SHA256 of the body with a shared secret, in X-Hub-Signature-256 A timestamp included in that signature
Stripe A signature covering a timestamp and the unchanged body The same signature for every retry
Telegram Bot API The value of X-Telegram-Bot-Api-Secret-Token, configured through secret_token A body HMAC or a signed timestamp

These differences are documented by GitHub, Stripe and Telegram setWebhook. Telegram's secret header does not become a JSON signature because we compare it safely. Once disclosed, the secret can be attached to another body too.

For a real integration, use verification from the official SDK when it is available and matches the chosen contract. The envelope below was created to explain the mechanics. It cannot be connected to Telegram or substituted for Stripe verification.

The signature covers exact bytes

Our headers are called X-Note-Time and X-Note-Signature. The server route selects the alpha or beta scope and its secret. The body cannot select a key or change that context. The HMAC message is assembled as follows:

v1 + LF + scope + LF + timestamp + LF + raw_body

LF is a single line-feed byte. Scope and time have narrow formats that exclude that character; the remaining bytes belong to the body. The version label fixes this particular scheme. Scope is included in the signature to prevent moving a request between routes even if a key is accidentally reused.

The verifier receives the body before json_decode. An added space, different Unicode escaping or a line break changes the HMAC message. Parsing JSON and serializing it again does not recover the original bytes. Stripe explicitly requires an unchanged body for signature verification.

The comparison at the heart of the PHP code is short:

$message = "v1\n" . $scope . "\n" . $timestamp . "\n" . $rawBody;
$expected = hash_hmac('sha256', $message, $secret);
$valid = hash_equals($expected, $receivedHex);

Before this, the code checks the exact header format: v1= followed by 64 lowercase hexadecimal characters. The prefix is removed before comparison. hash_hmac returns hex, while hash_equals is designed to compare without revealing the known string's contents through execution time; the client-supplied value is the second argument. This does not make the entire HTTP handler run in constant time.

HMAC protects message integrity and checks knowledge of a shared secret. It does not encrypt the body or replace HTTPS, key storage or domain permissions for an action.

Apply bounds before expensive operations

The example accepts a nonempty body of up to 65,536 bytes. This is an exercise policy, not a limit imposed by the APIs mentioned above. Checking strlen before HMAC and JSON bounds subsequent work, but the body may already occupy memory. A real HTTP entry point therefore also needs an upload limit at the server or while reading the stream.

The adapter must pass every value of the critical headers. Our agreement permits exactly one timestamp and one signature. Silently selecting the last of two headers is unacceptable. This policy must not be transferred to another protocol: key rotation, for example, may permit several signatures.

The HTTP adapter also defines HTTPS POST, an acceptable Content-Type and compression handling. The verifier must receive precisely the bytes specified by the sender's agreement. Proxies, middleware and logging must not transform them unnoticed.

Time has both syntax and an allowed interval

Our timestamp is an ASCII integer: 0, or up to ten digits without a leading zero. +1000, 01000, 1e3, whitespace and oversized numbers are rejected before casting. Checking only is_numeric would admit a broader language of values than agreed.

The timestamp enters the HMAC in its original textual form. After verifying the signature, the receiver compares it with a trusted clock, allowing an age of up to 300 seconds and a lead of up to 30 seconds, both inclusive. With a synthetic now = 1000, 700 and 1030 are accepted; 699 and 1031 are rejected.

A future tolerance prevents small clock differences from breaking the integration. A one-sided “not too old” check would leave the future unbounded. Arbitrarily widening the window does not fix an unsynchronized server: the clock and rejection reasons need monitoring.

These numbers belong to the exercise. Stripe includes time in its replay protection and gives a retried delivery a new timestamp and signature, as described in its replay prevention documentation. A receiver must agree its allowed age with the particular provider.

Authenticate before recording duplicates

The order is: body size and header syntax, HMAC, time window, JSON schema, then event persistence. Before authentication, the receiver neither looks up the event ID in the ledger nor claims it. Otherwise, an unverified request could occupy a genuine event's identity first.

Even a known duplicate goes through signature and time verification again. Knowing an ID does not grant the right to obtain an acknowledgement on the provider's behalf. An old saved delivery does not become acceptable simply because a corresponding row exists.

The signed JSON admits id, kind and note with defined types and bounds. Signed malformed JSON receives a format rejection; unsigned malformed JSON never reaches the parser. An authentic sender can still make a schema mistake, so HMAC does not remove the need for data validation.

A duplicate differs from an identity conflict

The accounting key is (scope, event_id). alpha / evt-a and beta / evt-a are different events. Delivery time and the signature are excluded from that key: a new attempt may have a different timestamp while remaining the same event.

The receipt stores a SHA-256 of the exact body. For a known key, the same hash means a duplicate; a different hash means an identity conflict. The second body neither overwrites the original record nor performs another action. This is a conflict between two messages using one ID, not a claim of a cryptographic SHA-256 collision.

The policy requires stable bytes across retries. Even reformatting equivalent JSON produces a conflict. If the provider changes the envelope on each attempt, the immutable event needs another explicitly defined identity. Inventing a JSON “canonicalization” scheme can conceal a meaningful difference.

The time window does not replace the ledger: one request can be sent many times within the allowed seconds. Nor should the ledger be cleared using that window alone. A late authentic retry may carry a new signature; receipt retention must cover the agreed retry and manual recovery horizon.

Commit the receipt and local effect together

The receipt, note and increment are written in one native MySQL/InnoDB transaction. The schema enforces uniqueness of (scope, event_id); textual identities use VARCHAR with the utf8mb4_0900_bin collation, while note text uses LONGTEXT. Foreign keys and CHECK constraints enforce relationships and data constraints. This is not a single-writer model: InnoDB uses row locks, and lock wait or deadlock errors must not be treated as successful duplicate handling. The code owning the transaction rolls it back on failure and does not hide the storage error; the different effects of errors are described in the InnoDB documentation.

Before serving HTTP requests, prepare the schema with a separate migrator and configure the application with a DML-only account. The handler does not execute CREATE, ALTER or DROP. DDL runs before the business transaction: MySQL can perform an implicit commit, so this is neither an atomic schema upgrade nor an automatic data transfer from the old SQLite database.

For an already completed event, the receiver returns 200 without another increment. A signed conflict receives 409. A known local failure before commit rolls back both the receipt and the effect; a 503 response leaves room for a retry. Recording “done” before completing the work would wrongly block recovery.

If the process stops after commit but before the HTTP response, the next authentic delivery finds the receipt. The local action already exists, so the retry receives an acknowledgement. A storage error with an undetermined outcome must not automatically be described as a known rollback or a success.

This guarantee applies within one local transaction. Sending an email or calling a payment API cannot be undone by that rollback. For lengthy work, the receiver can persist an inbox first, respond after commit, and delegate execution to a worker. External effects need separate idempotency or reconciliation. RFC 9110 on retries likewise ties retrying a non-idempotent request to additional knowledge of its semantics or non-execution.

What the teaching checks must establish

Scenario Expected model behavior
Valid signature and allowed time One receipt, note and increment
Changed bytes with the old signature Rejection before JSON and the ledger
Old or excessively future-dated signed delivery Rejection without new work
Fresh signature for the same event Acknowledgement without another effect
The same ID in two scopes Two independent events
The same key with a different signed body Conflict without an overwrite
Known failure before commit Rollback and an opportunity to retry
Process exit after commit but before response A persisted receipt after restart

The example fixes literal bodies, timestamps and expected HMAC values computed independently of the PHP code. An earlier separate Python calculation checked 19 HMACs and one published GitHub known-answer vector; it was not rerun this time. That is an independent bytes check, not proof of the PHP implementation.

The Symfony Demo checks use actual MySQL 8.4 in a guarded disposable test schema prepared by the migrator through App\Infrastructure\MysqlLab. Separate native PDO connections access the same schema; assertions and the handler execute DML only. The verified invariants are one receipt, note and increment after accepting an event, no partial result after a known pre-commit failure, and a persisted result after process exit between commit and the response. A fresh authentic retry after that exit is recognized as a duplicate without another increment.

Tests using a real Symfony Kernel check Request::getContent, HeaderBag lists, trusted context from fixed routes, a fixed clock and signature verification before parsing and SQL. They also check a duplicate with the same signed bytes, a 409 response for a reserialized body, and the absence of these test routes in the dev environment. These are educational local checks: the Kernel tests run in-process, without real HTTPS, a test of duplicate-header preservation by a proxy, or an upstream or pre-buffer body limit. The current Symfony Request buffers the body.

A real deployment still needs checks of proxies, raw-body preservation and the acknowledgement boundary. A correct HMAC formula is only one step. A working contract must also explain which event was accepted, which effect has already been committed, and when the next delivery can safely continue the work.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/SignedNoteLab
  1. Symfony Core One business operation, one transaction: saving a note with its tags
  2. Distribution One webhook for several bots: choosing the right context
  3. Databases Handler idempotency: repeat the task without duplicating its result