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 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. Cogwell Cycles is a chain of six bicycle repair workshops in Sheffield (cogwellcycles.example), founded by Hannah. Its two developers, Priya and Owen, 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 Kelham Island workshop. Invoice 311 belongs to a customer called Mr Ahmed. 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 Cogwell 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 cogwellcycles.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 Priya 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 Kelham Island workshop is curious about how busy the Ecclesall Road 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 Priya and Owen 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.

ProtectionGuards againstOn by default in a new Rails 7.1 app?How it gets switched off
Authenticity token on every form and Turbo requestCross site request forgery (CSRF)Yes, since the 5.2 defaults3skip_forgery_protection in a controller
Values sent to the database apart from the SQLSQL injectionYes, when you use hash conditions or ? placeholders1Building SQL with string interpolation
Automatic HTML escaping in ERB templatesCross site scripting (XSS)Yes4html_safe, raw, <%==
Strong parametersMass assignment of fields like roleYes5permit!
Encrypted, signed session cookieReading or changing the sessionYes1Writing secrets into plain cookies[...]
SameSite=Lax on cookiesCookies riding along on cross site requestsYes, since the 6.1 defaults3Configuration
HTTPS only, with HTTP Strict Transport Security (HSTS) and secure cookiesEavesdropping, downgrade to plain HTTPYes in production, new in Rails 7.16config.force_ssl = false
Redirects to other hosts raise an errorOpen redirects used for phishingYes, since the 7.0 defaults3allow_other_host: true
Parameter filtering in logsPasswords and tokens in log filesYes, for names containing passw, secret, token, _key, crypt, salt, certificate, otp, ssnRemoving entries from the list
Encrypted credentialsSecret keys in the Git repositoryYes1Committing config/master.key
Host authorisationDNS rebindingIn development only. Production needs config.hosts3
Content Security Policy (CSP)Injected scripts running at allNo. The initialiser is generated but commented out
Active Record encryptionReadable data in a leaked database or backupNo. 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 Cogwell's site. Here is what Rails does along the way, without any code from Priya or Owen:

  1. The booking page is rendered with a hidden authenticity_token field, and the layout's csrf_meta_tags puts the same token in the page head for Turbo to send as a header1.
  2. 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.
  3. 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.
  4. The controller saves the booking with booking_params, which permits bike_id, starts_at and notes. A crafted request that also sends booking[price_pence]=0 has that field dropped, because it is not on the list.
  5. 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.
  6. All of this travels over HTTPS, because the generated config/environments/production.rb in Rails 7.1 contains config.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 hatchWhat it switches offWhat to write instead
where("name = '#{params[:name]}'"), order(params[:sort]), find_by_sql with interpolationParameterised querieswhere(name: value), where("starts_at > ?", time), an allow list of sortable columns
html_safe, raw(...), <%==HTML escapingPlain <%= %>, simple_format, or sanitize with an allow list of tags1
params.require(:user).permit!Strong parametersName every field. Never let role or workshop_id in from a form a user controls
redirect_to params[:return_to], allow_other_host: trueOpen redirect protectionurl_from(params[:return_to]), which returns nil for another host, with root_path as the fallback8
skip_forgery_protectionCSRF tokensKeep it on for anything a browser with cookies talks to
Model.find(params[:id]) in a controller for logged in usersNothing, because nothing protected itFind through a scope, as shown in the authorisation section
constantize or send on a value from paramsNothing: it lets a request choose which code runsAn 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: Cogwell's ten minute review before each release

Owen 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. Priya 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 primitivesDeviseRodauthOmniAuth
What it isMethods in Rails itselfA gem of ten modulesA framework with a Rails integrationLogin through another provider
Code you ownAll of it, typically a few hundred linesConfiguration and viewsConfigurationCallback handling
Second factorBuild it, for example with rotpSeparate gemsBuilt inThe provider's own
Best whenFew flows, all understoodStandard sign up flows, many usersMany flows, strict security needsUsers 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.

Tap or click to enlarge

Example: Cogwell counts its flows

Priya and Owen list who logs in and what each person needs.

  • Staff. 38 mechanics, one manager per workshop (six, an assumption of this example) and Hannah 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 Hannah 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 Cogwell builds on the Rails 7.1 primitives. Had Hannah 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: Cogwell'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, so find_by(email_address: " Hannah@Cogwellcycles.example ") finds the right row12.
  • The minimum of 12 characters is Cogwell'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_for returns 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_session before 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_s on both parameters means a crafted request that sends a nested hash instead of a string becomes a harmless string.
  • current_user reads the database on every request. When a mechanic leaves, a manager sets deactivated_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.

# 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.

Cogwell requires it for managers and Hannah, 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: "Cogwell 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: "Cogwell 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 Hannah, 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 Cogwell 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 nn guesses is right is

P(n)=1−(1−p)nP(n) = 1 - (1 - p)^{n}

where P(n)P(n) is the probability of at least one correct guess in nn attempts, pp is the probability that a single guess is correct, and nn is the number of guesses the attacker gets. With one valid code out of a million possible codes, p=11,000,000p = \frac{1}{1{,}000{,}000}. (The 15 second drift window can make two codes valid for a moment, which at worst doubles pp. The conclusion does not change.) Foundations: probability

Work it through with Cogwell's code throttle of 5 attempts every 5 minutes from one address:

  1. Attempts per day from one address: n=5×24×605=5×288=1,440n = 5 \times \frac{24 \times 60}{5} = 5 \times 288 = 1{,}440.
  2. One day: P=1−(1−10−6)1,440≈0.14%P = 1 - (1 - 10^{-6})^{1{,}440} \approx 0.14\%.
  3. Thirty days: n=43,200n = 43{,}200, so P≈4.2%P \approx 4.2\%.
  4. One year: n=525,600n = 525{,}600, so P≈40.9%P \approx 40.9\%.
  5. A hundred addresses for one day, which a botnet rents easily: n=144,000n = 144{,}000, so P≈13.4%P \approx 13.4\%.
  6. With Cogwell's lockout after 10 wrong codes on the account, whatever the address: n=10n = 10, so P=0.001%P = 0.001\%, after which the attempt needs Hannah on the phone.
Probability that an attacker who has the password guesses the second factor code. With a throttle of 5 tries every 5 minutes from one address: 0.14% in one day, 4.2% in 30 days, 13.4% with 100 addresses for one day, 40.9% in one year. With a lockout after 10 wrong codes per account: 0.001%. Tap or click to enlarge

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. Cogwell picks 10, because 45 staff can phone Hannah.

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 like user.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 nested Scope class whose resolve method returns the records a user may see21. Controllers call authorize and policy_scope. It also offers verify_authorized and verify_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]). Owen's escape hatch script from earlier searches for the first form, so the habit is checked on every release.

Tap or click to enlarge

Example: Cogwell's roles and rights

Before writing a policy, Priya writes the table and Hannah signs it off. This table is the specification. The policies are its translation into code, and the tests prove the translation.

WhatCustomer (by link)MechanicWorkshop managerOwner (Hannah)
Book a repairYes, no login neededYes, walk ins at own workshopOwn workshopAll workshops
See job cardsOwn bikes onlyOwn workshopOwn workshopAll workshops
Move a card on the boardNoOwn workshopOwn workshopAll workshops
Before and after photosSee ownAdd, own workshopAdd, own workshopAll workshops
Parts stockNoSee and record usage, own workshopEdit and reorder, own workshopAll workshops
Invoices with VATOwn invoicesNoOwn workshopAll workshops
ReportsNoNoOwn workshopAll workshops
Staff loginsNoNoMechanics at own workshopEveryone
Second factorNot needed (link only)NoRequiredRequired

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               # Cogwell'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 Priya and Owen.

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 Kelham Island never reaches a browser at Ecclesall Road. 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. Hannah'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
kelham_mechanic:
  email_address: mechanic.kelham@cogwellcycles.example
  password_digest: <%= BCrypt::Password.create("long enough secret") %>
  role: mechanic
  workshop: kelham

kelham_manager:
  email_address: manager.kelham@cogwellcycles.example
  password_digest: <%= BCrypt::Password.create("long enough secret") %>
  role: manager
  workshop: kelham
  otp_secret: <%= ROTP::Base32.random %>

hannah:
  email_address: hannah@cogwellcycles.example
  password_digest: <%= BCrypt::Password.create("long enough secret") %>
  role: owner

The fixtures for workshops, bookings, job cards and invoices follow the same pattern: kelham and ecclesall workshops, a job card kelham_puncture on a Kelham booking, a job card ecclesall_service on an Ecclesall booking, and an invoice kelham_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(:kelham_mechanic), JobCard).resolve

    assert_includes visible, job_cards(:kelham_puncture)
    assert_not_includes visible, job_cards(:ecclesall_service)
  end

  test "the owner sees every workshop" do
    visible = JobCardPolicy::Scope.new(users(:hannah), JobCard).resolve

    assert_includes visible, job_cards(:ecclesall_service)
  end

  test "only managers and the owner may delete a job card" do
    card = job_cards(:kelham_puncture)

    assert_not JobCardPolicy.new(users(:kelham_mechanic), card).destroy?
    assert JobCardPolicy.new(users(:kelham_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(:kelham_mechanic)

    assert_not InvoicePolicy.new(mechanic, invoices(:kelham_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(:kelham_mechanic)

    get job_card_path(job_cards(:ecclesall_service))

    assert_response :not_found
  end

  test "a mechanic cannot open the invoices at all" do
    sign_in_as users(:kelham_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@cogwellcycles.example", password: "x" * 12 }
    unknown_address = flash[:alert]

    post session_path, params: { email_address: users(:hannah).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: Cogwell'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. Cogwell 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: UK GDPR and the ICO

This section is general information, not legal advice. For decisions about your own processing, speak to a data protection professional.

Cogwell 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 the UK, the UK General Data Protection Regulation (UK GDPR) and the Data Protection Act 2018 apply26. Three articles matter directly to this chapter:

  • Article 5(1)(f) requires personal data to be processed with appropriate security, using "appropriate technical or organisational measures", as the Information Commissioner's Office (ICO), the UK regulator, explains in its guide to data security27.
  • 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 ICO 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. The ICO's guide says to make sure appropriate access controls are in place and to use encryption where appropriate27.

Example: Cogwell's measures, mapped to the risk

RiskMeasure in the applicationWhere in this article
A mechanic sees another workshop's customersScopes per workshop, testedAuthorisation
A manager's password is phishedSecond factor, lockout after 10 codesSecond factor, rate limits
A leaver keeps accessDeactivation takes effect on the next clickStaff login
A database backup leaksSecond factor secrets encrypted, passwords only as bcrypt hashes, no customer passwords at allSecond factor, customers
Tokens and passwords in logsDefault parameter filterDefaults
A known flaw in a gembundler audit on every deployTools

Priya keeps this table in the repository next to the roles table. If the ICO ever asks what Cogwell 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.

  1. 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.
  2. 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".
  3. The config.load_defaults line in config/application.rb. On a Rails 7.1 application it should say 7.1, or there should be a written reason why not.
  4. A Brakeman and bundler audit run from this week, with every remaining warning explained.
  5. The list of escape hatches in the code, from a search like Owen's, with a reason next to each.
  6. 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.

If you want someone to walk through the roles, logins and escape hatches of your Rails application with you, book the free workshop. The first two weeks of work are on me.

Sources

  1. 1.

    Ruby on Rails Guides, Securing Rails Applications, version 7.1, https://guides.rubyonrails.org/v7.1/security.html

  2. 2.

    OWASP Foundation, A01:2021 Broken Access Control, OWASP Top 10:2021, 2021, https://owasp.org/Top10/A01_2021-Broken_Access_Control/

  3. 3.

    Ruby on Rails Guides, Configuring Rails Applications, version 7.1, https://guides.rubyonrails.org/v7.1/configuring.html

  4. 4.

    Ruby on Rails API, ActionView::Helpers::OutputSafetyHelper, version 7.1, https://api.rubyonrails.org/v7.1/classes/ActionView/Helpers/OutputSafetyHelper.html

  5. 5.

    Ruby on Rails Guides, Action Controller Overview, section Strong Parameters, version 7.1, https://guides.rubyonrails.org/v7.1/action_controller_overview.html

  6. 6.

    Ruby on Rails, Railties change log for 7.1 ("Enable force_ssl=true in production by default"), GitHub, 2023, https://github.com/rails/rails/blob/v7.1.3.2/railties/CHANGELOG.md

  7. 7.

    Ruby on Rails Guides, Active Record Encryption, version 7.1, https://guides.rubyonrails.org/v7.1/active_record_encryption.html

  8. 8.

    Ruby on Rails API, ActionController::Redirecting (url_from), version 7.1, https://api.rubyonrails.org/v7.1/classes/ActionController/Redirecting.html

  9. 9.

    Ruby on Rails API, ActiveModel::SecurePassword::ClassMethods (has_secure_password), version 7.1, https://api.rubyonrails.org/v7.1/classes/ActiveModel/SecurePassword/ClassMethods.html

  10. 10.

    Ruby on Rails API, ActiveRecord::SecurePassword::ClassMethods (authenticate_by), version 7.1, https://api.rubyonrails.org/v7.1/classes/ActiveRecord/SecurePassword/ClassMethods.html

  11. 11.

    Ruby on Rails API, ActiveRecord::TokenFor::ClassMethods (generates_token_for, find_by_token_for), version 7.1, https://api.rubyonrails.org/v7.1/classes/ActiveRecord/TokenFor/ClassMethods.html

  12. 12.

    Ruby on Rails Guides, Ruby on Rails 7.1 Release Notes, October 2023, https://guides.rubyonrails.org/v7.1/7_1_release_notes.html

  13. 13.

    Devise, README, version 4.9.3 (released 11 October 2023), heartcombo, GitHub, https://github.com/heartcombo/devise/blob/v4.9.3/README.md

  14. 14.

    Janko Marohnić, rodauth rails, README, version 1.13.0 (released 25 December 2023), GitHub, https://github.com/janko/rodauth-rails/blob/v1.13.0/README.md

  15. 15.

    OmniAuth, Resolving CVE 2015 9284, OmniAuth wiki, GitHub, https://github.com/omniauth/omniauth/wiki/Resolving-CVE-2015-9284

  16. 16.

    Paul A. Grassi and others, NIST Special Publication 800 63B, Digital Identity Guidelines: Authentication and Lifecycle Management, National Institute of Standards and Technology, June 2017, updated 2 March 2020, sections 5.1.1.2 and 5.2.2, https://pages.nist.gov/800-63-3/sp800-63b.html

  17. 17.

    UK General Data Protection Regulation, Article 5, Principles relating to processing of personal data, legislation.gov.uk, https://www.legislation.gov.uk/eur/2016/679/article/5

  18. 18.

    D. M'Raihi, S. Machani, M. Pei and J. Rydell, RFC 6238, TOTP: Time Based One Time Password Algorithm, Internet Engineering Task Force, May 2011, https://datatracker.ietf.org/doc/html/rfc6238

  19. 19.

    Mark Percival, ROTP, README, version 6.3.0 (released 30 August 2023), GitHub, https://github.com/mdp/rotp/blob/v6.3.0/README.md

  20. 20.

    Rack::Attack, README, version 6.7.0 (released 26 July 2023), GitHub, https://github.com/rack/rack-attack/blob/v6.7.0/README.md

  21. 21.

    Pundit, README, version 2.3.1 (released 17 July 2023), Varvet, GitHub, https://github.com/varvet/pundit/blob/v2.3.1/README.md

  22. 22.

    Evil Martians, Action Policy documentation, https://actionpolicy.evilmartians.io/

  23. 23.

    Hotwire, turbo rails, Turbo::StreamsChannel source and documentation, version 2.0.4 (released 21 February 2024), GitHub, https://github.com/hotwired/turbo-rails/blob/v2.0.4/app/channels/turbo/streams_channel.rb

  24. 24.

    Brakeman, Introduction, Brakeman documentation, https://brakemanscanner.org/docs/introduction/

  25. 25.

    RubySec, bundler audit, README, GitHub, https://github.com/rubysec/bundler-audit

  26. 26.

    Data Protection Act 2018, legislation.gov.uk, https://www.legislation.gov.uk/ukpga/2018/12/contents

  27. 27.

    Information Commissioner's Office, A guide to data security, ico.org.uk, https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/security/a-guide-to-data-security/

  28. 28.

    UK General Data Protection Regulation, Article 32, Security of processing, legislation.gov.uk, https://www.legislation.gov.uk/eur/2016/679/article/32

  29. 29.

    UK General Data Protection Regulation, Article 33, Notification of a personal data breach to the supervisory authority, legislation.gov.uk, https://www.legislation.gov.uk/eur/2016/679/article/33

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter