In Rails, how does config.action_dispatch.cookies_rotations keep signed and encrypted cookies readable after you change the secret, cipher or digest?
answer
- write with the new, read with old too
- rotate :signed and rotate :encrypted
- old secret means a derived key
- re-written with the current key on read
- remove the rotation after the window
basics
~20 sEach cookies.rotate entry gives the signed or encrypted jar an extra secret, digest or cipher to try when the current one fails. Cookies are always written with the current settings, and a cookie read through an old entry is re-written with the current key, so the rotation can be removed later.
solid answer
~40 s`config.action_dispatch.cookies_rotations` is an `ActiveSupport::Messages::RotationConfiguration`. Calling `cookies.rotate :signed, ...` or `cookies.rotate :encrypted, ...` registers fallback secrets and options (`digest:`, `cipher:`) that the jar's verifier or encryptor tries after the current configuration. New cookies are always written with the current secret. When a cookie verifies only through a rotation, Rails sets it again with the current key in the same response, so active readers migrate on their next visit. A changed `secret_key_base` needs the old **derived** keys: build an `ActiveSupport::KeyGenerator` from the old secret and generate keys with the cookie salts, as the upgrade guide shows. Keep the rotation for longer than your longest-lived cookie should still be honoured, then delete it.
code
ruby · 16 linesclass ApplicationController < ActionController::Base
before_action :resume_from_remember_token
private
def resume_from_remember_token
token = cookies.signed[:remember_token] or return
reader = RememberToken.find_by(token_digest: Digest::SHA256.hexdigest(token))&.reader or return
# Re-set with full options; a rotation re-write would drop them.
cookies.signed[:remember_token] = {
value: token, expires: 2.weeks, httponly: true, secure: Rails.env.production?
}
Current.reader = reader
end
endgo deeper
Recall that changing secret_key_base makes signed and encrypted cookies read as nil, and that cookies_rotations exists to keep old ones readable.
Explain rotate :signed and :encrypted, that writes use current settings, that a successful old read re-writes the cookie, and why derived keys are needed.
Show you ship the rotation with the change, size the window to the longest cookie, re-set attribute-sensitive cookies, and remove the rotation afterwards.
Plan secret and algorithm changes as timed migrations with an end date, and separate them from incident response, where invalidating everything is the goal.
## The problem rotations solve A news-reader app keeps readers signed in with a signed remember-me cookie that lasts two weeks, and keeps some preferences in an encrypted cookie. Three kinds of change would make every existing cookie fail verification and read as `nil`: - a new **`secret_key_base`** (after a leak, or on a schedule); - a new **digest** for signed cookies, such as moving from SHA1 to SHA256; - a new **cipher** or key derivation for encrypted cookies, as happened when the 5.2 defaults moved to AES-256-GCM and the 7.0 defaults moved the key generator to SHA256. Without help, every reader is signed out at deploy time. ## How rotation works `config.action_dispatch.cookies_rotations` holds an `ActiveSupport::Messages::RotationConfiguration`. Each `rotate` call adds a fallback for one jar: ```ruby Rails.application.config.action_dispatch.cookies_rotations.tap do |cookies| cookies.rotate :signed, digest: "SHA1" end ``` When the signed or encrypted jar is built for a request, it creates its verifier or encryptor with the **current** settings and then calls `rotate` on it once per registered entry. On read: 1. Rails tries the current key, digest and cipher. 2. If that fails, it tries each rotation in turn. 3. If one succeeds, the value is returned **and** the cookie is written again with the current settings in this response. 4. If none succeeds, the read returns `nil`. On write, only the current settings are used. Rails' own test suite checks this: a cookie signed with an old secret and SHA1 is readable, and the response carries it re-signed with the current secret and SHA256. ## Rotating secret_key_base A `rotate` entry for a new secret needs the **derived keys**, not the raw `secret_key_base`, because cookie jars sign and encrypt with keys generated from it plus a salt. The upgrade guide's pattern: ```ruby # config/initializers/cookie_rotator.rb Rails.application.config.after_initialize do Rails.application.config.action_dispatch.cookies_rotations.tap do |cookies| old = ActiveSupport::KeyGenerator.new(ENV.fetch("OLD_SECRET_KEY_BASE"), iterations: 1000) config = Rails.application.config.action_dispatch cookies.rotate :signed, old.generate_key(config.signed_cookie_salt) cookies.rotate :encrypted, old.generate_key( config.authenticated_encrypted_cookie_salt, ActiveSupport::MessageEncryptor.key_len("aes-256-gcm") ) end end ``` The salts default to `"signed cookie"` and `"authenticated encrypted cookie"`. The session cookie goes through the encrypted jar, so the encrypted rotation also keeps sessions alive. Where the secret itself lives and how it is replaced belongs to the credentials topic. ## Which rotate call for which change | Change | Rotation to add | |---|---| | signed digest SHA1 to SHA256 | `cookies.rotate :signed, digest: "SHA1"` (the security guide's example) | | new `secret_key_base` | `rotate :signed` and `rotate :encrypted` with keys derived from the old secret | | key generator digest change, as in the 7.0 defaults | both jars, with keys derived using the old digest class (the upgrade guide's example) | | another cipher for encrypted cookies | `rotate :encrypted` with the old key and its `cipher:` | ## Running a rotation safely - **Deploy the rotation together with the new setting.** Old cookies then keep working from the first request. - **Wait out the window.** Cookies are re-written only when a reader visits; someone who returns after the window still holds an old cookie. Keep the rotation at least as long as the longest expiry you intend to honour, such as two weeks for remember-me. - **Then delete the entry.** Each rotation is one more key an attacker's forged or stolen cookie could verify against, and it costs a failed attempt on every old read. - **Re-set cookies whose attributes matter.** The automatic re-write sets the cookie from its value alone, without the `expires:`, `httponly:` or `domain:` you used originally, so for a remember-me token it is better to write it again yourself with full options once you have verified it. ## What rotations do not cover - **Plain cookies** have no key and need nothing. - **Revocation.** A rotation keeps old cookies valid on purpose. To invalidate a leaked secret's cookies, change the secret **without** rotating, accepting that everyone is signed out. - **Other message verifiers** in the app, such as signed ids or tokens, have their own rotation settings.
- Why must a secret_key_base rotation pass derived keys instead of the old secret itself?The signed and encrypted jars never use `secret_key_base` directly; they derive a key from it with `ActiveSupport::KeyGenerator` and a salt such as `signed_cookie_salt`. A rotation entry is handed to the verifier or encryptor as its key, so it has to be the old derived key, generated with the same salt, iteration count and key length.
- How do you invalidate every cookie made with a leaked secret?Change `secret_key_base` and do not add a rotation for the old one. Every signed and encrypted cookie, the session cookie included, then reads as `nil`, signing everyone out. A rotation would do the opposite and keep the leaked secret's cookies valid.
A rotation is changing the locks while the old key still opens the door for a grace period, and each time someone uses an old key the doorman hands them a new one. New keys are only ever cut for the new lock.
- cookies_rotations makes Rails write new cookies with the old secret
- rotate :signed takes the old secret_key_base string unchanged
- a rotation is the way to revoke cookies signed with a leaked secret
- rotated cookies are only upgraded when the user signs in again
- plain cookies[] values must also be rotated when the secret changes