Switchyard

Broken authorization

The IDOR hiding in your Rails controllers

One line, usually written on day one, that lets any logged-in user read anyone else’s records.

In May 2019, a real estate developer in Washington state noticed that a link First American Financial had sent him for one of his own documents had a nine-digit number in it. He changed the number and got somebody else’s mortgage paperwork. Then somebody else’s. The site would hand anyone about 885 million documents going back 16 years (bank statements, Social Security numbers, wire receipts, driver’s license images) without a login, and the numbers were sequential. KrebsOnSecurity broke the story, and the SEC opened an investigation.

That’s the most common serious bug we see in Rails apps, and it’s also the most boring one. Somebody writes Invoice.find(params[:id]), it works in development, the tests pass, and it ships. Then a customer changes the number in the URL and reads somebody else’s invoice.

It’s called an IDOR (insecure direct object reference, a name only a standards body could love). Rails won’t stop you from writing one, and the scaffold generator writes the vulnerable lookup for you.

The basic bug

class InvoicesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_invoice, only: %i[show edit update destroy]

  def show
  end

  private

  def set_invoice
    @invoice = Invoice.find(params[:id])
  end
end

authenticate_user! checks that someone is logged in. It doesn’t check who. Anyone with an account can read every invoice in the table by counting up from 1, and since set_invoice also runs before update and destroy, they can edit and delete them too.

The basic fix

def set_invoice
  @invoice = current_user.invoices.find(params[:id])
end

If the invoice belongs to someone else, find raises ActiveRecord::RecordNotFound and Rails turns that into a 404. A 404 is the right answer here, by the way—a 403 confirms the record exists, which is free information for whoever is poking at your IDs.

First American’s version needs one more piece, because their links went out by email to people who might not have an account. A long random ID only makes the record harder to guess; it doesn’t check who’s asking. A signed link that expires does the job:

def share(document, recipient)
  @url = shared_document_url(token: document.signed_id(expires_in: 7.days, purpose: :share))
  mail(to: recipient.email, subject: "Your closing documents")
end
class SharedDocumentsController < ApplicationController
  def show
    @document = Document.find_signed(params[:token], purpose: :share) or raise ActiveRecord::RecordNotFound
  end
end

signed_id is signed with your app’s secret, so changing one character gets you a 404 instead of a neighbor’s tax return, and the link stops working after a week. Anyone who’s logged in still goes through the scoped lookup above.

The hardcore version

class TasksController < ApplicationController
  before_action :set_project

  def update
    @task = Task.find(params[:id])
    @task.update!(task_params)
    redirect_to [@project, @task]
  end

  def complete_all
    Task.where(id: params[:task_ids]).update_all(completed_at: Time.current)
    redirect_to @project
  end

  private

  def set_project
    @project = current_user.projects.find(params[:project_id])
  end
end

This one passes review all the time, because set_project is scoped and everything reads as safe. It isn’t. The task lookup ignores the project entirely, so any task ID works under any project you own. The bulk action is worse: where(id: ...) doesn’t raise when it matches records you don’t own. It just updates them.

The background job version

class ExportsController < ApplicationController
  def create
    ExportJob.perform_later(current_user.id, params[:report_ids])
    redirect_to reports_path, notice: "We'll email it to you."
  end
end
class ExportJob < ApplicationJob
  def perform(user_id, report_ids)
    user = User.find(user_id)
    reports = Report.where(id: report_ids)
    ReportMailer.export(user, reports).deliver_now
  end
end

The controller never loads a report, so there’s nothing to scope there, and the job has no current_user, so there’s nothing to scope it to. It gets two arguments and believes both of them. Put a few IDs that aren’t yours in the request and the CSV lands in your inbox a minute later. If you’re running Pundit’s verify_authorized, someone will make the error go away with authorize Report, which checks the class and says yes.

Jobs need the same scoping as controllers. They just have to do it with the user they were handed:

def perform(user_id, report_ids)
  user = User.find(user_id)
  reports = user.reports.where(id: report_ids)
  ReportMailer.export(user, reports).deliver_now
end

Same goes for anything that takes IDs now and does the work later: bulk deletes, imports, the "send this to my accountant" button. Treat the job’s arguments like params, because that’s where they came from.

The GraphQL version

class AppSchema < GraphQL::Schema
  def self.object_from_id(global_id, context)
    GlobalID::Locator.locate(global_id)
  end
end

Relay-style APIs hand out global IDs and let clients fetch anything with node(id:). This resolver will find any record of any model in the app, scoped to nothing. The IDs look opaque (they’re base64 of something like gid://yourapp/Invoice/42), and opaque gets mistaken for secret constantly. Anyone who decodes one can see exactly how to make another, including for models you never meant to expose through the API at all.

class AppSchema < GraphQL::Schema
  def self.object_from_id(global_id, context)
    GlobalID::Locator.locate(global_id, only: [Invoice, Project])
  end
end
module Types
  class InvoiceType < Types::BaseObject
    def self.authorized?(object, context)
      super && object.account_id == context[:current_account].id
    end
  end
end

only: limits which models a global ID can resolve to. authorized? runs every time an invoice comes back from any field, not just node, so project { invoices } gets checked too. When it returns false, graphql-ruby returns nil by default, which is the GraphQL version of a 404.

Fix #1: Scope through the parent, every time

def update
  @task = @project.tasks.find(params[:id])
  @task.update!(task_params)
  redirect_to [@project, @task]
end

def complete_all
  @project.tasks.where(id: params[:task_ids]).update_all(completed_at: Time.current)
  redirect_to @project
end

Every lookup starts from something you already authorized. If you catch yourself typing a bare model constant followed by find or where in a controller, stop and ask what it should be scoped to. The answer is almost never "nothing."

Fix #2: Make forgetting impossible to miss

Fix #1 depends on every developer remembering, forever. Pundit lets you write the rule once per model and, more importantly, blow up when an action skips it:

class ApplicationController < ActionController::Base
  include Pundit::Authorization

  after_action :verify_authorized, except: :index
  after_action :verify_policy_scoped, only: :index
end
class TaskPolicy < ApplicationPolicy
  def update?
    user.project_ids.include?(record.project_id)
  end

  class Scope < ApplicationPolicy::Scope
    def resolve
      scope.where(project_id: user.project_ids)
    end
  end
end
def update
  @task = policy_scope(Task).find(params[:id])
  authorize @task
  @task.update!(task_params)
  redirect_to [@project, @task]
end

Now a new action that forgets to call authorize raises Pundit::AuthorizationNotPerformedError in development and in your test suite, which is a much better time to find out than when a customer emails you.

Fix #3: Let Postgres say no

The hardest-core version moves the rule into the database with row-level security. Even a raw find_by_sql someone writes in 2029 can’t read another account’s rows:

class EnableRowLevelSecurityOnInvoices < ActiveRecord::Migration[8.0]
  def up
    execute <<~SQL
      ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
      CREATE POLICY invoices_by_account ON invoices
        USING (account_id = current_setting('app.current_account_id', true)::bigint);
    SQL
  end

  def down
    execute <<~SQL
      DROP POLICY invoices_by_account ON invoices;
      ALTER TABLE invoices DISABLE ROW LEVEL SECURITY;
    SQL
  end
end
class ApplicationController < ActionController::Base
  around_action :scope_database_to_account

  private

  def scope_database_to_account
    connection = ActiveRecord::Base.connection

    ActiveRecord::Base.transaction do
      connection.execute("SET LOCAL app.current_account_id = #{connection.quote(Current.account.id.to_s)}")
      yield
    end
  end
end

Three gotchas. The app has to connect as a role that doesn’t own the tables, because owners bypass policies (or use FORCE ROW LEVEL SECURITY). SET LOCAL only lasts for the transaction, which is the point: it can’t leak to the next request that borrows the connection. And wrapping every request in a transaction changes when things commit, so jobs enqueued mid-request need to wait for the commit. It’s real work. It’s also the only fix on this page that survives a developer having a bad day.

Switchyard tests for IDORs automatically. Or grep for .find(params and start reading. That works too; it’s just slower. :)

Secure your Rails app today.

Find and fix critical vulnerabilities in minutes.

Inquire