Preventing IDOR and Broken Access Control in Ruby on Rails

A comprehensive security engineering guide to preventing IDOR and broken access control in Ruby on Rails using scoped associations, Pundit policies, and RSpec.

Abstract cybersecurity composition: IDOR & Broken Access Control defense architecture in Ruby on Rails with red security accents

Insecure Direct Object References (IDOR), classified under Broken Access Control in the OWASP Top 10, remain one of the most prevalent vulnerabilities affecting Ruby on Rails web applications. The very convention-over-configuration philosophy that makes Rails remarkably productive can inadvertently expose internal database models if developers rely blindly on default REST scaffolding.

In Rails, scaffolding and tutorials routinely showcase controller actions like @order = Order.find(params[:id]). While clean and concise, this pattern is fundamentally vulnerable: it looks up the order globally across the entire database, regardless of which tenant or customer is currently logged in. If Alice intercepts her HTTP request and substitutes Bob’s order ID, Rails will happily fetch Bob’s record and return it to Alice.

Before diving into Rails policy gems, ensure your broader web application security perimeter is protected by reviewing our guides on preventing CSRF attacks and cookie security best practices with HttpOnly and SameSite.

The Classic Rails Anti-Pattern: Unscoped Lookups

Consider a standard e-commerce or customer portal controller generated by traditional Rails scaffolding:

# VULNERABLE CONTROLLER IMPLEMENTATION
class OrdersController < ApplicationController
  before_action :authenticate_user! # Devise authentication ensures user is logged in

  def show
    # VULNERABILITY: Global unscoped lookup!
    # Any authenticated user can supply any ID in params[:id]
    @order = Order.find(params[:id])
    render json: @order
  end

  def destroy
    # CRITICAL VULNERABILITY: Cross-user deletion!
    @order = Order.find(params[:id])
    @order.destroy
    head :no_content
  end
end

In this code, authenticate_user! verifies that the user is logged in. However, Rails does not know that @order must belong to current_user. An authenticated attacker can iterate through /orders/1, /orders/2, and /orders/3, reading every customer's private invoice data or deleting their records.

Security Layer Vulnerable Rails Pattern Hardened Production Pattern
Data Lookup Order.find(params[:id]) Association scoping: current_user.orders.find(params[:id])
Complex Policies Inline if @order.user != current_user Declarative policy objects with Pundit or Action Policy
Mass Assignment Permitting foreign keys in strong params Explicitly setting ownership: current_user.orders.build(order_params)
ID Exposure Auto-incrementing integer IDs (/orders/50) UUIDv7 or has_secure_token / friendly_id obfuscation
Status Codes Rescuing with render status: :forbidden Letting ActiveRecord::RecordNotFound return standard 404 Not Found

Technical Control 1: Association-Scoped Lookups

The first and most idiomatic line of defense in Ruby on Rails is querying records through the authenticated user's associations:

class OrdersController < ApplicationController
  before_action :authenticate_user!

  def show
    # SECURE: Lookup is automatically scoped to current_user
    # Generates: SELECT * FROM orders WHERE orders.user_id = 12 AND orders.id = 50 LIMIT 1
    @order = current_user.orders.find(params[:id])
    render json: @order
  end

  def destroy
    @order = current_user.orders.find(params[:id])
    @order.destroy
    head :no_content
  end
end

Why Scoped Queries Stop IDOR by Default

When using current_user.orders.find(params[:id]), if an attacker tries to access an order owned by someone else, ActiveRecord will fail to find a matching row and raise ActiveRecord::RecordNotFound.

In production environments, Rails automatically catches ActiveRecord::RecordNotFound and renders 404 Not Found. This conceals the existence of other users' records, completely mitigating automated blind ID enumeration attacks.


Technical Control 2: Declarative Authorization with Pundit

While association scoping works well for single-owner records, real-world systems quickly encounter complex authorization requirements:

  • Organizations with multiple team members.
  • Roles like "Accountant", "Manager", and "Auditor".
  • Time-based edit windows (e.g. orders can only be edited within 15 minutes of placement).

Attempting to handle these variations using complex association chains creates unmaintainable controller code. The gold standard for authorization in Rails is Pundit.

Step 1: Install and Include Pundit in ApplicationController

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

  # Ensure every controller action calls authorize or policy_scope
  after_action :verify_authorized, except: :index
  after_action :verify_policy_scoped, only: :index

  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

  private

  def user_not_authorized
    render json: { error: "You are not authorized to perform this action." }, status: :forbidden
  end
end

Step 2: Define the Policy Class (app/policies/order_policy.rb)

class OrderPolicy < ApplicationPolicy
  # Define which records the user is allowed to see in index lists
  class Scope < Scope
    def resolve
      if user.admin?
        scope.all
      elsif user.manager?
        scope.where(organization_id: user.organization_id)
      else
        scope.where(user_id: user.id)
      end
    end
  end

  def show?
    user.admin? || record.user_id == user.id || record.organization_id == user.organization_id
  end

  def update?
    # Only owner can update, and only while status is pending
    (record.user_id == user.id && record.pending?) || user.admin?
  end

  def destroy?
    record.user_id == user.id && record.pending?
  end
end

Step 3: Enforce Policies in the Controller

class OrdersController < ApplicationController
  before_action :authenticate_user!

  def index
    # Uses OrderPolicy::Scope to filter records automatically
    @orders = policy_scope(Order)
    render json: @orders
  end

  def show
    @order = Order.find(params[:id])
    # Challenges the retrieved record against OrderPolicy#show?
    authorize @order
    render json: @order
  end

  def update
    @order = Order.find(params[:id])
    authorize @order

    if @order.update(order_params)
      render json: @order
    else
      render json: { errors: @order.errors }, status: :unprocessable_entity
    end
  end
end

Technical Control 3: Defending Against Parameter Tampering in Mass Assignment

Another subtle variant of IDOR occurs when creating or updating records: an attacker sends user_id or organization_id in the request body to assign objects to arbitrary accounts.

Never permit ownership foreign keys in Rails Strong Parameters:

class OrdersController < ApplicationController
  private

  # VULNERABLE STRONG PARAMS:
  # def order_params
  #   params.require(:order).permit(:title, :amount, :user_id) # Attacker can inject user_id!
  # end

  # SECURE STRONG PARAMS:
  def order_params
    params.require(:order).permit(:title, :amount, :shipping_address)
  end

  def create
    # Explicitly bind to current_user rather than trusting request parameters
    @order = current_user.orders.build(order_params)
    authorize @order

    if @order.save
      render json: @order, status: :created
    else
      render json: { errors: @order.errors }, status: :unprocessable_entity
    end
  end
end

Technical Control 4: Automated Security Testing with RSpec

Authorization controls must be verified with automated test suites. In RSpec, write policy and request specs testing unauthorized access:

# spec/requests/orders_spec.rb
RSpec.describe "Orders API", type: :request do
  let(:alice) { create(:user) }
  let(:bob) { create(:user) }
  let(:bobs_order) { create(:order, user: bob) }

  describe "GET /orders/:id" do
    context "when Alice attempts to access Bob's order" do
      before do
        sign_in alice # Authenticate as Alice
        get "/orders/#{bobs_order.id}"
      end

      it "refuses access and does not expose Bob's data" do
        expect(response).to have_http_status(:not_found).or have_http_status(:forbidden)
        expect(response.body).not_to include(bobs_order.title)
      end
    end
  end
end

Security Review Checklist for Rails Controllers

Before shipping code to production:

  • Are single-record lookups scoped via current_user.association.find(params[:id])?
  • If using global .find(id), is authorize @record invoked immediately afterwards?
  • Is after_action :verify_authorized enabled in ApplicationController to catch missing authorization checks?
  • Are foreign keys (user_id, account_id, tenant_id) excluded from params.permit?
  • Do index actions enforce policy_scope rather than querying Model.all?

Official Documentation and Further Reading


Application Security Defense Matrix: Insecure Direct Object References (IDOR), Ruby on Rails Guide.

Keep reading