Skip to content

About

PostgreSQL row level security for Rails: migrations, schema.rb support, and per-request tenant context.

Resources

Code of conduct

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ActiveRecord::RLS

PostgreSQL row level security (RLS) for Active Record.

ActiveRecord::RLS lets you manage everything RLS needs from Rails:

  • Migrations for roles, privileges, default privileges, policies, and enabling RLS. They can all be rolled back.
  • schema.rb support, so roles, privileges, policies, and RLS settings are dumped and loaded with the rest of your schema.
  • Runtime variables that tell your policies who the current user, tenant, or workspace is, including helpers on your models.

Requirements

  • Ruby 3.2 or later
  • Active Record 7.2 or later (tested with Rails 7.2, 8.0, and 8.1)
  • PostgreSQL. The gem uses PostgreSQL-only features and does not work with other databases.

Installation

Add the gem to your Gemfile:

gem "activerecord-rls"

Then run bundle install. The gem hooks itself into Active Record when it loads; there is nothing else to set up.

Quick start

This example limits each workspace's todos to that workspace.

1. Create a role for the application and give it access to the table

Your application must connect to the database as a role that is not a superuser, does not have BYPASSRLS, and does not own the tables. Superusers and roles with BYPASSRLS always skip RLS, and table owners skip it unless it is forced (see Forcing RLS).

class AddRlsToTodos < ActiveRecord::Migration[8.1]
  def change
    create_role "app"
    grant_privileges_to "app", %w[SELECT INSERT UPDATE DELETE], :table, "todos"

    enable_rls "todos"
    enable_force_rls "todos"

    create_policy "todos", name: "todos_workspace_isolation" do |policy|
      policy.using "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
      policy.check "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
    end
  end
end

2. Tell the policy which workspace is current

class Workspace < ApplicationRecord
  include ActiveRecord::RLS::Model
  
  ...
end

class ApplicationController < ActionController::Base
  around_action :scope_to_workspace
  
  private

  def scope_to_workspace(&block)
    ActiveRecord::Base.transaction do
      current_workspace.with_rls_runtime_variable(&block)
    end
  end
end

Inside the block, Todo.all only returns the current workspace's todos. Outside it, the policy matches nothing, so no todos are returned at all.

Migrations

Every method below can be used in a change method and is reversed automatically on rollback, except alter_policy.

Roles

create_role "app"
create_role "reporting", bypass_rls: true, create_db: false
create_role "app_user", password: true   # can log in; see "Role passwords"

alter_role "reporting", bypass_rls: false
create_or_alter_role "app", inherit: true

drop_role "app"
drop_role "app", reassign: true          # hand its objects to the database owner first
drop_role "app", reassign: "other_role"  # or to another role

Role options are super_user, inherit, create_role, create_db, replication, bypass_rls, and password. true turns a permission on and false turns it off. password: true also lets the role log in.

Passwords are not part of the migration. password: true only marks the role as one that can log in. The password itself is looked up when the migration runs, from environment variables or Rails credentials, so it never ends up in your migrations or schema.rb. See Role passwords.

When rolling back drop_role, the role is recreated with the options you passed to drop_role. Pass the role's options to drop_role if you want them restored.

Privileges

grant_privileges_to "app", %w[SELECT INSERT UPDATE DELETE], :table, "todos"
grant_privileges_to %w[app reporting], "SELECT", :table, %w[todos workspaces]
grant_privileges_to "app", "UPDATE", :table, "todos", columns: %w[title]
grant_privileges_to "app", "SELECT", :table, :all, schema: "public"   # every table in a schema
grant_privileges_to "app", "USAGE", :sequence, :all, schema: "public"
grant_privileges_to "app", "USAGE", :schema, "reporting"

grant_privileges_to "app_user", "app", nil, nil   # make app_user a member of app

revoke_privileges_from "app", "DELETE", :table, "todos"
revoke_privileges_from "app", "SELECT", :table, "todos", cascade: true

Default privileges

Default privileges apply to objects a role creates in the future. target_role is the role that will create them, which is usually the role your migrations run as.

grant_default_privileges_to "app", %w[SELECT INSERT UPDATE DELETE], :tables, target_role: "deploy", schema: "public"
grant_default_privileges_to "app", %w[SELECT USAGE], :sequences, target_role: "deploy"

revoke_default_privileges_from "app", "DELETE", :tables, target_role: "deploy", schema: "public"

Default privileges do not apply to tables that already exist. Grant those separately with grant_privileges_to.

Enabling RLS

enable_rls "todos"
disable_rls "todos"

enable_force_rls "todos"
disable_force_rls "todos"

Turning RLS on with no policies denies everything to every role that RLS applies to.

Policies

create_policy, alter_policy, and drop_policy pass a policy builder to their block. The builder has two methods:

  • using sets the policy's USING expression: which existing rows can be read, updated, or deleted.
  • check sets its WITH CHECK expression: which rows can be inserted, or what rows can be changed into.

Each takes an SQL string, or a block that returns one.

# Reading: only the current workspace's todos are visible.
create_policy "todos", name: "todos_select", command: :select, roles: "app" do |policy|
  policy.using "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
end

# Writing: new todos must belong to the current workspace.
create_policy "todos", name: "todos_insert", command: :insert, roles: "app" do |policy|
  policy.check "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
end

# Updating: only the current workspace's todos can be changed, and they can't
# be moved to another workspace.
create_policy "todos", name: "todos_update", command: :update, roles: "app" do |policy|
  policy.using { "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer" }
  policy.check { "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer" }
end

create_policy "todos", name: "todos_hide_archived", permissive: false do |policy|
  policy.using "archived = false"
end

rename_policy "todos", "todos_select", "todos_read"
drop_policy "todos", name: "todos_read"

INSERT policies only use check, because there are no existing rows to filter. SELECT and DELETE policies only use using. UPDATE and ALL policies use both. If an UPDATE or ALL policy has no check, PostgreSQL uses its using expression for both.

Option Default Notes
name <table>_<roles>_policy
command :all :all, :select, :insert, :update, or :delete
roles PUBLIC One role or an array. "public", "current_user", "current_role", and "session_user" are accepted.
permissive true false creates a restrictive policy

PostgreSQL combines permissive policies with OR: a row is visible if any of them allows it. Restrictive policies are combined with AND, and every one of them must allow the row as well.

To roll back drop_policy, give it the same options and block the policy was created with, so it can be recreated:

drop_policy "todos", name: "todos_select", command: :select, roles: "app" do |policy|
  policy.using "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
end

Changing a policy

alter_policy "todos", name: "todos_select", roles: %w[app reporting] do |policy|
  policy.using "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
end

alter_policy can change a policy's roles, using, and check. PostgreSQL can't change whether a policy is permissive or which command it applies to, so passing permissive: or command: raises an ArgumentError. Drop and recreate the policy instead.

alter_policy can't be rolled back automatically, because the previous definition isn't known. Use up and down methods, or reversible, if you need to roll it back.

Writing policies

Use NULLIF when reading runtime variables

Write policies like this:

workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer

and not like this:

workspace_id = current_setting('rls.workspace_id', true)::integer

The true makes current_setting return NULL instead of raising an error when the variable has never been set. Once a variable has been set in a session, resetting it leaves an empty string rather than NULL, and ''::integer raises an error. NULLIF turns the empty string back into NULL, so the policy matches no rows instead of failing the query.

Who RLS applies to

  • Superusers and roles with BYPASSRLS always skip RLS. Use them for maintenance or reporting roles, never for your application's connection.
  • Table owners skip RLS unless it is forced.
  • Everyone else only sees and changes rows the policies allow.

Forcing RLS on table owners

If your application connects as the role that owns its tables, which is common when migrations and the app use the same database user, RLS has no effect until you force it:

enable_force_rls "todos"

Runtime variables

Policies find out who the current user or tenant is from PostgreSQL runtime variables, which are read with current_setting(...).

On the connection

connection = ActiveRecord::Base.lease_connection

connection.set_runtime_variable "rls.workspace_id", 42
connection.runtime_variable "rls.workspace_id"   # => "42", or nil if never set
connection.reset_runtime_variable "rls.workspace_id"

connection.with_runtime_variable "rls.workspace_id", 42 do
  Todo.all.to_a   # only workspace 42's todos
end               # the previous value is restored, even if the block raises

Every method takes scope::

  • scope: :local (the default) lasts until the current transaction ends. It has no effect outside a transaction, so wrap your work in one, as the quick start does.
  • scope: :session lasts until it's changed or the connection is closed. Connections are reused from the pool, so reset session variables when you are done with them.

Passing nil as the value resets the variable.

Variable names must be dotted identifiers such as rls.workspace_id. Other names raise an ArgumentError.

On models

Include ActiveRecord::RLS::Model to use a record's id as a runtime variable:

class Workspace < ApplicationRecord
  include ActiveRecord::RLS::Model
end

workspace.with_rls_runtime_variable { Todo.all.to_a }   # rls.workspace_id = workspace.id
workspace.set_rls_runtime_variable                      # until the transaction ends
workspace.set_rls_runtime_variable(scope: :session)
workspace.reset_rls_runtime_variable

Workspace.rls_runtime_variable_name   # => "rls.workspace_id"

The variable is named <namespace>.<model>_id. Namespaced models use underscores, so Admin::User becomes rls.admin_user_id. The value is the record's primary key.

To change the namespace for every model:

# config/initializers/rls.rb
ActiveRecord::RLS.config do |config|
  config.default_runtime_variable_namespace = :app
end

To change it for one model, override rls_runtime_variable_namespace. To change the whole name, override rls_runtime_variable_name:

class Tenant < ApplicationRecord
  include ActiveRecord::RLS::Model

  def self.rls_runtime_variable_name
    "app.current_tenant"
  end
end

Setting the variable whenever a connection is checked out

Wrapping every request in a transaction, as the quick start does, is the simplest way to use scope: :local. The alternative is to set a session variable each time a connection is taken from the pool. Connections are shared between requests, so this makes sure a reused connection never keeps the previous request's value:

# config/initializers/rls.rb
ActiveRecord::ConnectionAdapters::AbstractAdapter.set_callback :checkout, :after do |connection|
  connection.set_runtime_variable "rls.workspace_id", Current.workspace&.id, scope: :session
end

Current.workspace must not need the database. If looking up the workspace checks out a connection, this callback runs again for that connection and can recurse. Load the workspace before any connection is checked out, or store just its id.

Role passwords

Passwords are never written to migrations or schema.rb. When a role is created or changed with password: true, its password is looked up in this order:

  1. ENV["#{Rails.env}_DB_ROLE_<ROLE>_PASSWORD"], for example production_DB_ROLE_APP_USER_PASSWORD
  2. ENV["DB_ROLE_<ROLE>_PASSWORD"], for example DB_ROLE_APP_USER_PASSWORD
  3. Rails.application.credentials.database.<role>.password
# bin/rails credentials:edit
...

database:
  app_user:
    password: a-long-random-password

<ROLE> is the role name in upper case. If no password is found, the role is still allowed to log in, but no password is set. An existing password is left unchanged.

The first and third sources are only used when Rails is loaded.

schema.rb

bin/rails db:schema:dump adds the following to schema.rb, after your tables:

  • every role on the PostgreSQL server, as create_or_alter_role
  • default privileges, including the target_role they belong to
  • privileges on tables, columns, sequences, schemas, and the current database, and role memberships
  • policies
  • which tables have RLS enabled and forced

Loading schema.rb recreates all of it. A few details:

  • Roles belong to the whole PostgreSQL server, not one database. create_or_alter_role creates a role if it is missing and updates it if it exists, so loading the schema is safe when roles already exist.
  • Tables outside public are written with their schema, for example "reporting.events".
  • Database privileges are written with current_database, so they apply to whichever database the schema is loaded into.
  • Ignored tables. Tables in ActiveRecord::SchemaDumper.ignore_tables are left out of the privileges, policies, and RLS sections too. Strings and regular expressions both work.
  • Schemas. On Rails 8 and later, the dump covers the schemas in ActiveRecord.dump_schemas.

Testing your application

Your tests should run as the same restricted role your app uses in production, or they won't catch a missing policy or privilege. Setting up the test database still needs a role that can create tables and bypass RLS, though. The setup below uses two database configurations that point at the same database with different credentials.

Two configurations for one database

# config/database.yml
default: &default
  adapter: postgresql
  url: <%= ENV["DATABASE_URL"] %>
  
...

test:
  primary:
    <<: *default             # the app's restricted role
    database_tasks: false
  bypass_rls:
    <<: *default
    database_tasks: true
    schema_dump: "schema.rb"
    url: <%= ENV["ADMIN_DATABASE_URL"] %>

...
  • primary connects as the app's restricted role. database_tasks: false stops Rails from using it to create the database or load the schema, which that role isn't allowed to do.
  • bypass_rls connects to the same database as an admin role: a superuser, or the tables' owner with BYPASSRLS. database_tasks: true and schema_dump: "schema.rb" make bin/rails db:test:prepare create the database and load schema.rb, including its roles, privileges, and policies, through this connection.

Running test setup as the admin role

# test/test_helper.rb

ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"

# Give tests a way to connect with the `bypass_rls` config:
ActiveRecord::Base.connects_to database: { test_setup: :bypass_rls }

# Create the ar_internal_metadata table with the `bypass_rls` config, because
# the app's role isn't allowed to create tables:
ActiveRecord::Base.connected_to role: :test_setup do
  ActiveRecord::Base.connection_pool.internal_metadata.create_table
end

...

Load fixtures as the admin role too. Otherwise RLS can hide or reject the fixture rows, and the app's role usually isn't allowed to turn off foreign key checks while fixtures are inserted:

class ActiveSupport::TestCase
  ...
  
  def setup_fixtures
    ActiveRecord::Base.connected_to(role: :test_setup) do
      super
    end
  end
  
  ...
end

Parallel tests

When tests run in parallel, each worker gets its own database, but Rails only renames the database for some configurations. Make sure every configuration, including bypass_rls, points at the worker's database:

class ActiveSupport::TestCase
  ...
  
  parallelize_setup do |index|
    ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, include_hidden: true).each do |config|
      config._database = "#{config.database}_#{index}" unless config.database.end_with?("_#{index}")
    end
  end
  
  ...
end

_database= is an internal Rails method, so check this still works when you upgrade Rails.

Each worker's database is created by loading schema.rb. The roles in it are shared by the whole PostgreSQL server, so several workers changing them at the same time can conflict. To skip role changes while the worker databases are created, add this after require "rails/test_help":

require "active_record/rls/test_databases"

The roles still have to exist, so load the schema once, for example with bin/rails db:test:prepare, before running tests in parallel.

Reading the current setup

The schema dumper uses these methods, and you can call them too:

connection.all_roles
connection.all_privileges(schema: %w[public])
connection.all_default_privileges(schema: %w[public])
connection.all_policies(schema: %w[public], ignore: %w[schema_migrations])
connection.all_rls_policies(schema: %w[public])

connection.role_exists?("app")
connection.database_owner_role

Each returns structs. For example, all_policies returns Policy structs with table_name, name, permissive, roles, command, using, check, and schema.

Names and SQL

  • Names are quoted. Role, table, schema, and column names are quoted, so mixed case, hyphens, and other special characters work as written. Names are not lower-cased: create_role "AppUser" creates AppUser, not appuser.
  • SQL keywords are checked. Privileges such as SELECT and object types such as :table can't be quoted, so anything other than plain words raises an ArgumentError.
  • Policy expressions are not escaped. The strings passed to policy.using and policy.check are SQL and are used exactly as written. Never build them from user input.
  • Function privileges take their signature as written, for example "add(integer, integer)".

Development

The repository includes a dev container with Ruby and PostgreSQL. Open it in your editor, or start it with the dev container CLI, then run:

bin/setup
bundle exec rake test

Tests run against a PostgreSQL server reachable at host db, user postgres, password postgres (see test/database.rb). Every run:

  • recreates the active_record_rls_test database
  • loads test/schema.rb into a second database, active_record_rls_test_fixture

The end-to-end and migration tests use that second database.

test/schema.rb is also the expected output of the schema dumper. If you change the dumper's output on purpose, regenerate it and review the diff:

REGENERATE_SCHEMA=1 bundle exec rake test

bin/console starts an interactive prompt with the gem loaded.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/activerecord-rls. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to follow the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the ActiveRecord::RLS project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the code of conduct.

About

PostgreSQL row level security for Rails: migrations, schema.rb support, and per-request tenant context.

Resources

Code of conduct

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages