Advanced

Rotating a live secret

A signing key leaked and I swapped it, and every old token broke. Rotation must accept the old key briefly while the new one takes over.

What you will see

True

About 1 min of reading

Try It

Rotate a signing key without breaking live tokens.

1

Sign a new token with the new key.

sign(payload, NEW_KEY)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
token signed with NEW_KEY
2

Verify accepts either key during the window, so an old token still passes.

verify(sig, [NEW_KEY, OLD_KEY])

Before you run it, say out loud what it will print. Then open the answer.

What it prints
True
The window must exceed the longest token lifetime. If tokens live 24h, a 1h window rejects valid old tokens mid-flight. Size the window from the lifetime, not a guess.

Data Flow

During rotation you sign with the new key but verify with new-or-old for a window longer than the longest token lifetime, then drop the old key.
1 Sign new with new key
↓
2 Verify new or old in window
↓
3 Window longer than lifetime
↓
4 Drop old after window
Why this works
Rotate without a cliff

A secret that signs live tokens cannot be swapped instantly. Keep a current key for signing and a previous key for verifying during a window, then drop the previous once no old token can still be presented.

Window beats lifetime

The accept-old window must be longer than the longest-lived token or signature you issue. Set it from that lifetime, not a guess, so you never reject a still-valid old token and never accept a burned one forever.

Examples

The break

old key -> new key instantly
old tokens -> all fail at once

A hard swap invalidates everything signed with the old key in one instant. A live site has traffic mid-swap.

Two keys briefly

sign with: new
verify with: new OR old

Sign new work with the new key, but accept either for a window. Old tokens keep working while new ones migrate.

Then drop the old

after window: verify with new only

After the window (longer than the longest token lifetime), stop accepting the old key. The leak is now fully burned.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Injection beyond the page
Previous Lesson
Injection beyond the page
Next Lesson
Auditing a whole app
Auditing a whole app →