rails-security
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
endFilter 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 authenticationUse 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
endauthenticate_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
endAccount 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
endFail 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
endStrong 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)
endRails 8 adds expect, which raises on a malformed structure instead of returning an empty
hash:
def user_params
params.expect(user: [:email, :name])
endAttributes 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 rathe
