Skip to content

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.

“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_for and button_to include 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 for SameSite=None, older clients, or GET routes that mutate state. GET must never mutate.
  • Token auth in an Authorization header is not CSRF-vulnerable, because the browser does not attach it automatically. That is why ActionController::API omits 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.

Post.where("title = ?", params[:title]) # safe: bound parameter
Post.where(title: params[:title]) # safe: hash form
Post.where("title = '#{params[:title]}'") # vulnerable: interpolation
Post.order(params[:sort]) # identifiers cannot be bound
Post.where(params[:filters]) # hash keys become column names

order, pluck, select and group take identifiers, which cannot be bound — allow-list them:

SORTABLE = { "newest" => "created_at DESC", "title" => "title ASC" }.freeze
Post.order(Arel.sql(SORTABLE.fetch(params[:sort], "created_at DESC")))

Arel.sql on user-supplied input is the same vulnerability with extra steps.

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's

Scoping through the current user is the cheapest authorisation there is, and it is what prevents insecure direct object references.

Terminal window
bin/rails credentials:edit
bin/rails credentials:edit --environment production

credentials.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”.

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.

  1. How does CSRF protection work, and why does an API with bearer tokens not need it?
  2. What makes raw dangerous when ERB already escapes?
  3. Why is where(params[:filters]) injectable with no string interpolation?
  4. What is the difference between authentication and authorisation in Rails?
  5. Which cookie flag stops XSS from stealing a session?
  • skip_before_action :verify_authenticity_token. Justify it or remove it.
  • html_safe on 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_type from the client. It is an attacker-controlled string.