CSRF and sessions
The CSRF protection you turned off to fix one bug
Rails protects every form by default. The holes are skipped callbacks, state-changing GETs, and sessions nobody hardened.
In 2021, a researcher reported that GitLab’s GraphQL API would run mutations sent as GET requests. GitLab protected GraphQL from CSRF with an X-CSRF-Token header on POSTs, and the backend didn’t expect that header on a GET, so it didn’t look for one. A link was enough to make a logged-in user’s browser change things in their account (the GitLab issue). In 2024, CVE-2024-4994 found another way to the same place through multiplexed queries, and per GitLab’s issue it let an attacker run arbitrary mutations as the victim, including ones that steal CI/CD variables, with one click. GitLab is one of the biggest Rails apps out there, and it has a security team.
ActionController::Base has forgery protection on by default (since Rails 5.2), and form_with adds the token for you. If you never touch any of it, you’re fine. The trouble is that it’s really easy to touch.
The basic bug
class CommentsController < ApplicationController
skip_before_action ,
end
This shows up when a fetch call from the front end starts failing with InvalidAuthenticityToken and someone makes the error go away. The endpoint still authenticates with the session cookie, so any website your users visit can now post comments as them.
The basic fix
fetch("/comments", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": document.querySelector("meta[name='csrf-token']").content
},
body: JSON.stringify({ comment: { body } })
})
Delete the skip_before_action and send the token. It’s already in the page if your layout has csrf_meta_tags. Webhooks are the legitimate reason to skip verification, because Stripe doesn’t have your token; those controllers should check a signature and never touch the session.
The hardcore version
resources do
get ,
get ,
end
Nothing is skipped and the tokens are all in place, and it’s still forgeable. Rails only checks the token on non-GET requests, because GETs are supposed to be safe. A link to https://yourapp.com/invoices/42/cancel in an email, a forum post, or a window.location on some page fires that request with the victim’s cookies attached. The default SameSite=Lax session cookie doesn’t help here: Lax blocks cookies on cross-site form posts and image loads, but still sends them on top-level GET navigations, which is exactly what a link is.
The API controller version
class Api::BaseController < ActionController::Base
skip_forgery_protection
before_action
private
def authenticate
token = request.headers["Authorization"]&.delete_prefix("Bearer ")
@current_user = User.find_by( token) if token
@current_user ||= User.find_by( session[])
head unless @current_user
end
end
Skipping forgery protection on a token API is reasonable, since a browser won’t attach a header token on its own. The session fallback inside authenticate isn’t. Somebody wanted the app’s own front end to call the API without juggling tokens, so the API also accepts the session cookie, and now every endpoint under /api is cookie-authenticated with CSRF checks off. SameSite=Lax keeps most cross-site posts from carrying the cookie in modern browsers, which is why nobody noticed. It doesn’t help when the request comes from one of your own subdomains (same-site, as far as the browser cares), or when the app set SameSite=None so it could run inside a customer’s iframe.
def authenticate
if (token = request.headers["Authorization"]&.delete_prefix("Bearer "))
@current_user = User.find_by( token)
else
verify_authenticity_token
@current_user = User.find_by( session[])
end
head unless @current_user
end
Token in the header, no CSRF check needed. Cookie, CSRF check required. The front end already has the token from csrf_meta_tags. Cleaner still: put the token API on ActionController::API, which doesn’t load sessions or cookies at all, and give the front end its own controllers.
The token check is code too, and it’s had bugs. CVE-2020-8166 let anyone holding a session’s global CSRF token (the one in the meta tag) build valid per-form tokens for that session. The Rails team rated it low severity, since you’d need an HTML injection bug first, and fixed it in 5.2.4.3 and 6.0.3.1. Patch releases are part of the protection.
The logout version
def destroy
reset_session
redirect_to root_path
end
With the default cookie store, the session lives entirely inside the cookie. There’s no server-side record to delete, so reset_session tells this one browser to forget its copy and that’s all it can do. A copy taken earlier (from a shared computer, a sketchy browser extension, a proxy log that captured headers) keeps working until expire_after runs out, and if you never set expire_after, nothing on the server ever expires it. Changing your password doesn’t touch it either. So the user who logged out everywhere and changed their password is still logged in somewhere else.
module Authentication
private
def start_new_session_for(user)
session_record = user.sessions.create!( request.user_agent, request.remote_ip)
cookies.signed.permanent[] = { session_record.id, true, }
end
def resume_session
Current.session ||= Session.find_by( cookies.signed[])
end
def terminate_session
Current.session.destroy
cookies.delete()
end
end
def update
current_user.update!(password_params)
current_user.sessions.where.not( Current.session.id).destroy_all
redirect_to root_path
end
The cookie now holds a pointer to a row instead of the session itself. Delete the row and every copy of the cookie stops working, wherever it ended up. This is what bin/rails generate authentication sets up in Rails 8, so new apps get it for free. Devise apps get half of it: Devise keeps part of the password hash in the session and rejects sessions where it doesn’t match, so a password change kills other sessions, but logging out still only clears the one browser.
Fix #1: GETs read, everything else writes
resources do
patch ,
patch ,
end
<%= button_to "Cancel invoice", cancel_invoice_path(@invoice), method: :patch %>
button_to renders a small form with the token included. Then grep config/routes.rb for get routes whose names are verbs. mark_paid, cancel, approve, unsubscribe, delete: if it changes data, it doesn’t belong on GET.
GraphQL gets the same rule. The simplest fix for GitLab’s bug is to never route GETs to it:
post "/graphql", "graphql#execute"
If you want GET for cacheable queries, check the operation type on the query you’re about to execute, not on a separate read of the params:
def execute
query = GraphQL::Query.new(AppSchema, params[],
prepare_variables(params[]),
params[],
{ current_user })
return head if request.get? && query.mutation?
render query.result
end
The 2024 bug was that kind of gap: the check looked at one interpretation of the request and execution followed another. Check the thing that actually runs.
Fix #2: Reject cross-site requests with Fetch Metadata
Every modern browser sends a Sec-Fetch-Site header that says whether a request came from your own site. That gives you a second check that doesn’t depend on tokens at all:
class ApplicationController < ActionController::Base
before_action
private
def reject_cross_site_writes
return if request.get? || request.head?
head if request.headers["Sec-Fetch-Site"] == "cross-site"
end
end
Older clients and server-to-server requests don’t send the header at all, which is why this only rejects an explicit cross-site instead of requiring same-origin. It sits alongside the token check, not in place of it.
Fix #3: Harden the session itself
Rails.application.config.session_store ,
"_yourapp_session",
,
true,
.hours
def create
user = User.authenticate_by( params[], params[])
return redirect_to new_session_path, "Try again." unless user
reset_session
session[] = user.id
redirect_to root_path
end
SameSite=Strict stops the browser from sending the session cookie on any cross-site request, GETs included. The cost is that following a link to your app from email or Slack lands the user logged out for that first page, which is fine for an admin panel and annoying for a consumer app. reset_session before writing the user ID throws away any session an attacker planted before login; Devise does this for you, hand-rolled auth usually doesn’t.
And if you’ve ever written cookies[:user_id] = user.id, go fix that first. A plain cookie is whatever the browser says it is. Change it to 1 and you’re probably the founder.