DEV Community

Cover image for The webhook nobody signs
Oyinlola Lawal
Oyinlola Lawal

Posted on Edited on Originally published at lawaloyinlola.com

The webhook nobody signs

Comparing trust models for login-free API doors

Here is a request that a lot of production apps will answer with a cheerful 200:

curl -s -X POST https://your-api.example/webhooks/payments \
  -H "Content-Type: application/json" \
  -d '{"event":"payment.succeeded","amount":5000,"customer":"cus_123"}'
Enter fullscreen mode Exit fullscreen mode

Nobody at the payment provider sent that. You did, from a laptop, with no key of any kind. If your endpoint processes it, anyone who can guess the URL can tell your app that a payment succeeded, a vehicle moved, a message was delivered or a user confirmed their email. The endpoint exists so a vendor can reach your system without logging in, which makes it a login-free door by design, and the only thing standing in that door is whatever check you wrote.

I maintain an app with two such doors, and they use two different checks. The differences between them are most of what there is to know.

The first one: a shared secret

The app's GPS server posts position updates to it. The sender is one machine I control, so the simplest thing that works is a shared secret in a header, compared on arrival. A first version of that check is five lines, and the interesting part is everything around the comparison.

The comparison itself is constant-time, with a length check ahead of it because the function throws on buffers of different sizes:

const secretBuf = Buffer.from(incomingSecret);
const expectedBuf = Buffer.from(expectedSecret);

if (
  secretBuf.length !== expectedBuf.length ||
  !crypto.timingSafeEqual(secretBuf, expectedBuf)
) {
  throw new UnauthorizedException("Invalid webhook secret");
}
Enter fullscreen mode Exit fullscreen mode

The app also refuses to start if the secret is not configured. A missing environment variable is the easiest way for an authentication check to turn itself off without anyone deciding to, so on boot the controller checks for the secret and exits the process if it is absent. Failing loudly on deploy is better than accepting everything quietly for a month.

And the secret must never be logged. This is in the code as a comment, and it is there because of what happened. During debugging, a statement logged both the secret the request presented and the secret the server expected. Log output was captured to a file, the file was committed, and the secret sat in version control history until a secrets scanner found it, eight times in one commit. It was rotated, the log statements were removed, and the comment now says that the header carries the secret in plaintext and no log line may touch either side of the comparison. A shared secret is only as private as the least careful place it gets printed.

The second one: a signature over the exact bytes

The other door belongs to Meta's WhatsApp Cloud API, and here the sender is a third party, so a shared secret in a header would be the wrong shape. Meta signs each delivery instead. The request carries X-Hub-Signature-256, an HMAC-SHA256 of the body, keyed with an app secret that only Meta and I know. If the signature matches, the body is the one Meta sent, unchanged.

The trap is in the word body. It means the exact bytes that arrived. Most web frameworks parse a JSON body before your handler sees it, and if you take the parsed object, serialise it again and hash that, the whitespace and key order may differ from what Meta signed. The signatures will not match, and the failure looks like an attack on every single request. The fix in this app is to keep the raw bytes around, and the handler hashes those:

const expected = crypto
  .createHmac("sha256", appSecret)
  .update(req.rawBody)
  .digest("hex");
Enter fullscreen mode Exit fullscreen mode

Three rules sit around that call. A missing app secret is a hard error and never a skipped check. A signature header without the sha256= prefix is rejected before any hashing. And if the raw body is unavailable, which means the app was deployed without the setting that keeps it, the request fails too, because that is a deployment fault and the safe response to a fault in a security check is to refuse.

Two paths for the same bytes, using an example body. Hash the parsed body: the bytes Meta signed are parsed and re-serialised with different whitespace and key order, the HMAC-SHA256 runs over different bytes, and the signature fails, which looks like an attack on every request. Hash the raw bytes: the bytes are kept as they arrived in req.rawBody, the HMAC-SHA256 runs over the same bytes, and the signature matches. Three rules each refuse: no app secret is a hard error, a missing sha256= prefix is rejected before any hashing, and a missing raw body fails the request as a deployment fault.

Each of those rules has a test: a correctly signed body is accepted, a tampered body is rejected, a body signed with the wrong secret is rejected, a missing header is rejected, a non-prefixed signature is rejected, and an app with no secret configured refuses every request. The tests generate their own secrets, so no real one ever sits in the repository.

A door schedule comparing the two webhooks. Door 1, GPS position updates: the sender is one machine I control, the check is a shared secret in a header compared in constant time, the request carries the secret itself in plaintext, the app exits on boot if the secret is not set, and the trap is logging it, which happened eight times in one commit before it was rotated. Door 2, WhatsApp Cloud API: the sender is Meta, the check is an HMAC-SHA256 of the body in X-Hub-Signature-256, the request carries a signature and not the app secret, a missing secret is a hard error and never a skipped check, and the trap is hashing the parsed body, so every signature fails like an attack.

A rate limit that knows who is asking

One more detail is specific to webhooks. Every delivery from Meta arrives from Meta's addresses, so a rate limiter keyed on client IP sees one very busy caller and throttles all of your users at once. The limit has to be keyed on something inside the payload, in this case the sender's phone number, which means it can only run after the signature has been verified and the body parsed. Limits per sender sit inside the handler, in order: a number of inbound messages per minute, a stricter limit on replies to numbers the app does not know, and a per-hour cap on commands from linked numbers.

What this does not cover

I have described verifying the sender. I have not described replay protection, which stops an attacker re-sending a genuine signed request later. Meta's scheme does not include a timestamp in the signed content in the way some providers' do, so any replay defence has to come from making the handler idempotent. This app acknowledges a delivery quickly and handles the work afterwards, and I have not shown that the handler is safe to run twice on the same event.

Run it against your own

Take a real event body for your endpoint, the kind your provider actually sends (its documentation has examples, and so do your logs), and keep it in a variable. Use the same body in every request below, so that a rejection can only come from the check you are testing, not from a body your code fails to parse. With no credentials:

BODY='{"event":"payment.succeeded","amount":5000,"customer":"cus_123"}'  # your provider's real event shape
curl -s -o /dev/null -w "%{http_code}\n" -X POST https://your-api.example/webhooks/your-endpoint \
  -H "Content-Type: application/json" -d "$BODY"
Enter fullscreen mode Exit fullscreen mode

You want a 401 or a 403. A 200 means the door is open, or may be: some endpoints answer 200 to everything and quietly drop what fails, and some acknowledge first and check later. So after a 200, look in the logs or the data for whether the event was acted on. A 400 proves nothing either way, because it usually means the body failed validation before any check ran.

If you do get a rejection, send the same body with a valid signature to make sure the good path works:

SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$YOUR_APP_SECRET" | sed 's/^.* //')
curl -s -o /dev/null -w "%{http_code}\n" -X POST https://your-api.example/webhooks/your-endpoint \
  -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$BODY"
Enter fullscreen mode Exit fullscreen mode

Then change one value in the body, keep the old signature, and send it again:

TAMPERED='{"event":"payment.succeeded","amount":9000,"customer":"cus_123"}'  # the same body, one value changed
curl -s -o /dev/null -w "%{http_code}\n" -X POST https://your-api.example/webhooks/your-endpoint \
  -H "Content-Type: application/json" -H "X-Hub-Signature-256: sha256=$SIG" -d "$TAMPERED"
Enter fullscreen mode Exit fullscreen mode

The signed request should pass and be processed, and the tampered one should fail and leave no trace in the data. The tampered body is still valid JSON in the same shape, so if it is rejected, the signature check rejected it. If both pass, the signature is being read and then ignored.

If your endpoint uses a shared secret in a header instead, like the first door above, run the same pair with that header: the right secret should pass, and the same request with one character of the secret changed should fail.

Three requests to aim at your own webhook. With no credentials and a plausible body you want a 401 or 403, and a 200 means the door is open. With a valid signature you want it to pass. With the same signature and one value in the body changed you want it to fail, and if both of those last two pass, the signature is read and then ignored.

Top comments (19)

Collapse
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

On replay: since the WhatsApp signature has no timestamp in the signed content, the defence is dedupe on event identity. Each message in the payload carries its own id (the wamid value), so insert that id into a table with a unique constraint before doing any work, and on a conflict return 200 and skip. That also makes acknowledge-first, handle-later safe, because a provider retry or a replayed capture hits the conflict instead of running the handler twice. One catch is atomicity: if the id insert and the job enqueue are separate steps, a crash between them leaves a recorded id with no job, and the retry is then silently dropped. Writing both in one transaction, with a jobs table as the queue, closes that gap. Keep the ids for as long as a replay is plausible, and since they are small, indefinitely is cheap.

Collapse
 
lawaloyinlola profile image
Oyinlola Lawal •

This is a clear write-up of the fix, and the atomicity catch is the part most people miss: a recorded id with no job is a silent drop, which is worse than a duplicate. One small nuance on timestamps. Meta's signature header has no timestamp of its own, but each message in the body carries one, and the body is what's signed. So a freshness check is possible. It just can't replace the dedupe you describe, because Meta retries failed deliveries, and a retry arrives late on purpose. Insert the id and the job in one transaction is the pattern I'd use for the next change.

Collapse
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

Agreed on the layering. If the body timestamp is used, the window has to be wide, since retries can land days later, so I would use it to flag and alert on old deliveries and not to reject them. Where it earns its place is ordering: status updates (sent, delivered, read) can arrive out of order, so compare the event timestamp with the stored one before overwriting a message's state. Otherwise a late "sent" can roll back a "read".

Thread Thread
 
heyvaldemar profile image
Vladimir Mikhalev •

Dedupe holds only while the key sits inside what the signature covers. In WhatsApp's case the wamid is in the signed body, so the unique constraint is sound. A key read from a header is not.

Cypress Cloud's webhooks show the split: X-Cypress-Signature covers X-Cypress-Timestamp and the body, and X-Cypress-Event-Id is outside it. In run 43513818839 I sent one real delivery back at the public URL with a fresh X-Cypress-Event-Id. It got 409, the same as the unchanged copy. Unsigned, or with one byte added to the body, it got 401, and none of the four started a job.

A dedupe table keyed on that header would have run the handler twice. On the GPS door, with only the shared secret checked, what would you key on?

Thread Thread
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

With only a shared secret and nothing signed beyond the body, I would key on a hash of the raw body plus the device id read from inside the body, since that is the only input the secret covers. If the payload carries a device sequence number or a reading timestamp, put it in the key too, otherwise two identical readings collapse into one. Keep the dedupe rows at least as long as the longest retry window, and treat every header outside the key as untrusted metadata.

Thread Thread
 
lawaloyinlola profile image
Oyinlola Lawal • • Edited

Good point, and the current code doesn't do it: it takes one secret. Both ends are on one box, so the gap during a routine rotation is short, but accepting the current and previous secret for a brief overlap is cleaner. The one exception is a leak: then the old secret should die at once, even if a few requests fail until the sender is updated. Noting the overlap for the next pass.

Thread Thread
 
heyvaldemar profile image
Vladimir Mikhalev •

That key covers exactly what the secret covers, so it holds. The status code you answer with matters as much as the key.

Cypress Cloud retries a delivery, up to ten attempts with backoff, after a network error, a 408, a 429 or a 5xx, and never after another 3xx or 4xx. The receiver in ADR 9 answers a replay with 409, so the provider stops there. A dedupe check that throws and returns 500 turns one duplicate into up to ten.

On the GPS door, the vendor's retry list decides which code is safe.

Thread Thread
 
hritik_chaudhary_5db0056f profile image
Hritik Chaudhary •

That is the right way to pick it: the provider's retry list decides. If the docs are silent, send one replayed delivery from a test sender and watch whether the provider retries on your answer. For an already-accepted duplicate I would answer 2xx unless the vendor documents that it stops on a 4xx, and the log line should say duplicate, not error.

Collapse
 
userxnom profile image
Abdullah Naseer •

Oyinlola, the "two doors" framing is what makes this stick — the same endpoint shape, two completely different trust models, and the check has to match the sender, not the route. The detail I would steal is the fail-closed defaults: refusing to start without the secret, and treating a missing app secret as a hard error instead of a skipped check. Most webhook guides show the HMAC and stop there; yours shows what happens when the pieces around it are missing.

The trap I have seen most is the one you name in the second door: hashing the parsed body instead of the exact bytes. A JSON parser that reorders keys or normalises whitespace quietly breaks every signature, and the failure looks like the provider is wrong.

One question on the part you deliberately left out: since you name replay protection as not covered, do you check a timestamp on the signed payload anywhere in your own setup, or is that the next control you would add after the signature and the per-sender rate limit?

Collapse
 
lawaloyinlola profile image
Oyinlola Lawal •

Thanks Abdullah. Honest answer: no, not yet. There's no timestamp check and no dedupe in the handler today, which is why replay sits under what the post doesn't cover. Two things blunt it a little. A tap on a menu that has since been replaced is ignored, because the reply has to point at the current prompt, and the per-sender limits cap how fast anyone can repeat a message. Neither stops a replay of the current message. The next control is dedupe on the message id, and Hritik's reply below describes it better than I would have.

Collapse
 
maxbuildsdev profile image
Max Kaya •

The signature half is right, but there's a third door you get for free once you verify: replay. A captured request with a valid X-Hub-Signature-256 stays valid forever, so an attacker who sees one delivery (proxy log, a stolen backup, whatever the secret leak was) can POST the same bytes again and your handler processes the same payment twice. Meta's own payload leaves you the fix — keep a short TTL table keyed on the event id in entry[].changes[].value.messages[].id (or the X-Hub-Signature-256 plus a timestamp if you control the sender) and reject anything you have already accepted inside the window, with the insert as the lock so two concurrent retries can't both win. Same applies to the GPS door: a shared secret plus a timestamp header, reject older than a couple of minutes.

One more on the secret: timingSafeEqual protects the comparison, but the throw-on-length-mismatch means you leak length by the different exception path anyway. Hashing both sides to a fixed width first (sha256(incoming) vs sha256(expected)) closes that without the branch.

Does the WhatsApp handler do anything at all before the signature check, like writing a log row or touching the DB? If yes and it's before, a replayed request hits the side effect even if you later return 401.

Collapse
 
paullovelace profile image
Paul Lovelace •

The secret sitting in git history until a scanner found it eight times in one commit — yeah, that one hurt to read, I've done the dumber version of that with a log line. The raw-body trap is the part I'd have tripped on too, re-serialising feels like the obvious thing to do. For the GPS door, do you rotate that shared secret on any schedule, or is it set-and-forget since it's one machine you control?

Collapse
 
lawaloyinlola profile image
Oyinlola Lawal •

Closer to set-and-forget, honestly. It has been rotated once, after that scanner find, and there's no schedule yet. Both ends sit on one server I run, so a rotation is a single coordinated change, which is probably why it never got a calendar. Kevin's comment below is the better answer to how it should work.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

refusing to start when the secret is missing is the part i would steal. failing loudly on deploy beats accepting everything quietly for a month.

Collapse
 
lawaloyinlola profile image
Oyinlola Lawal •

Steal away. It came from asking how the check could switch itself off without anyone deciding to, and a missing env var was the easiest answer.

Collapse
 
gautamtalksdev profile image
Gautam K •

The cheerful 200 to an unsigned webhook is scary because it looks like everything works. Verifying the signature and the timestamp before anything else should be the first line in every handler.

Collapse
 
lawaloyinlola profile image
Oyinlola Lawal •

Agreed on the signature first. Meta's scheme doesn't sign a timestamp, though, so for that door replay protection has to come from the handler being safe to run twice. That's the gap I flagged at the end of the post.

Collapse
 
kevinhall profile image
Kevin Hall •

worth letting the first door accept two secrets for a short window, otherwise rotating after a leak either drops requests or keeps getting put off

Collapse
 
lawaloyinlola profile image
Oyinlola Lawal •

Good point, and the current code doesn't do it: it takes one secret. Both ends are on one box, so the gap during a rotation is short, but accepting the current and previous secret for a brief overlap is cleaner, and it means a rotation after a leak never waits for a quiet moment. Noting it for the next pass.