Our webhook signature check failed 1 in 300 events
Found this when signature verification rejected about 1 in 300 webhooks, only for some merchants. The HMAC matched every time in testing.
The handler ran express.json(), then verified the signature against JSON.stringify(req.body). Most payloads round-tripped to identical bytes. Some did not.
Same data, different bytes
The gateway sent a non-ASCII cardholder name escaped as \u00e9, and JSON.stringify emits the raw character instead. Same data, different bytes, different HMAC.
Another source was an amount like 10.50 that came back as 10.5.
The failures looked random, so the first guess was clock skew or a flaky proxy. It was neither. The sender signs the exact bytes it wrote, and anything that parses and re-serializes the body changes them.
The fix
The fix was small:
- Capture the raw body before any parser touches it (in Express, the
verifyoption of the JSON parser, storing aBufferonreq). - Compute HMAC-SHA256 over that buffer.
- Compare with
crypto.timingSafeEqual, after checking the lengths match, since it throws on unequal lengths. - Parse the JSON only after the signature passes.
Two things to check
Two things to check in your own setup. A proxy that re-compresses or converts charset in front of the handler can alter the bytes too. And a "skip verification" flag added during debugging has a habit of surviving into production.
We now keep a fixture set with escaped unicode, trailing zeros and shuffled key order. How do you test the signature path before it meets real traffic? Payneteasy handles this kind of payment flow for merchants and PSPs - see how it works.
Comments
No comments yet. Start the discussion.