SECRETS, ROTATION & REPLAY
A signed request is still valid the second time it arrives
Your receiver checks HMAC(secret, ts.nonce.body), a tag over the timestamp, a random nonce and the body, and nothing else. An attacker finds last week's genuine request in a log and sends it again, unchanged. What happens?
A signature answers “who wrote this?”. It does not answer “is this the first time?”. A captured request, from a proxy log, a debug dump or a retry queue, verifies forever.
Freshness is a separate check. The sender signs a timestamp and a random nonce along with the body. The receiver rejects anything outside a short window, and remembers the nonces it has accepted inside that window. Old copies fail the window; quick copies fail the nonce.
Rotation is the same idea in reverse: the receiver trusts both keys while the sender switches, so no genuine request is ever signed with a key the receiver has dropped.
// timingSafeEqual throws on unequal lengths, so compare equal-length Buffers
const safeEqual = (a, b) => {
const x = Buffer.from(a, 'hex'), y = Buffer.from(String(b || ''), 'hex');
return x.length === y.length && timingSafeEqual(x, y);
};
app.post('/webhook', (req, res) => {
const sig = hmac(SECRET, `${req.headers.ts}.${req.headers.nonce}.${req.rawBody}`);
if (!safeEqual(sig, req.headers.sig)) return res.sendStatus(401);
creditAccount(req.body); // valid today, valid next month
res.sendStatus(200);
});
// rotation: swap the secret in one deploy
const SECRET = process.env.WEBHOOK_SECRET_V2;// timingSafeEqual throws on unequal lengths, so compare equal-length Buffers
const safeEqual = (a, b) => {
const x = Buffer.from(a, 'hex'), y = Buffer.from(String(b || ''), 'hex');
return x.length === y.length && timingSafeEqual(x, y);
};
const KEYS = [env.WEBHOOK_SECRET_V2, env.WEBHOOK_SECRET_V1]; // overlap during rollout
const WINDOW = 300;
app.post('/webhook', async (req, res) => {
const { ts, nonce, sig } = req.headers;
const msg = `${ts}.${nonce}.${req.rawBody}`;
if (!KEYS.some((k) => safeEqual(hmac(k, msg), sig))) return res.sendStatus(401);
if (Math.abs(nowSeconds() - Number(ts)) > WINDOW) return res.sendStatus(401);
// SET NX with a TTL: atomic, and expires with the window
if (!(await redis.set(`nonce:${nonce}`, 1, { NX: true, EX: WINDOW * 2 }))) return res.sendStatus(409);
creditAccount(req.body);
res.sendStatus(200);
}); Watch the RECEIVER box. In SIGNATURE ONLY, credited climbs past paid and the first invariant turns red. In WINDOW + NONCE the same replays are rejected, one by the nonce store and one by the window. HARD CUTOVER rejects a genuine payment and breaks the second invariant; OVERLAPPING KEYS accepts all three and still rejects the replays.
The receiver checks the signature and nothing else. Insert one attacker step so that one payment is credited twice.
GOAL: one event is processed twice
Return true only for a request that is authentic, fresh and new. keys is every secret currently trusted (new and old during a rotation); each has mac(payload). nonces is a Map from nonce to ts that persists between calls. Reject anything signed more than 300 s from now either way. A forged request must not use up a nonce. Keep the store bounded: drop a nonce only once its request can no longer pass the time check (keyed by ts, that is 300 s; keyed by arrival time, 600 s, because a request dated 300 s ahead stays fresh for 600 s).
Stripe's Stripe-Signature header signs timestamp.body and its libraries reject old timestamps (300 s by default). Slack request signing does the same. AWS SigV4 rejects requests whose date is too far from the server's clock. Key rotation with overlap shows up as JWKS key sets with several kids, and as webhook endpoints that list more than one active secret.
“How do you secure a webhook endpoint?” Verify an HMAC over the raw body with a constant-time compare, sign and check a timestamp window, dedupe by nonce or event id with a TTL (SET NX in Redis), make the handler idempotent anyway because providers retry, and describe a zero-downtime secret rotation.
USED IN
Chapters that build on this lesson.
- A security engineer's weekSecurity
- Cloud and infrastructure securitySecurity
- Detection and incident responseSecurity
- Identity, access and secretsSecurity
- Security philosophies: defence in depth, least privilege, assume breach, risk not fearSecurity
- Security review when AI agents write the codeSecurity
- Threat modellingSecurity
- Triaging researcher reports: running a disclosure programme day to daySecurity
- Why security engineering existsSecurity