SECRETS, ROTATION & REPLAY

A signed request is still valid the second time it arrives

L215 MINSECURITY
PREDICT

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.

▶ SIMULATION
PROVIDER
signs with k1
payments sent 0 · $0
sig = HMAC(key, ts.nonce.body)
RECEIVER
trusts: k1
checks: sig only
nonce store (0): —
credited $0 for $0 paid
ATTACKER
captured 0 · replayed 0
holds no key; only copies of signed requests
clockt = 0 s
last—
receiver log—
✓ each request is processed at most once✓ every genuine request is accepted
SCHEDULE
01[RECEIVER]receiver: check the signature, nothing else
02[CLOCK]clock → t = 0 s
03[PROVIDER]provider sends evt_1 (payment of $50)
04[CLOCK]clock → t = 600 s
05[ATTACKER]attacker re-sends a captured request, byte for byte
06[RECEIVER]report
Start of signature only scenario. 6 steps.
// 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;

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.

BREAK IT NOT YET

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

FIX IT NOT YET

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).

Mental model:

A signature has no expiry and no memory; you add both. The signed timestamp gives expiry, the nonce store gives memory, and the window is what keeps the memory small. For rotation, think overlap: trust new and old, switch the signer, then retire the old key once nothing signed with it can still pass the window.

IN PRODUCTION

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.

IN INTERVIEWS

“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.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.

NEXT: CAPSTONE: HARDEN A LOGIN FLOW →