About

What Is CSRF? How Rails Blocks Forged Requests with Tokens

Why you get a 422, the null_session trap, and how it differs from SameSite

Browsers attach cookies on their own. So a form hidden on another site can POST to your server and arrive looking like a logged-in user. The fix is to require one more value the attacker can't read, and that's the CSRF token.

The cookie comes along. The token does not.evil.examplehidden form, auto-submitcannot read your HTMLBrowserlogged in to your appcookie jarYour Rails appcookie: validtoken: missingPOST+ cookieInvalidAuthenticityToken422 in productionSameSite=Lax also stops the cookie on a cross-site POST.A sibling subdomain counts as same-site, so it still gets through.The token lives in your own page, and another origin cannot read it.

form_with adds a hidden authenticity_token field and csrf_meta_tags puts an equivalent value in <head>. Turbo sends that meta value as an X-CSRF-Token header on unsafe requests. GET and HEAD aren't checked, so changing data on a GET is outside this protection.

What I got when I ran it

A small Rails 8.0.4 app on load_defaults 8.0, with the check on:

POST, no token                          422
POST, form token                        200
POST, meta token via X-CSRF-Token       200
Old form in another tab after logout    422
protect_from_forgery (no args), no token  200, empty session
ActionController::API, no token         200

The 422 and the exception are one event

On a bad token Rails raises ActionController::InvalidAuthenticityToken, and ActionDispatch::ExceptionWrapper turns it into a 422. The error screen in development and the 422 page in production are the same thing.

You can get a 422 with no attack at all, as in row four. Log out in one tab and the session changes, so the form in another tab dies with a 422. To the user that looks broken, so explain and send them back.

rescue_from ActionController::InvalidAuthenticityToken do
  redirect_to new_session_path, alert: 'Your session ended. Please log in again.'
end

The null_session trap

Row five is the dangerous one. ActionController::Base raises by default, but calling protect_from_forgery yourself with no arguments sets the strategy to :null_session (options[:with] || :null_session in the source). The request isn't blocked. The action runs with an empty session.

An action that needs login still bounces, but one that doesn't just runs. If you call it, write with: :exception. :null_session is a deliberate choice for when cookie sessions and API tokens share a controller.

How is this different from SameSite and API tokens?

SameSite cookies: since load_defaults 6.1 the session cookie carries samesite=lax (confirmed in that app's Set-Cookie). A POST from another site gets no cookie, which is one more layer. But sibling subdomains count as the same site, so on a service with several subdomains, don't turn tokens off.

API tokens (Authorization header): browsers don't attach them on their own, so CSRF doesn't apply. That's why ActionController::API has no check at all (last row). Log people into an API with a cookie, though, and you're back in scope.

Webhooks: the sender doesn't know your token, so use skip_forgery_protection and verify the signature instead. Turning the check off without checking the signature lets anyone call it.

If you're unsure where the check got turned off, grep for skip_forgery_protection and read each hit. If you'd like a second pair of eyes, you can ask negabaro.

Key Points

1

Find where it's off with `grep -rn skip_forgery_protection app/`

2

If you find a bare `protect_from_forgery`, add `with: :exception`

3

Check that no GET action changes data

4

Give `InvalidAuthenticityToken` a friendly response

← What Is Devise? The Gem That Adds Login and Sign-Up to Rails What Are Strong Parameters? Accepting Only the Fields You Allow →