Rails Security
Security practices for Ruby on Rails applications (Rails 7.1+ and 8.x). Rails is secure by
default in most places; the vulnerabilities that reach production usually come from opting
out of a default rather than failing to add protection. This skill is the "how." For the
decisions about which control to reach for, see the Ruby security rules —
rules/ruby/security.md in this repository, installed as rules/ecc/ruby/security.md.
When to Activate
- Writing or reviewing authentication, sessions, or account recovery
- Adding authorization checks to controllers or views
- Handling user input, file uploads, or webhook payloads
- Configuring a Rails app for production
- Reviewing a PR that touches
config/,app/controllers/, orGemfile - Any use of
html_safe,raw,Arel.sql, or raw SQL strings
Production Configuration
# config/environments/production.rb
Rails.application.configure do
config.force_ssl = true
# Only use when all requests pass through a proxy that rejects or redirects HTTP.
config.assume_ssl = true # behind a proxy that terminates TLS
# Reject requests with unexpected Host headers.
config.hosts << "example.com"
config.hosts << /.*\.example\.com/
config.action_dispatch.cookies_same_site_protection = :lax
config.log_level = :info
end
Filter sensitive values out of logs:
# config/initializers/filter_parameter_logging.rb
Rails.application.config.filter_parameters += %i[
passw secret token _key crypt salt certificate otp ssn cvv card_number
]
Authentication
Rails 8 ships an authentication generator that produces session-based auth with password reset and metadata tracking:
bin/rails generate authentication
Use Devise when you need OAuth, MFA, confirmable, lockable, or multi-model auth. For
hand-rolled auth, has_secure_password handles bcrypt hashing:
class User < ApplicationRecord
has_secure_password
validates :email, presence: true, uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 12 }, allow_nil: true
end
authenticate_by looks up and verifies in one call, so a missing user and a wrong password
take the same time:
# Bad: the timing difference reveals whether the email exists
user = User.find_by(email: params[:email])
if user&.authenticate(params[:password])
# Good
user = User.authenticate_by(email: params[:email], password: params[:password])
Rotate the session on sign-in and on any privilege change:
class SessionsController < ApplicationController
def create
user = User.authenticate_by(email: params[:email], password: params[:password])
return render :new, status: :unprocessable_entity unless user
reset_session
session[:user_id] = user.id
redirect_to root_path
end
def destroy
reset_session
redirect_to root_path
end
end
Account recovery
Password reset tokens must expire, be single-use, and not reveal whether an account exists. Signed tokens generated by the model give you both:
class User < ApplicationRecord
generates_token_for :password_reset, expires_in: 15.minutes do
password_salt&.last(10) # invalidates the token once the password changes
end
end
user = User.find_by_token_for(:password_reset, params[:token])
Render the same response whether or not the address matched.
Authorization
Authentication is not authorization. Every action that touches a record must check that the current user may act on it.
# Bad: any signed-in user can load any invoice
@invoice = Invoice.find(params[:id])
# Good: scope through the owner
@invoice = current_user.invoices.find(params[:id])
For anything past ownership, use a policy object (Pundit, Action Policy, or CanCanCan):
class InvoicePolicy < ApplicationPolicy
def update?
user.admin? || record.user_id == user.id
end
end
class InvoicesController < ApplicationController
def update
@invoice = Invoice.find(params[:id])
authorize @invoice
# ...
end
end
Fail closed — verify that authorization ran rather than trusting each action to remember:
class ApplicationController < ActionController::Base
include Pundit::Authorization
after_action :verify_authorized, except: :index
after_action :verify_policy_scoped, only: :index
end
# Public actions have no record to authorize, so exempt them explicitly.
class SessionsController < ApplicationController
skip_after_action :verify_authorized
end
Strong Parameters and Mass Assignment
Never pass raw params to a model. Permit an explicit list:
# Bad: a crafted request can set admin
User.new(params[:user])
# Good
def user_params
params.require(:user).permit(:email, :name)
end
Rails 8 adds expect, which raises on a malformed structure instead of returning an empty
hash:
def user_params
params.expect(user: [:email, :name])
end
Attributes such as admin, role, user_id, and account_id should never appear in a
permit list driven by request data. Assign them explicitly from the session or a checked
policy.
SQL Injection
Active Record parameterizes by default. Injection appears when a string is built by hand:
# Bad
User.where("email = '#{params[:email]}'")
Order.order("#{params[:sort]} #{params[:dir]}")
# Good
User.where(email: params[:email])
User.where("email = ?", params[:email])
order, pluck, group, and select accept raw SQL and are not sanitized. Allowlist the
input rather than escaping it:
SORTABLE = { "created_at" => "created_at", "total" => "total" }.freeze
DIRECTIONS = { "asc" => "ASC", "desc" => "DESC" }.freeze
column = SORTABLE.fetch(params[:sort], "created_at")
direction = DIRECTIONS.fetch(params[:dir], "DESC")
Order.order(Arel.sql("#{column} #{direction}"))
LIKE needs its own escaping, since % and _ are wildcards:
term = User.sanitize_sql_like(params[:q])
User.where("name LIKE ?", "%#{term}%")
XSS and Output Escaping
ERB escapes interpolated values by default. Every bypass is security-sensitive:
<%# Bad: renders attacker-controlled markup %>
<%= @comment.body.html_safe %>
<%= raw @comment.body %>
<%# Good: escaped %>
<%= @comment.body %>
<%# Good: allowlisted markup when the field is genuinely rich text %>
<%= sanitize @comment.body, tags: %w[p br strong em a], attributes: %w[href] %>
html_safe does not sanitize — it marks a string as already safe and skips escaping. Only
call it on strings you constructed.
Interpolating into JavaScript needs the matching escape, not the HTML one:
<script>
const payload = <%= raw @data.to_json %>; // Bad
const payload = <%= raw json_escape(@data.to_json) %>; // Good
</script>
link_to's href accepts javascript: URLs, so validate user-supplied links:
uri = URI.parse(url) rescue nil
safe = uri.is_a?(URI::HTTP) # URI::HTTPS subclasses URI::HTTP
Set a Content Security Policy:
# config/initializers/content_security_policy.rb
Rails.application.configure do
config.content_security_policy do |policy|
policy.default_src :self
policy.script_src :self
policy.object_src :none
policy.frame_ancestors :none
end
end
CSRF
Rails enables CSRF protection for new apps. Keep it on, and do not exempt actions to make a client work:
# Bad: disables protection for every action in the controller
skip_before_action :verify_authenticity_token
If an endpoint genuinely cannot carry the token — a third-party webhook, say — authenticate it another way (signature verification) and scope the exemption to that action alone.
API-only controllers inheriting from ActionController::API have no cookie session, so CSRF
does not apply; token or session-cookie APIs still need it.
File Uploads
The content_type a client sends is attacker-controlled, and blob.content_type is not a
substitute for it. Active Storage derives that column through Marcel::MimeType.for, which
treats the client's declared type as one candidate alongside magic-byte detection and keeps
it when the bytes match nothing known — so opaque bytes declared image/png are stored as
image/png with identified? true. Inspect the stored bytes yourself:
module Uploads
Rejected = Class.new(StandardError)
MAGIC = {
"application/pdf" => "%PDF-".b,
"image/png" => "\x89PNG\r\n\x1a\n".b,
"image/jpeg" => "\xFF\xD8\xFF".b
}.freeze
ALLOWED_EXTENSIONS = %w[.pdf .png .jpg .jpeg].freeze
MAX_BYTES = 10.megabytes
def self.verified!(blob)
# Fail closed: an object that is missing or still pending cannot be inspected.
raise Rejected, "could not be verified" unless blob.service.exist?(blob.key)
raise Rejected, "is too large" if blob.byte_size > MAX_BYTES
extension = File.extname(blob.filename.to_s).downcase
raise Rejected, "extension not allowed" unless ALLOWED_EXTENSIONS.include?(extension)
head = blob.service.download_chunk(blob.key, 0...8)
raise Rejected, "type not allowed" unless MAGIC.any? { |_mime, magic| head.start_with?(magic) }
blob
end
end
The check reads from storage, so it has to run where the bytes already exist. A form upload is not yet in storage when model validations run — Active Storage uploads on save — so upload explicitly first, and attach only what passed:
# Form upload
blob = ActiveStorage::Blob.create_and_upload!(io: params[:file], filename: params[:file].original_filename)
document.file.attach(Uploads.verified!(blob))
# Direct upload: the client already stored the object, so verify before the record
# points at it.
document.file.attach(Uploads.verified!(ActiveStorage::Blob.find_signed!(params[:file])))
Attach to a private service — a public bucket makes every upload world-readable regardless of the checks above.
has_one_attached :file, service: :private_documents
rails_blob_url and url_for(attachment) are stable references that never expire; they
redirect to a short-lived service URL, so anyone holding one keeps access. Serve
user-scoped files from your own controller that authorizes each request, with
config.active_storage.draw_routes = false, which removes every default Active Storage
route; apps using direct uploads need a replacement route:
get "documents/:id/file", to: "document_files#show", as: :document_file
# Rails' direct-upload endpoint has no authentication of its own. This example uses a
# hand-rolled session sign-in; see Devise or the Rails 8 generator for their equivalents.
constraints ->(req) { req.session[:user_id].present? } do
post "uploads", to: "active_storage/direct_uploads#create", as: :rails_direct_uploads
end
class DocumentPolicy < ApplicationPolicy
def show?
record.user_id == user.id
end
end
class DocumentFilesController < ApplicationController
def show
document = current_user.documents.find(params[:id])
authorize document, :show?
redirect_to document.file.blob.url(expires_in: 5.minutes), allow_other_host: true
end
end
Never interpolate a user-supplied path into send_file:
# Bad: path traversal
send_file Rails.root.join("storage", params[:name])
API Security
Rate-limit authentication and other abusable endpoints. Action Controller ships
rate_limit from Rails 7.2; use rack-attack on 7.1 or for app-wide throttling:
class SessionsController < ApplicationController
rate_limit to: 10, within: 3.minutes, only: :create
end
Verify webhook signatures with a constant-time comparison:
class WebhooksController < ApplicationController
skip_before_action :verify_authenticity_token, only: :create
def create
expected = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("WEBHOOK_SECRET"), request.raw_post)
given = request.headers["X-Signature"].to_s
unless ActiveSupport::SecurityUtils.secure_compare(expected, given)
return head :unauthorized
end
event_id = JSON.parse(request.raw_post).fetch("id")
delivery = WebhookDelivery.create_or_find_by!(provider: "billing", delivery_id: event_id)
return head :ok if delivery.processed_at?
ProcessWebhookJob.perform_later(delivery.id, request.raw_post)
head :ok
end
end
add_index :webhook_deliveries, %i[provider delivery_id], unique: true
The job marks processed_at when it finishes. Jobs retry, so perform must be
idempotent for the same reason. Requires a stable id in the signed body.
Keep CORS narrow — never reflect an arbitrary origin alongside credentials:
# Bad
origins "*"
# Good
origins "https://app.example.com"
Serialize responses explicitly so new columns do not leak:
# Bad: ships every column, including ones added later
render json: @user
# Good
render json: @user.as_json(only: %i[id name created_at])
Secrets and Credentials
Secrets belong in Rails credentials, environment variables, or a secret manager:
bin/rails credentials:edit --environment production
config/credentials/production.key must stay out of version control. Read secrets through
Rails.application.credentials or ENV.fetch — ENV[...] returns nil and fails silently
when a variable is missing:
# Bad
ENV["STRIPE_SECRET"]
# Good
Rails.application.credentials.dig(:stripe, :secret)
ENV.fetch("STRIPE_SECRET")
If a key is ever committed, rotate it. Removing the commit does not un-expose it.
Untrusted Boundaries
Controller params are not the only entry point. Job arguments, webhook payloads, Action Cable messages, and Turbo Stream targets all carry outside data:
- Pass record IDs to jobs and re-scope inside
perform; a queued job runs without the original request's session. - Authorize in
ApplicationCable::Connectionand in each channel'ssubscribed. - Never build a Turbo Stream target from user input.
class ExportJob < ApplicationJob
def perform(user_id, invoice_id)
user = User.find(user_id)
invoice = user.invoices.find(invoice_id) # scoped, not Invoice.find
# ...
end
end
Dependency Scanning
Run these when the lockfile changes, and in CI:
bundle exec bundle-audit check --update
bundle exec brakeman --no-progress
Brakeman flags the patterns above statically. Treat new warnings as blocking, and record
deliberate exceptions in config/brakeman.ignore with a reason rather than lowering the
confidence threshold.
Verification Checklist
-
force_sslandconfig.hostsset in production - Sensitive parameters filtered from logs
- Sessions rotated on sign-in and privilege change
- Every record lookup scoped to the current user or checked by a policy
- No permit list contains a role, ownership, or account column
- No raw SQL string interpolation;
orderandpluckinputs allowlisted - Every
html_safeandrawreviewed - CSRF exemptions scoped to specific actions with another auth mechanism
- Uploads validated against stored bytes, not
blob.content_type, and fail closed when the object is unavailable - Auth endpoints rate-limited; webhook signatures compared in constant time
- No secrets in version control; master key excluded
-
bundle-auditandbrakemanclean
Related Skills
rails-patterns— the architectural patterns these controls sit insidesecurity-review— secure-by-default review patterns across languages- Ruby security rules (
rules/ruby/security.md, installed asrules/ecc/ruby/security.md) — the decisions and when-to-use guidance this skill implements
