Logins, permissions and security in Rails: what the framework does for you, and what it never can
TL;DR
Difficulty: Intermediate
Rails guards the doors: CSRF tokens, HTML escaping, parameterised queries, strong parameters, an encrypted session cookie and HTTPS in production are on by default in Rails 7.1.
- Every hole is a named escape hatch (html_safe, raw, permit!, interpolated SQL, allow_other_host), so a search plus Brakeman and bundler audit reviews the doors.
- The rooms are yours: broken access control is first in the OWASP Top 10. Find every record through a scope, then check the action, so a guessed id is a 404.
- Count your account flows. Five or fewer: build on has_secure_password, authenticate_by and generates_token_for. More: Devise or Rodauth.
- Customers often need no password, just a signed link. Anyone who sees money needs a second factor and a lockout per account, because throttles only slow guessing down.
Rails does a remarkable amount for your security before you write a line, and there is one category of protection it can never do for you, which is the one behind most breaches. Here is where the line runs, built on a Limerick bike workshop chain's application with logins, a second factor, policies and the tests that prove them.
The question behind this article
"How do I handle logins, permissions and security in Rails properly, and what does Rails already do for me?" It is the question every team asks once the first screens work and real people are about to use them. It usually comes with a worry attached: security feels like a field of its own, full of acronyms, where one mistake ends up in the news.
The honest answer has two halves. Rails does a remarkable amount for you without being asked, and it says so in its own security guide1. And there is one whole category of protection that no framework can ever do for you, which happens to be the category behind most real breaches. This article draws the line between the two halves, then builds both on one example application, with code that runs on Rails 7.1 and tests that prove it.
If you have not read it yet, how a Rails application is structured explains the folders and the request cycle this article relies on.
The example is the one this whole series uses, and it is made up. Freewheel Cycles is a chain of six bicycle repair workshops in Limerick (freewheelcycles.example), founded by Niamh. Its two developers, Aisling and Cian, are replacing spreadsheets and a rented booking widget with their own application, and they chose Rails after building a spike in both frameworks. There are 38 mechanics, about 1,150 repair bookings a week and 9,000 active customers. The application has job cards with before and after photos, a live workshop board, parts stock, invoices with VAT and a back office for managers. That is a lot of data with different owners, which makes it a good place to learn security.
Every request to an application like this has to answer three questions, in this order:
- Who are you? That is authentication: proving identity, usually with a password, a link or a second factor.
- Which records exist for you? That is scoping: the set of rows this person may even know about.
- What may you do with this one? That is authorisation: may this role read, change or delete this record.
Keep those three questions in mind. The rest of the article is about answering each of them properly.
Rails guards the doors, you guard the rooms
Here is the model I use to explain the split, and I have not seen it put this way in the official guides.
Think of an application as a building. The doors are where data crosses a boundary: a form arrives, a query goes to the database, HTML goes to the browser, a cookie goes back and forth. Attacks at the doors are generic. A forged form looks the same in a bike workshop and in a bank. So a framework can guard the doors, and Rails does: it adds a token to every form, escapes every value it writes into HTML, passes every value to the database separately from the query, and encrypts the session cookie.
The rooms are your data and who owns it. Job card 4812 belongs to the Castletroy workshop. Invoice 311 belongs to a customer called Ms Byrne. No framework can know that, because it is not a property of HTTP or SQL. It is a property of your business. So the rooms are yours to guard, and nothing in Rails guards them for you.
The evidence says the rooms are where it goes wrong. In the 2021 edition of the OWASP Top 10, the most widely used list of web application security risks, "Broken Access Control" moved up to first place, and OWASP reports that 94% of applications tested showed some form of it2. Its first piece of prevention advice is to deny by default, and its second is that access controls should enforce record ownership2.
My view: in a Rails application built with current defaults, your time on security is best spent in the rooms. The doors deserve a check that nobody has propped them open, which I come to in a moment, but they do not deserve your anxiety.
Example: two attacks on the Freewheel Cycles workshop board
Two things could go wrong on the day the board goes live.
The door attack. A stranger builds a page on another website with a hidden form that posts to freewheelcycles.example/job_cards/4812 and sets the status to "collected". If a logged in manager visits that page, the browser sends the form along with the manager's cookie. This is called cross site request forgery (CSRF). In a new Rails 7.1 application it fails without Aisling writing a line: the form lacks the secret token that Rails puts in every page it renders, so Rails rejects the request1.
The room attack. A mechanic at the Castletroy workshop is curious about how busy the Dooradoyle workshop is. He opens his own job card, /job_cards/4812, and changes the number in the address bar to 4813. Everything about this request is valid: he is logged in, the token is correct, the cookie is genuine. If the controller says JobCard.find(params[:id]), Rails will happily show him the other workshop's card, with the customer's name and phone number on it. This is called an insecure direct object reference (IDOR), and OWASP lists it explicitly under broken access control2.
Rails stopped the first attack for free. Only Aisling and Cian can stop the second, because only they know that job cards belong to workshops.
What Rails already does for you
Here is the list of the doors Rails guards in a new Rails 7.1 application, taken from the security guide, the configuration guide and the 7.1 change log. The middle column is the part most articles leave out: whether you get it by default or have to switch it on.
| Protection | Guards against | On by default in a new Rails 7.1 app? | How it gets switched off |
|---|---|---|---|
| Authenticity token on every form and Turbo request | Cross site request forgery (CSRF) | Yes, since the 5.2 defaults3 | skip_forgery_protection in a controller |
| Values sent to the database apart from the SQL | SQL injection | Yes, when you use hash conditions or ? placeholders1 | Building SQL with string interpolation |
| Automatic HTML escaping in ERB templates | Cross site scripting (XSS) | Yes4 | html_safe, raw, <%== |
| Strong parameters | Mass assignment of fields like role | Yes5 | permit! |
| Encrypted, signed session cookie | Reading or changing the session | Yes1 | Writing secrets into plain cookies[...] |
SameSite=Lax on cookies | Cookies riding along on cross site requests | Yes, since the 6.1 defaults3 | Configuration |
| HTTPS only, with HTTP Strict Transport Security (HSTS) and secure cookies | Eavesdropping, downgrade to plain HTTP | Yes in production, new in Rails 7.16 | config.force_ssl = false |
| Redirects to other hosts raise an error | Open redirects used for phishing | Yes, since the 7.0 defaults3 | allow_other_host: true |
| Parameter filtering in logs | Passwords and tokens in log files | Yes, for names containing passw, secret, token, _key, crypt, salt, certificate, otp, ssn | Removing entries from the list |
| Encrypted credentials | Secret keys in the Git repository | Yes1 | Committing config/master.key |
| Host authorisation | DNS rebinding | In development only. Production needs config.hosts3 | |
| Content Security Policy (CSP) | Injected scripts running at all | No. The initialiser is generated but commented out | |
| Active Record encryption | Readable data in a leaked database or backup | No. You opt in per attribute7 |
Two details in that table matter more than they look.
First, several protections arrive through config.load_defaults, the line in config/application.rb that says which version's defaults the application uses. An application born on Rails 5 and upgraded to 7.1 keeps its old defaults until someone moves that line forward. Such an application can run Rails 7.1 and still allow open redirects.
Second, two of the strongest protections, a Content Security Policy and encryption of sensitive columns, are opt in. They are worth turning on, and I show both below.
Example: one booking form, followed through the defaults
A customer books a service for her bike on Freewheel's site. Here is what Rails does along the way, without any code from Aisling or Cian:
- The booking page is rendered with a hidden
authenticity_tokenfield, and the layout'scsrf_meta_tagsputs the same token in the page head for Turbo to send as a header1. - The customer types
<script>alert(1)</script>into the notes box on the booking form, because some people do. The booking is saved with that text. - The workshop board later shows the note in
<%= booking.notes %>. ERB escapes it, so the mechanics see the literal characters instead of a running script. - The controller saves the booking with
booking_params, which permitsbike_id,starts_atandnotes. A crafted request that also sendsbooking[price_pence]=0has that field dropped, because it is not on the list. - The search box on the booking page looks up the customer's bikes with
Bike.where(frame_number: params[:frame]). The frame number goes to the database as a separate value, so a value like' OR 1=1 --is just a frame number that matches nothing. - All of this travels over HTTPS, because the generated
config/environments/production.rbin Rails 7.1 containsconfig.force_ssl = true6.
Six defences, zero lines of security code. That is the part of the answer that should reassure you.
Every security hole in Rails is a named escape hatch
Because Rails guards its doors by default, a door can only be opened from the inside, on purpose, with a method that has a name. That gives you something unusual in security: a review you can do with a search.
This is the rule of thumb I would give any Rails team. Do not audit everything. Audit the escape hatches. Each one is legitimate somewhere, which is why it exists. Each one also turns a default protection off for that line.
| Escape hatch | What it switches off | What to write instead |
|---|---|---|
where("name = '#{params[:name]}'"), order(params[:sort]), find_by_sql with interpolation | Parameterised queries | where(name: value), where("starts_at > ?", time), an allow list of sortable columns |
html_safe, raw(...), <%== | HTML escaping | Plain <%= %>, simple_format, or sanitize with an allow list of tags1 |
params.require(:user).permit! | Strong parameters | Name every field. Never let role or workshop_id in from a form a user controls |
redirect_to params[:return_to], allow_other_host: true | Open redirect protection | url_from(params[:return_to]), which returns nil for another host, with root_path as the fallback8 |
skip_forgery_protection | CSRF tokens | Keep it on for anything a browser with cookies talks to |
Model.find(params[:id]) in a controller for logged in users | Nothing, because nothing protected it | Find through a scope, as shown in the authorisation section |
constantize or send on a value from params | Nothing: it lets a request choose which code runs | An explicit case statement or a hash lookup |
The Rails API is blunt about one of these. The documentation for raw says it "outputs without escaping a string" and adds that this is not recommended if the data comes from user input4.
Example: Freewheel's ten minute review before each release
Cian adds one script to the repository and runs it before every release:
#!/usr/bin/env bash
# bin/escape_hatches: list every line that switches a Rails default off.
# Each hit needs a reason. No hit is a failure on its own.
git grep -nE 'html_safe|raw\(|<%==|permit!|allow_other_host|skip_forgery_protection|find_by_sql|constantize' -- app lib
git grep -nE '\.(where|order|group|having|pluck)\("[^"]*#\{' -- app lib
git grep -nE '[A-Z][A-Za-z]+\.find\(params' -- app/controllers
The first run finds one line in the job card view:
<%# app/views/job_cards/_job_card.html.erb, before %>
<p><%= raw job_card.notes.gsub("\n", "<br>") %></p>
Someone wanted line breaks in the mechanics' notes and reached for raw. But the notes include text that customers typed into the booking form. Aisling replaces it with simple_format, which turns line breaks into paragraphs and sanitises the text in the same step:
<%# app/views/job_cards/_job_card.html.erb, after %>
<%= simple_format job_card.notes %>
The third search finds JobCard.find(params[:id]) in two controller actions. Those are the room problem from the start of the article, and they are fixed properly in the authorisation section below. The script takes seconds. Thinking about the hits takes ten minutes. That is a security review a small team actually does.
Authentication: four ways in, as of Rails 7.1
Authentication answers "who are you?". In March 2024 a Rails team has four serious options, and they are not mutually exclusive.
Build it on Rails' own primitives. has_secure_password stores a bcrypt hash of the password in a password_digest column, adds a validation that the password is present and no longer than 72 bytes, and gives you authenticate9. Rails 7.1 added three pieces that used to need a gem or careful hand work. authenticate_by finds a user and checks the password in one call, and it digests the password even when no user matches, which the documentation says helps against timing based enumeration attacks, where an attacker learns which email addresses exist from how long the answer takes10. generates_token_for makes signed, expiring tokens for links such as password resets11. And password_challenge checks the current password before a change is accepted12.
Devise. The most widely used authentication gem for Rails, version 4.9.3 at the time of writing. It describes itself as "a flexible authentication solution for Rails based on Warden" and comes as ten modules, from database authentication and password recovery to confirmation, lockout and timeouts13. Its README is admirably honest about one thing: if you are building your first Rails application, it recommends that you do not use Devise13, because so much happens out of sight.
Rodauth, through rodauth rails. Rodauth is an authentication framework by Jeremy Evans, and the rodauth-rails gem (1.13 at the time of writing) integrates it with Rails14. Its strength is breadth: multifactor authentication with time based codes, SMS codes, recovery codes and passkeys, password complexity and reuse rules, session expiry, audit logging and a JSON API, all configured in one place14. It talks to the database through a library called Sequel, reusing the Active Record connection14.
OmniAuth, for single sign on (SSO). OmniAuth lets people log in with an account they already have elsewhere, such as Google Workspace or Microsoft. It sits next to one of the other three. Since OmniAuth 2.0, the login request must be a POST, to close a CSRF problem in the old GET flow, and the project documents how to wire it to Rails' own token15.
| Rails 7.1 primitives | Devise | Rodauth | OmniAuth | |
|---|---|---|---|---|
| What it is | Methods in Rails itself | A gem of ten modules | A framework with a Rails integration | Login through another provider |
| Code you own | All of it, typically a few hundred lines | Configuration and views | Configuration | Callback handling |
| Second factor | Build it, for example with rotp | Separate gems | Built in | The provider's own |
| Best when | Few flows, all understood | Standard sign up flows, many users | Many flows, strict security needs | Users already have company accounts |
The common warning in the Ruby community is "never roll your own authentication". It is good advice about cryptography: never invent your own password hashing or token signing. It is weaker advice about the flows around them, now that Rails ships the cryptographic parts. The useful question is not "gem or no gem" but how many account flows you need.
My view: count the flows. Sign in, sign out, password reset, password change, second factor, email confirmation, self sign up, lockout, recovery codes, remember me, account deletion. If each kind of user needs five or fewer of those, and nobody signs up on their own, Rails 7.1's primitives give you code you fully understand at little cost. Beyond that, Devise or Rodauth has already written, tested and patched the flows you are about to write, and Rodauth covers more of the security heavy ones out of the box.
Example: Freewheel counts its flows
Aisling and Cian list who logs in and what each person needs.
- Staff. 38 mechanics, one manager per workshop (six, an assumption of this example) and Niamh as owner: 45 logins. Nobody signs up: a manager creates the accounts for their workshop. They need sign in, sign out, password reset and password change. Managers and Niamh see invoices and customer data across a workshop, so they also need a second factor. That is five flows.
- Customers. 9,000 active customers who bring a bike in a few times a year. Asking each of them to create and remember a password would add 9,000 password hashes to protect and a support queue of forgotten passwords. They need one flow: a link by email that opens their own bookings.
Six flows across two kinds of user, no self sign up, no SSO: the team has Google Workspace accounts, but the mechanics do not. So Freewheel builds on the Rails 7.1 primitives. Had Niamh wanted customers to manage accounts with saved bikes, payment cards and loyalty points, the count would pass ten and Rodauth would be my recommendation.
The staff login, built on has_secure_password
Here is the whole staff login. It needs the bcrypt gem, which the generated Gemfile includes as a commented line, ready to be switched on9.
Example: Freewheel's users table and model
# db/migrate/20240312090000_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.1]
def change
create_table :users do |t|
t.string :email_address, null: false
t.string :password_digest, null: false # bcrypt hash, never the password
t.string :role, null: false, default: "mechanic"
t.references :workshop, foreign_key: true # empty only for the owner
t.text :otp_secret # encrypted, see the second factor section
t.integer :last_otp_at # stops a code being used twice
t.integer :failed_otp_attempts, null: false, default: 0
t.datetime :deactivated_at # set when someone leaves
t.timestamps
end
add_index :users, :email_address, unique: true
end
end
# app/models/user.rb
class User < ApplicationRecord
has_secure_password
belongs_to :workshop, optional: true
enum :role, { mechanic: "mechanic", manager: "manager", owner: "owner" }
encrypts :otp_secret
# Store and look up addresses the same way, whatever people type
normalizes :email_address, with: ->(email) { email.strip.downcase }
validates :email_address, presence: true, uniqueness: true
validates :password, length: { minimum: 12 }, allow_nil: true
validates :workshop, presence: true, unless: :owner?
scope :active, -> { where(deactivated_at: nil) }
# A reset link dies after 15 minutes, or as soon as the password changes
generates_token_for :password_reset, expires_in: 15.minutes do
password_salt.last(10)
end
def second_factor_required?
manager? || owner?
end
end
A few decisions in there deserve a sentence each:
normalizes(new in 7.1) applies to queries as well, sofind_by(email_address: " Niamh@Freewheelcycles.example ")finds the right row12.- The minimum of 12 characters is Freewheel's choice. NIST's guidance for passwords sets at least 8, asks verifiers to accept at least 64, and advises against forced composition rules and periodic changes16. Rails caps the password at 72 bytes, a limit of bcrypt9.
- The block on
generates_token_forreturns part of the password salt. The documentation's own example does exactly this: when the password changes, the salt changes, and every reset link sent before stops working11. A reset link can therefore be used once.
Example: the sign in controller
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :user
end
# app/controllers/concerns/authentication.rb
module Authentication
extend ActiveSupport::Concern
included do
helper_method :current_user
end
private
# Loaded fresh on every request, so a deactivated user is out at once
def current_user
return unless session[:user_id]
Current.user ||= User.active.find_by(id: session[:user_id])
end
def require_staff_login
redirect_to new_session_path unless current_user
end
def start_session_for(user)
reset_session # a new session id after login, against session fixation
session[:user_id] = user.id
end
end
# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.active.authenticate_by(
email_address: params[:email_address].to_s,
password: params[:password].to_s
)
if user.nil?
# The same message for a wrong address and a wrong password
redirect_to new_session_path, alert: "That email and password do not match."
elsif user.second_factor_required?
reset_session
session[:pending_user_id] = user.id
session[:pending_since] = Time.current.to_i
redirect_to new_second_factor_path
else
start_session_for(user)
redirect_to root_path
end
end
def destroy
reset_session
redirect_to new_session_path, notice: "You are signed out."
end
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include Authentication
end
# config/routes.rb (the parts this article uses)
resource :session, only: %i[new create destroy]
resource :second_factor, only: %i[new create]
resources :password_resets, only: %i[new create edit update], param: :token
resources :job_cards, only: %i[index show update]
resources :invoices, only: %i[index show]
get "my/link/:token", to: "customer_links#show", as: :customer_link
namespace :my do
resources :bookings, only: %i[index show]
end
The details that make this safe:
reset_sessionbefore storing the user id issues a new session identifier, which is the security guide's main defence against session fixation1, where an attacker plants a known session id on a victim and waits for them to log in.- The error message never says which part was wrong, so the form does not tell an attacker which addresses belong to staff. The security guide recommends the same generic messages, including on the "forgot password" page1.
.to_son both parameters means a crafted request that sends a nested hash instead of a string becomes a harmless string.current_userreads the database on every request. When a mechanic leaves, a manager setsdeactivated_at, and the next click from that person's browser lands on the sign in page. A login that cannot be switched off immediately is a common gap in hand built authentication, and this one line closes it.
Example: a password reset that cannot be replayed
# app/controllers/password_resets_controller.rb
class PasswordResetsController < ApplicationController
def new
end
def create
if (user = User.active.find_by(email_address: params[:email_address].to_s))
StaffMailer.with(user: user).password_reset.deliver_later
end
# Same answer either way, so the form reveals nothing
redirect_to new_session_path, notice: "If that address belongs to a staff login, a link is on its way."
end
def edit
@user = User.find_by_token_for(:password_reset, params[:token])
redirect_to new_password_reset_path, alert: "That link has expired. Ask for a new one." unless @user
end
def update
@user = User.find_by_token_for(:password_reset, params[:token])
return redirect_to(new_password_reset_path, alert: "That link has expired. Ask for a new one.") unless @user
if @user.update(params.require(:user).permit(:password, :password_confirmation))
redirect_to new_session_path, notice: "Password changed. Sign in with the new one."
else
render :edit, status: :unprocessable_entity
end
end
end
The mailer builds the link with edit_password_reset_url(@user.generate_token_for(:password_reset)). The email goes out through a background job, as set up in the chapter on jobs, email and files. find_by_token_for returns nil for an expired, tampered or already used token11, so the controller needs no token table, no cleanup job and no used_at column.
Customers do not need a password
This is the decision I would most like more teams to consider. Every password you store is a liability: a hash that can leak, an account that can be guessed, a reset flow that can be abused. Customers reuse passwords across sites, so a leaked list from somewhere else becomes a set of keys to your application.
The data protection principle of data minimisation says you should process only the personal data you need17. A bike workshop's customer needs to see their bookings, their job card photos and their invoices a few times a year. They do not need a password for that. A signed link sent to the email address they booked with proves the same thing a password would: that they control that inbox.
generates_token_for makes this a few lines. One caution from the documentation: the value the block returns is embedded in the token as readable JSON, so it must not be sensitive11. That rules out the email address. A counter is ideal.
Example: Freewheel's "your bookings" link
# db/migrate/20240312091000_add_link_generation_to_customers.rb
class AddLinkGenerationToCustomers < ActiveRecord::Migration[7.1]
def change
add_column :customers, :link_generation, :integer, null: false, default: 0
end
end
# app/models/customer.rb (the relevant part)
class Customer < ApplicationRecord
has_many :bookings
# Valid for seven days. Raising link_generation by one kills every link sent so far.
generates_token_for :bookings_link, expires_in: 7.days do
link_generation
end
end
# app/controllers/customer_links_controller.rb
class CustomerLinksController < ApplicationController
def show
customer = Customer.find_by_token_for(:bookings_link, params[:token])
if customer
reset_session
session[:customer_id] = customer.id
redirect_to my_bookings_path # the token leaves the address bar at once
else
redirect_to root_path, alert: "That link has expired. You can ask for a new one on the booking page."
end
end
end
# app/controllers/my/bookings_controller.rb
module My
class BookingsController < ApplicationController
before_action :require_customer
def index
@bookings = current_customer.bookings.order(starts_at: :desc)
end
def show
# Found through the customer's own bookings: someone else's id is simply not there
@booking = current_customer.bookings.find(params[:id])
end
private
def current_customer
@current_customer ||= Customer.find_by(id: session[:customer_id])
end
def require_customer
redirect_to root_path unless current_customer
end
end
end
Three small things make the link safe. The token is in a parameter called token, which the default log filter already masks, so it never sits in a log file. The controller redirects straight away, so the token does not linger in the address bar or leak to another site in a Referer header. And current_customer.bookings.find is authorisation done with nothing but an association, which is the simplest and often the best kind.
The result: 9,000 customers, zero customer passwords. The "ready for collection" email from the workshop can carry the same link, so the customer sees the after photos with one tap.
A second factor for anyone who can see money
A password alone fails when it is guessed, phished or reused from another breach. A second factor means a stolen password is not enough. The most common form in staff applications is the time based one time password (TOTP), the six digit code that an authenticator app shows and changes every 30 seconds. It is defined in an open standard, RFC 623818, and the rotp gem implements it for Ruby19.
Freewheel requires it for managers and Niamh, because they see invoices and the customer list across a workshop. Mechanics, who see job cards in their own workshop, sign in with a password alone. That is a judgement about risk, and the roles table further down makes it visible.
Example: enrolling a manager and checking the code
The secret that both the server and the authenticator app know must be stored so that a leaked database does not leak it. Active Record encryption does that with one line, encrypts :otp_secret, after running bin/rails db:encryption:init and adding the keys it prints to the credentials7. Without the keys, a copy of the database shows only ciphertext.
# Enrolment, for example in a manager's settings page
user.update!(otp_secret: ROTP::Base32.random)
totp = ROTP::TOTP.new(user.otp_secret, issuer: "Freewheel Cycles")
@provisioning_uri = totp.provisioning_uri(user.email_address) # shown as a QR code
# app/controllers/second_factors_controller.rb
class SecondFactorsController < ApplicationController
MAX_FAILED_CODES = 10
def new
redirect_to new_session_path unless pending_user
end
def create
user = pending_user
return redirect_to(new_session_path) unless user
totp = ROTP::TOTP.new(user.otp_secret, issuer: "Freewheel Cycles")
used_at = totp.verify(params[:code].to_s, drift_behind: 15, after: user.last_otp_at)
if used_at
user.update!(last_otp_at: used_at, failed_otp_attempts: 0)
start_session_for(user)
redirect_to root_path
else
user.increment!(:failed_otp_attempts)
redirect_to new_second_factor_path, alert: "That code did not work. Try the newest one in your app."
end
end
private
# The password step is valid for five minutes, and ten wrong codes lock the second step
def pending_user
return unless session[:pending_user_id]
return if session[:pending_since].to_i < 5.minutes.ago.to_i
user = User.active.find_by(id: session[:pending_user_id])
user if user && user.failed_otp_attempts < MAX_FAILED_CODES
end
end
after: user.last_otp_at makes verify refuse a code that was already used, so a code read over someone's shoulder cannot be replayed19. drift_behind: 15 accepts a code that changed in the last 15 seconds, which forgives a slow thumb. A locked account is unlocked by Niamh, who resets the counter after a phone call. Why ten wrong codes and not unlimited ones is a question of arithmetic, and it comes next.
Rate limits slow guessing down, only lockouts stop it
Rails 7.1 has no built in rate limiting. The established answer at the time of writing is Rack::Attack, a middleware that counts requests in the Rails cache and answers with status 429 when a limit is passed20. It is one gem and one initialiser.
Example: the limits Freewheel sets
# config/initializers/rack_attack.rb
class Rack::Attack
# Password guesses from one address: 5 a minute
throttle("logins/ip", limit: 5, period: 1.minute) do |req|
req.ip if req.path == "/session" && req.post?
end
# Guesses at one account from many addresses: 10 an hour
throttle("logins/email", limit: 10, period: 1.hour) do |req|
if req.path == "/session" && req.post?
req.params["email_address"].to_s.strip.downcase.presence
end
end
# Second factor codes from one address: 5 every 5 minutes
throttle("second_factor/ip", limit: 5, period: 5.minutes) do |req|
req.ip if req.path == "/second_factor" && req.post?
end
end
Two practical notes. The counts live in Rails.cache, and the README recommends a separate store such as Redis20: with more than one server, every server must see the same counts, otherwise each one allows its own five. And behind a load balancer, check that req.ip is the visitor's address and not the balancer's, or one throttle will lock out every customer at once.
The arithmetic of guessing a code
Throttles feel like protection. The arithmetic shows how much they actually buy. Suppose an attacker already has a manager's password, from a phishing email, and now guesses six digit codes. The chance that at least one of guesses is right is
where is the probability of at least one correct guess in attempts, is the probability that a single guess is correct, and is the number of guesses the attacker gets. With one valid code out of a million possible codes, . (The 15 second drift window can make two codes valid for a moment, which at worst doubles . The conclusion does not change.) Foundations: probability
Work it through with Freewheel's code throttle of 5 attempts every 5 minutes from one address:
- Attempts per day from one address: .
- One day: .
- Thirty days: , so .
- One year: , so .
- A hundred addresses for one day, which a botnet rents without much bother: , so .
- With Freewheel's lockout after 10 wrong codes on the account, whatever the address: , so , after which the attempt needs Niamh on the phone.
The lesson is the heading of this section. A throttle per address slows an attacker in proportion to how many addresses they control, and over enough time the probability creeps up towards certainty. A limit per account, with a lockout that needs a human to lift it, caps the number of guesses no matter how many machines the attacker has. NIST's guidance requires exactly this kind of per account cap, at no more than 100 consecutive failures16. Freewheel picks 10, because 45 staff can phone Niamh.
Authorisation: scope first, check second
Now the rooms. Authorisation in Rails is usually done with one of three things.
- Plain methods and associations.
current_customer.bookings.find(id)is authorisation. So is a method likeuser.can_issue_invoices?. For one or two kinds of user, this is often all you need, and you saw it in the customer area above. - Pundit. A small gem (2.3.1 at the time of writing) built on plain Ruby classes: one policy class per model with a method per action, such as
update?, and a nestedScopeclass whoseresolvemethod returns the records a user may see21. Controllers callauthorizeandpolicy_scope. It also offersverify_authorizedandverify_policy_scoped, checks that raise an error when an action forgot to authorise, which its README describes as a development aid rather than a security mechanism21. - Action Policy. A newer gem from Evil Martians (0.6.8 at the time of writing) with a similar policy per model idea and more built in: caching of checks within a request, reasons for a failure, translated error messages and test matchers for both RSpec and Minitest22.
Pundit and Action Policy are both sound choices. Pundit is smaller and easier to read in an afternoon. Action Policy pays off when rules get numerous and you want to explain refusals to users.
Here is the original rule I care about most, and the one that fixes the room attack from the start of the article. Scope first, check second. A permission check answers "may this user do this to that record?". A scope answers "which records exist for this user at all?". If you only check, you must remember to check in every action, and the day someone forgets, the record is shown. If you always find records through the scope, a forgotten check still cannot reach another workshop's data, because the record is never loaded. The guessed id becomes a "not found" by construction, which is exactly OWASP's "deny by default"2.
In code that means one habit: in a controller for logged in users, never JobCard.find(params[:id]), always policy_scope(JobCard).find(params[:id]). Cian's escape hatch script from earlier searches for the first form, so the habit is checked on every release.
Example: Freewheel's roles and rights
Before writing a policy, Aisling writes the table and Niamh signs it off. This table is the specification. The policies are its translation into code, and the tests prove the translation.
| What | Customer (by link) | Mechanic | Workshop manager | Owner (Niamh) |
|---|---|---|---|---|
| Book a repair | Yes, no login needed | Yes, walk ins at own workshop | Own workshop | All workshops |
| See job cards | Own bikes only | Own workshop | Own workshop | All workshops |
| Move a card on the board | No | Own workshop | Own workshop | All workshops |
| Before and after photos | See own | Add, own workshop | Add, own workshop | All workshops |
| Parts stock | No | See and record usage, own workshop | Edit and reorder, own workshop | All workshops |
| Invoices with VAT | Own invoices | No | Own workshop | All workshops |
| Reports | No | No | Own workshop | All workshops |
| Staff logins | No | No | Mechanics at own workshop | Everyone |
| Second factor | Not needed (link only) | No | Required | Required |
Example: the policies
In this example, Booking and Invoice each carry a workshop_id, and a JobCard belongs to a Booking.
# app/policies/application_policy.rb
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
# Deny by default: every permission is granted explicitly in a subclass
def index? = false
def show? = false
def update? = false
def destroy? = false
class Scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
raise NotImplementedError, "#{self.class} must define resolve"
end
private
attr_reader :user, :scope
end
end
# app/policies/job_card_policy.rb
class JobCardPolicy < ApplicationPolicy
def index? = true # the scope decides what is listed
def show? = true # the record already came through the scope
def update? = true # every staff role moves cards and adds photos
def destroy? = user.manager? || user.owner?
class Scope < Scope
def resolve
return scope.all if user.owner?
scope.joins(:booking).where(bookings: { workshop_id: user.workshop_id })
end
end
end
# app/policies/invoice_policy.rb
class InvoicePolicy < ApplicationPolicy
def index? = user.manager? || user.owner?
def show? = index?
def update? = false # Freewheel's rule: an issued invoice is corrected, never edited
class Scope < Scope
def resolve
return scope.none if user.mechanic?
return scope.all if user.owner?
scope.where(workshop_id: user.workshop_id)
end
end
end
Notice that JobCardPolicy#show? simply returns true. That is not careless: the record can only reach show? through the scope, so the workshop rule lives in exactly one place. The policy methods carry the rules that differ by role, such as who may delete.
Example: the staff controllers
# app/controllers/staff_controller.rb
class StaffController < ApplicationController
include Pundit::Authorization
before_action :require_staff_login
after_action :verify_authorized
after_action :verify_policy_scoped
# A refusal looks exactly like a record that does not exist
rescue_from Pundit::NotAuthorizedError do |error|
Rails.logger.warn("Refused #{error.query} on #{error.record.class} for user #{current_user.id}")
raise ActiveRecord::RecordNotFound
end
end
# app/controllers/job_cards_controller.rb
class JobCardsController < StaffController
def index
authorize JobCard
@job_cards = policy_scope(JobCard).includes(:booking).order(:created_at)
end
def show
@job_card = authorize policy_scope(JobCard).find(params[:id])
end
def update
@job_card = authorize policy_scope(JobCard).find(params[:id])
if @job_card.update(job_card_params)
redirect_to @job_card
else
render :show, status: :unprocessable_entity
end
end
private
def job_card_params
params.require(:job_card).permit(:status, :notes, before_photos: [], after_photos: [])
end
end
authorize returns the record it was given, so one line finds through the scope and checks the action21. Pundit calls current_user to find the user, which our Authentication concern provides21. Raising ActiveRecord::RecordNotFound turns a refusal into the same 404 as a missing record, so a mechanic who guesses an invoice number learns nothing, not even that the invoice exists. The log line keeps the refusal visible to Aisling and Cian.
The InvoicesController follows the same pattern. Because InvoicePolicy#index? is false for mechanics, a mechanic who types /invoices gets the same not found page.
The live board needs the same rule
The workshop board updates live through Turbo Streams, as built in the chapter on Hotwire. The view subscribes with turbo_stream_from, and turbo rails signs the stream name, so a browser cannot subscribe to a stream it invented: if the signature does not verify, the subscription is rejected23. But the signed name works like a key. Anyone who has seen a page containing it can listen. So the authorisation happens when the page is rendered, and the stream must be named after the thing the viewer is allowed to see.
Example: one stream per workshop
<%# app/views/job_cards/index.html.erb %>
<%= turbo_stream_from current_user.workshop, :board unless current_user.owner? %>
# app/models/job_card.rb (the relevant part)
class JobCard < ApplicationRecord
belongs_to :booking
after_update_commit do
broadcast_replace_later_to booking.workshop, :board
end
end
Each workshop's board listens to its own stream, so a card moving at Castletroy never reaches a browser at Dooradoyle. A single global stream called :board would have been easier to write and would have sent every customer's name on every card to all six workshops. Niamh's overview of all workshops renders one turbo_stream_from per workshop, which her role allows.
Tests that prove the rules
A roles table that is not tested is a wish. The tests below use Minitest, which Rails includes, and fixtures. The chapter on habits that keep a team fast explains why I keep the default stack. Writing tests first and the full workflow come in a later chapter of the testing series, on test driven development in Rails.
Example: fixtures for two workshops
# test/fixtures/users.yml
castletroy_mechanic:
email_address: mechanic.castletroy@freewheelcycles.example
password_digest: <%= BCrypt::Password.create("long enough secret") %>
role: mechanic
workshop: castletroy
castletroy_manager:
email_address: manager.castletroy@freewheelcycles.example
password_digest: <%= BCrypt::Password.create("long enough secret") %>
role: manager
workshop: castletroy
otp_secret: <%= ROTP::Base32.random %>
niamh:
email_address: niamh@freewheelcycles.example
password_digest: <%= BCrypt::Password.create("long enough secret") %>
role: owner
The fixtures for workshops, bookings, job cards and invoices follow the same pattern: castletroy and dooradoyle workshops, a job card castletroy_puncture on a Kelham booking, a job card dooradoyle_service on an Ecclesall booking, and an invoice castletroy_march. One caveat: because otp_secret is encrypted, encrypted fixtures need config.active_record.encryption.encrypt_fixtures = true in config/environments/test.rb, as the encryption guide describes7.
Example: policy tests
# test/policies/job_card_policy_test.rb
require "test_helper"
class JobCardPolicyTest < ActiveSupport::TestCase
test "a mechanic sees the job cards of their own workshop only" do
visible = JobCardPolicy::Scope.new(users(:castletroy_mechanic), JobCard).resolve
assert_includes visible, job_cards(:castletroy_puncture)
assert_not_includes visible, job_cards(:dooradoyle_service)
end
test "the owner sees every workshop" do
visible = JobCardPolicy::Scope.new(users(:niamh), JobCard).resolve
assert_includes visible, job_cards(:dooradoyle_service)
end
test "only managers and the owner may delete a job card" do
card = job_cards(:castletroy_puncture)
assert_not JobCardPolicy.new(users(:castletroy_mechanic), card).destroy?
assert JobCardPolicy.new(users(:castletroy_manager), card).destroy?
end
end
# test/policies/invoice_policy_test.rb
require "test_helper"
class InvoicePolicyTest < ActiveSupport::TestCase
test "a mechanic cannot see any invoice" do
mechanic = users(:castletroy_mechanic)
assert_not InvoicePolicy.new(mechanic, invoices(:castletroy_march)).show?
assert_empty InvoicePolicy::Scope.new(mechanic, Invoice).resolve
end
end
Example: the room attack, as an integration test
# test/test_helper.rb (addition)
class ActionDispatch::IntegrationTest
def sign_in_as(user, password: "long enough secret")
post session_path, params: { email_address: user.email_address, password: password }
end
end
# test/integration/job_card_access_test.rb
require "test_helper"
class JobCardAccessTest < ActionDispatch::IntegrationTest
test "a guessed id from another workshop shows nothing" do
sign_in_as users(:castletroy_mechanic)
get job_card_path(job_cards(:dooradoyle_service))
assert_response :not_found
end
test "a mechanic cannot open the invoices at all" do
sign_in_as users(:castletroy_mechanic)
get invoices_path
assert_response :not_found
end
test "a wrong password does not reveal whether the address exists" do
post session_path, params: { email_address: "nobody@freewheelcycles.example", password: "x" * 12 }
unknown_address = flash[:alert]
post session_path, params: { email_address: users(:niamh).email_address, password: "x" * 12 }
assert_equal unknown_address, flash[:alert]
end
end
These tests return 404 because the generated config/environments/test.rb in Rails 7.1 sets config.action_dispatch.show_exceptions = :rescuable, which turns ActiveRecord::RecordNotFound into a not found response just as production does. And one note for the throttles: the test environment uses a null cache store, so Rack::Attack never throttles in tests unless you give it a memory store in the test that checks it.
The tools that watch the doors for you
Two tools close the gaps a human review misses.
Brakeman is a static analysis scanner for Rails: it reads the source code without running the application, which means it can run on every commit24. It knows the escape hatches above and many more, such as unsafe redirects and dangerous send calls. Its own documentation is honest that it is deliberately suspicious, produces false positives and cannot understand everything in the code24. Treat each warning as a question, and record the answer.
bundler audit checks Gemfile.lock against the Ruby Advisory Database for gem versions with known vulnerabilities, and flags gem sources that use insecure http:// or git:// addresses25. Your code can be perfect and a dependency still not.
Example: Freewheel's security check before every deploy
# Run before each deploy, and in continuous integration (CI) on every push
bundle exec brakeman --quiet --no-pager
bundle exec bundle-audit check --update
bin/escape_hatches
The same release also turns on the Content Security Policy that Rails generates commented out. Freewheel uses import maps, so the nonce settings from the generated file are kept, and the policy starts in report only mode for a week, to see what it would block before it blocks anything:
# config/initializers/content_security_policy.rb
Rails.application.configure do
config.content_security_policy do |policy|
policy.default_src :self, :https
policy.img_src :self, :https, :data, :blob # job card photos
policy.object_src :none
policy.script_src :self, :https
policy.style_src :self, :https
end
config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s }
config.content_security_policy_nonce_directives = %w(script-src style-src)
config.content_security_policy_report_only = true # switch to false after a clean week
end
A CSP is the second line behind escaping: if a script ever slips into a page, the browser refuses to run it because it did not come from an allowed source1. How to run these checks automatically on every change, and keep CI fast, is a later chapter in the testing series.
What the law asks: the GDPR and the Data Protection Commission
This section is general information, not legal advice. For decisions about your own processing, talk to a data protection professional.
Freewheel Cycles processes personal data: names, phone numbers, email addresses, home addresses on invoices, and photos that may show a customer's bike outside their house. In Ireland, the EU General Data Protection Regulation (GDPR) applies directly, alongside the Data Protection Act 201826. The supervisory authority is the Data Protection Commission (DPC)27. Three articles of the GDPR matter directly to this chapter:
- Article 5(1)(f) requires personal data to be processed in a way that ensures appropriate security, using appropriate technical or organisational measures17.
- Article 32 asks for a level of security appropriate to the risk, taking into account what current technology offers and what it costs, and names encryption and the ability to keep systems confidential among the measures28.
- Article 33 requires a personal data breach to be reported to the supervisory authority, here the DPC, without undue delay and, where feasible, within 72 hours of becoming aware of it, unless it is unlikely to result in a risk to people's rights and freedoms29.
The law does not name Rails, two factor authentication or Pundit. It asks for measures appropriate to the risk, and it expects you to be able to show what you did.
Example: Freewheel's measures, mapped to the risk
| Risk | Measure in the application | Where in this article |
|---|---|---|
| A mechanic sees another workshop's customers | Scopes per workshop, tested | Authorisation |
| A manager's password is phished | Second factor, lockout after 10 codes | Second factor, rate limits |
| A leaver keeps access | Deactivation takes effect on the next click | Staff login |
| A database backup leaks | Second factor secrets encrypted, passwords only as bcrypt hashes, no customer passwords at all | Second factor, customers |
| Tokens and passwords in logs | Default parameter filter | Defaults |
| A known flaw in a gem | bundler audit on every deploy | Tools |
Aisling keeps this table in the repository next to the roles table. If the DPC ever asks what Freewheel did to secure customer data, the answer is a file, with the tests that prove it, rather than a memory.
For the person paying for this
If you commission a Rails application, you do not need to read the code to judge its security. Ask for these six things. A developer who has done the work can show each one in minutes.
- The roles table. Who may see and do what, signed off by you. If it does not exist, the rules exist only in someone's head.
- The tests for the roles table, and a run of them. Especially the test that a guessed id from another customer or branch returns "not found".
- The
config.load_defaultsline inconfig/application.rb. On a Rails 7.1 application it should say 7.1, or there should be a written reason why not. - A Brakeman and bundler audit run from this week, with every remaining warning explained.
- The list of escape hatches in the code, from a search like Cian's, with a reason next to each.
- What happens when someone leaves. Ask the developer to deactivate a test login while it is signed in and show you that the next click lands on the sign in page.
If any of these takes longer than a day to produce, that tells you more than any assurance. I build web applications on Rails this way, test first, and the client owns the code, the accounts and the data. If you want a second pair of eyes on an application you already have, the free workshop is the place to start, and my prices are published.
Conclusion
Rails guards the doors. A new Rails 7.1 application rejects forged forms, escapes HTML, separates values from SQL, filters parameters, encrypts its session cookie and forces HTTPS in production, all before you write a line. Your job at the doors is to keep them shut: search for the named escape hatches, run Brakeman and bundler audit, turn on the Content Security Policy and encrypt the columns that matter.
The rooms are yours. Authentication on Rails 7.1's own primitives is now a few hundred lines you fully understand, as long as you count your flows honestly and reach for Devise or Rodauth when they pass about five. Customers often need no password at all. Anyone who can see money needs a second factor, and a lockout per account, because throttles only slow guessing down. Authorisation starts with the roles table, then scope first, check second, so that a guessed id is a 404 by construction. Then the tests prove it.
The next chapter, on growing a Rails application without it turning into a mess, takes the same application two years on, to 14 workshops, where these policies have to keep up with a much larger codebase.
