Rails Security
Rails protects you by default more than most frameworks, which is why its failures are interesting: they happen where someone turned a default off, or never configured what Rails left to you. Two things are always left to you: authorisation and dependency hygiene.
The 60-second answer
Section titled “The 60-second answer”“CSRF is handled by a per-session authenticity token in forms, checked by protect_from_forgery — which is why skip_before_action :verify_authenticity_token is a finding. XSS is handled by escaping ERB output; vulnerabilities come from raw, html_safe, <%== and permissive sanitize options. SQL injection is prevented by bound parameters — where("name = ?", x), never interpolation, and never where(params[:filter]) because hash keys become column names. Mass assignment is prevented by strong parameters: permit is an allow-list, permit! is the vulnerability. Secrets live in encrypted credentials or environment variables. Session cookies need httponly, secure and a deliberate same_site. And you run Brakeman and bundler-audit in CI, because the vulnerability you ship is usually in a gem.”
The attack: evil.com submits a form to yourapp.com/account/delete; the browser attaches your session cookie automatically. The defence is a token the attacker cannot read.
<%= form_with model: @post do |f| %> <%# includes the token %>form_with,form_forandbutton_toinclude the token; a hand-written<form>does not.- A missing or invalid token raises
ActionController::InvalidAuthenticityToken. same_site: :lax(the Rails default) blocks cross-site POSTs in modern browsers, but not forSameSite=None, older clients, orGETroutes that mutate state.GETmust never mutate.- Token auth in an
Authorizationheader is not CSRF-vulnerable, because the browser does not attach it automatically. That is whyActionController::APIomits the check.
<%= raw(user.bio) %> <%# dangerous %><%= user.bio.html_safe %> <%# dangerous %><%== user.bio %> <%# dangerous, same as raw %><%= sanitize(user.bio, tags: %w[b i em strong], attributes: %w[href]) %>
<%# inside an attribute: quote it; inside <script>, ERB escaping does not help %><a title="<%= user.name %>">...</a><div data-controller="greeting" data-greeting-name-value="<%= user.name %>"></div>A CSP without unsafe_inline for scripts turns most XSS into a broken page instead of a stolen session.
SQL injection
Section titled “SQL injection”Post.where("title = ?", params[:title]) # safe: bound parameterPost.where(title: params[:title]) # safe: hash formPost.where("title = '#{params[:title]}'") # vulnerable: interpolationPost.order(params[:sort]) # identifiers cannot be boundPost.where(params[:filters]) # hash keys become column namesorder, pluck, select and group take identifiers, which cannot be bound — allow-list them:
SORTABLE = { "newest" => "created_at DESC", "title" => "title ASC" }.freezePost.order(Arel.sql(SORTABLE.fetch(params[:sort], "created_at DESC")))Arel.sql on user-supplied input is the same vulnerability with extra steps.
Mass assignment and authorisation
Section titled “Mass assignment and authorisation”permit is an allow-list of what the form may set. Anything a user should not choose — admin, role, account_id, price — must be set server-side:
Rails has no default authorisation. Authentication is Devise or the Rails 8 generator; authorisation is Pundit, CanCanCan, or explicit scoping:
@invoice = Invoice.find(params[:id]) # IDOR: any id works@invoice = current_account.invoices.find(params[:id]) # scoped: 404 for someone else'sScoping through the current user is the cheapest authorisation there is, and it is what prevents insecure direct object references.
Secrets and cookies
Section titled “Secrets and cookies”bin/rails credentials:editbin/rails credentials:edit --environment productioncredentials.yml.enc is encrypted with master.key, which must never be committed; without RAILS_MASTER_KEY production cannot boot, which is the design. If a secret ever reaches git history, rotate it — deleting the commit does not delete the secret.
cookies.encrypted[:remember_token] = { value: user.signed_id(purpose: :remember, expires_in: 30.days), httponly: true, # not readable by JavaScript secure: true, # HTTPS only same_site: :lax, # or :strict expires: 30.days}httponly stops XSS stealing the session, secure stops it leaking over HTTP, same_site blocks cross-site sends. The default cookie session is encrypted and signed, so it cannot be read or forged — but it cannot be revoked either, which is why a database-backed session matters for “log out everywhere”.
File uploads and auditing
Section titled “File uploads and auditing”Active Storage signs URLs, so files are not guessable — but content_type comes from the client:
Serve uploads from a separate origin or with Content-Disposition: attachment, so an uploaded HTML file cannot run in your origin, and never pass a user-supplied filename to send_file.
Run both in CI and fail on new warnings. Most real-world Rails compromises come from an outdated dependency, not a clever attack on your code.
Follow-up questions
Section titled “Follow-up questions”- How does CSRF protection work, and why does an API with bearer tokens not need it?
- What makes
rawdangerous when ERB already escapes? - Why is
where(params[:filters])injectable with no string interpolation? - What is the difference between authentication and authorisation in Rails?
- Which cookie flag stops XSS from stealing a session?
Common traps
Section titled “Common traps”skip_before_action :verify_authenticity_token. Justify it or remove it.html_safeon anything a user typed. The classic Rails XSS.- Authorising in the view. Hiding a button does not stop a POST.
permit!. Mass assignment, reintroduced deliberately.- Trusting
content_typefrom the client. It is an attacker-controlled string.
Further reading
Section titled “Further reading”- Rails Security Guide — read it end to end once.
- OWASP Top 10
- Brakeman