activerecord-rls 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 34809c16148058d26bacff89c596abbb1140c56c2af966fb579ff927c6904092
4
+ data.tar.gz: f8f496d01ea6e485b680fe4a9adc035e822686939399981672071dd542ab04c8
5
+ SHA512:
6
+ metadata.gz: 8ca3ad66dd91b612437e6292713be0399d279c0fbd785454b11c55d7b2d34d76d3004a25ac60ade8f946d22d75fe08aba35582bcac61b4035a20d06d73136cf4
7
+ data.tar.gz: a191f438c9751acf91adeac6f57994ced25d2bc0b7472032d813346474e7d99b3dac7b9ee28b28188329454b90da02f3a85563fc90524d8df57b39b1e210ca5d
@@ -0,0 +1,24 @@
1
+ ARG RUBY_VERSION=4.0.9
2
+ FROM ruby:${RUBY_VERSION}
3
+
4
+ ARG USERNAME=dev
5
+ ARG USER_UID=1000
6
+ ARG USER_GID=${USER_UID}
7
+
8
+ # libpq-dev for the pg gem, postgresql-client for psql/pg_dump (schema dumps, debugging)
9
+ RUN apt-get update \
10
+ && apt-get install -y --no-install-recommends \
11
+ build-essential git libpq-dev postgresql-client sudo less vim-tiny \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ RUN groupadd --gid ${USER_GID} ${USERNAME} \
15
+ && useradd --uid ${USER_UID} --gid ${USER_GID} -m -s /bin/bash ${USERNAME} \
16
+ && echo "${USERNAME} ALL=(root) NOPASSWD:ALL" > /etc/sudoers.d/${USERNAME} \
17
+ && chmod 0440 /etc/sudoers.d/${USERNAME}
18
+
19
+ # Keep installed gems in a named volume so rebuilds are fast
20
+ ENV BUNDLE_PATH=/usr/local/bundle \
21
+ GEM_HOME=/usr/local/bundle
22
+ RUN mkdir -p ${BUNDLE_PATH} && chown -R ${USERNAME}:${USERNAME} ${BUNDLE_PATH}
23
+
24
+ USER ${USERNAME}
@@ -0,0 +1,42 @@
1
+ name: activerecord-rls
2
+
3
+ services:
4
+ app:
5
+ build:
6
+ context: .
7
+ dockerfile: Dockerfile
8
+ command: sleep infinity
9
+ volumes:
10
+ - ..:/workspaces/activerecord-rls:cached
11
+ - bundle:/usr/local/bundle
12
+ environment:
13
+ PGHOST: db
14
+ PGPORT: "5432"
15
+ PGUSER: postgres
16
+ PGPASSWORD: postgres
17
+ DATABASE_URL: postgres://postgres:postgres@db:5432/activerecord_rls_test
18
+ depends_on:
19
+ db:
20
+ condition: service_healthy
21
+
22
+ db:
23
+ image: postgres:18
24
+ restart: unless-stopped
25
+ environment:
26
+ POSTGRES_USER: postgres
27
+ POSTGRES_PASSWORD: postgres
28
+ POSTGRES_DB: activerecord_rls_test
29
+ volumes:
30
+ # Postgres 18+ images store data under /var/lib/postgresql/<major>/docker
31
+ - postgres-data:/var/lib/postgresql
32
+ ports:
33
+ - "5432"
34
+ healthcheck:
35
+ test: ["CMD-SHELL", "pg_isready -U postgres -d activerecord_rls_test"]
36
+ interval: 5s
37
+ timeout: 5s
38
+ retries: 10
39
+
40
+ volumes:
41
+ bundle:
42
+ postgres-data:
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "activerecord-rls",
3
+ "dockerComposeFile": "compose.yaml",
4
+ "service": "app",
5
+ "runServices": ["app", "db"],
6
+ "workspaceFolder": "/workspaces/activerecord-rls",
7
+ "shutdownAction": "stopCompose",
8
+ "remoteUser": "dev",
9
+
10
+ "forwardPorts": ["db:5432"],
11
+ "portsAttributes": {
12
+ "db:5432": { "label": "PostgreSQL" }
13
+ },
14
+
15
+ "postCreateCommand": "sudo chown -R dev:dev /usr/local/bundle && bundle install",
16
+
17
+ "customizations": {
18
+ "jetbrains": {
19
+ "backend": "RubyMine"
20
+ }
21
+ }
22
+ }
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-11-23
4
+
5
+ - Initial release
@@ -0,0 +1,10 @@
1
+ # Code of Conduct
2
+
3
+ "activerecord-rls" follows [The Ruby Community Conduct Guideline](https://www.ruby-lang.org/en/conduct) in all "collaborative space", which is defined as community communications channels (such as mailing lists, submitted patches, commit comments, etc.):
4
+
5
+ * Participants will be tolerant of opposing views.
6
+ * Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
7
+ * When interpreting the words and actions of others, participants should always assume good intentions.
8
+ * Behaviour which can be reasonably considered harassment will not be tolerated.
9
+
10
+ If you have any concerns about behaviour within this project, please contact us at ["jefawks3@gmail.com"](mailto:"jefawks3@gmail.com").
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 James Fawks
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,511 @@
1
+ # ActiveRecord::RLS
2
+
3
+ PostgreSQL [row level security](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) (RLS) for Active Record.
4
+
5
+ ActiveRecord::RLS lets you manage everything RLS needs from Rails:
6
+
7
+ - **Migrations** for roles, privileges, default privileges, policies, and enabling RLS. They can all be rolled back.
8
+ - **`schema.rb` support**, so roles, privileges, policies, and RLS settings are dumped and loaded with the rest of your schema.
9
+ - **Runtime variables** that tell your policies who the current user, tenant, or workspace is, including helpers on your models.
10
+
11
+ ## Requirements
12
+
13
+ - Ruby 3.2 or later
14
+ - Active Record 7.2 or later (tested with Rails 7.2, 8.0, and 8.1)
15
+ - PostgreSQL. The gem uses PostgreSQL-only features and does not work with other databases.
16
+
17
+ ## Installation
18
+
19
+ Add the gem to your Gemfile:
20
+
21
+ ```ruby
22
+ gem "activerecord-rls"
23
+ ```
24
+
25
+ Then run `bundle install`. The gem hooks itself into Active Record when it loads; there is nothing else to set up.
26
+
27
+ ## Quick start
28
+
29
+ This example limits each workspace's todos to that workspace.
30
+
31
+ **1. Create a role for the application and give it access to the table**
32
+
33
+ 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](#forcing-rls-on-table-owners)).
34
+
35
+ ```ruby
36
+ class AddRlsToTodos < ActiveRecord::Migration[8.1]
37
+ def change
38
+ create_role "app"
39
+ grant_privileges_to "app", %w[SELECT INSERT UPDATE DELETE], :table, "todos"
40
+
41
+ enable_rls "todos"
42
+ enable_force_rls "todos"
43
+
44
+ create_policy "todos", name: "todos_workspace_isolation" do |policy|
45
+ policy.using "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
46
+ policy.check "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
47
+ end
48
+ end
49
+ end
50
+ ```
51
+
52
+ **2. Tell the policy which workspace is current**
53
+
54
+ ```ruby
55
+ class Workspace < ApplicationRecord
56
+ include ActiveRecord::RLS::Model
57
+
58
+ ...
59
+ end
60
+
61
+ class ApplicationController < ActionController::Base
62
+ around_action :scope_to_workspace
63
+
64
+ private
65
+
66
+ def scope_to_workspace(&block)
67
+ ActiveRecord::Base.transaction do
68
+ current_workspace.with_rls_runtime_variable(&block)
69
+ end
70
+ end
71
+ end
72
+ ```
73
+
74
+ 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.
75
+
76
+ ## Migrations
77
+
78
+ Every method below can be used in a `change` method and is reversed automatically on rollback, except `alter_policy`.
79
+
80
+ ### Roles
81
+
82
+ ```ruby
83
+ create_role "app"
84
+ create_role "reporting", bypass_rls: true, create_db: false
85
+ create_role "app_user", password: true # can log in; see "Role passwords"
86
+
87
+ alter_role "reporting", bypass_rls: false
88
+ create_or_alter_role "app", inherit: true
89
+
90
+ drop_role "app"
91
+ drop_role "app", reassign: true # hand its objects to the database owner first
92
+ drop_role "app", reassign: "other_role" # or to another role
93
+ ```
94
+
95
+ 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.
96
+
97
+ > **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](#role-passwords).
98
+
99
+ 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.
100
+
101
+ ### Privileges
102
+
103
+ ```ruby
104
+ grant_privileges_to "app", %w[SELECT INSERT UPDATE DELETE], :table, "todos"
105
+ grant_privileges_to %w[app reporting], "SELECT", :table, %w[todos workspaces]
106
+ grant_privileges_to "app", "UPDATE", :table, "todos", columns: %w[title]
107
+ grant_privileges_to "app", "SELECT", :table, :all, schema: "public" # every table in a schema
108
+ grant_privileges_to "app", "USAGE", :sequence, :all, schema: "public"
109
+ grant_privileges_to "app", "USAGE", :schema, "reporting"
110
+
111
+ grant_privileges_to "app_user", "app", nil, nil # make app_user a member of app
112
+
113
+ revoke_privileges_from "app", "DELETE", :table, "todos"
114
+ revoke_privileges_from "app", "SELECT", :table, "todos", cascade: true
115
+ ```
116
+
117
+ ### Default privileges
118
+
119
+ 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.
120
+
121
+ ```ruby
122
+ grant_default_privileges_to "app", %w[SELECT INSERT UPDATE DELETE], :tables, target_role: "deploy", schema: "public"
123
+ grant_default_privileges_to "app", %w[SELECT USAGE], :sequences, target_role: "deploy"
124
+
125
+ revoke_default_privileges_from "app", "DELETE", :tables, target_role: "deploy", schema: "public"
126
+ ```
127
+
128
+ Default privileges do not apply to tables that already exist. Grant those separately with `grant_privileges_to`.
129
+
130
+ ### Enabling RLS
131
+
132
+ ```ruby
133
+ enable_rls "todos"
134
+ disable_rls "todos"
135
+
136
+ enable_force_rls "todos"
137
+ disable_force_rls "todos"
138
+ ```
139
+
140
+ Turning RLS on with no policies denies everything to every role that RLS applies to.
141
+
142
+ ### Policies
143
+
144
+ `create_policy`, `alter_policy`, and `drop_policy` pass a policy builder to their block. The builder has two methods:
145
+
146
+ - **`using`** sets the policy's `USING` expression: which existing rows can be read, updated, or deleted.
147
+ - **`check`** sets its `WITH CHECK` expression: which rows can be inserted, or what rows can be changed into.
148
+
149
+ Each takes an SQL string, or a block that returns one.
150
+
151
+ ```ruby
152
+ # Reading: only the current workspace's todos are visible.
153
+ create_policy "todos", name: "todos_select", command: :select, roles: "app" do |policy|
154
+ policy.using "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
155
+ end
156
+
157
+ # Writing: new todos must belong to the current workspace.
158
+ create_policy "todos", name: "todos_insert", command: :insert, roles: "app" do |policy|
159
+ policy.check "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
160
+ end
161
+
162
+ # Updating: only the current workspace's todos can be changed, and they can't
163
+ # be moved to another workspace.
164
+ create_policy "todos", name: "todos_update", command: :update, roles: "app" do |policy|
165
+ policy.using { "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer" }
166
+ policy.check { "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer" }
167
+ end
168
+
169
+ create_policy "todos", name: "todos_hide_archived", permissive: false do |policy|
170
+ policy.using "archived = false"
171
+ end
172
+
173
+ rename_policy "todos", "todos_select", "todos_read"
174
+ drop_policy "todos", name: "todos_read"
175
+ ```
176
+
177
+ `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.
178
+
179
+ | Option | Default | Notes |
180
+ | --- | --- | --- |
181
+ | `name` | `<table>_<roles>_policy` | |
182
+ | `command` | `:all` | `:all`, `:select`, `:insert`, `:update`, or `:delete` |
183
+ | `roles` | `PUBLIC` | One role or an array. `"public"`, `"current_user"`, `"current_role"`, and `"session_user"` are accepted. |
184
+ | `permissive` | `true` | `false` creates a restrictive policy |
185
+
186
+ 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.
187
+
188
+ To roll back `drop_policy`, give it the same options and block the policy was created with, so it can be recreated:
189
+
190
+ ```ruby
191
+ drop_policy "todos", name: "todos_select", command: :select, roles: "app" do |policy|
192
+ policy.using "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
193
+ end
194
+ ```
195
+
196
+ #### Changing a policy
197
+
198
+ ```ruby
199
+ alter_policy "todos", name: "todos_select", roles: %w[app reporting] do |policy|
200
+ policy.using "workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer"
201
+ end
202
+ ```
203
+
204
+ `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.
205
+
206
+ `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.
207
+
208
+ ## Writing policies
209
+
210
+ ### Use NULLIF when reading runtime variables
211
+
212
+ Write policies like this:
213
+
214
+ ```sql
215
+ workspace_id = NULLIF(current_setting('rls.workspace_id', true), '')::integer
216
+ ```
217
+
218
+ and not like this:
219
+
220
+ ```sql
221
+ workspace_id = current_setting('rls.workspace_id', true)::integer
222
+ ```
223
+
224
+ 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.
225
+
226
+ ### Who RLS applies to
227
+
228
+ - **Superusers and roles with `BYPASSRLS`** always skip RLS. Use them for maintenance or reporting roles, never for your application's connection.
229
+ - **Table owners** skip RLS unless it is forced.
230
+ - **Everyone else** only sees and changes rows the policies allow.
231
+
232
+ ### Forcing RLS on table owners
233
+
234
+ 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:
235
+
236
+ ```ruby
237
+ enable_force_rls "todos"
238
+ ```
239
+
240
+ ## Runtime variables
241
+
242
+ Policies find out who the current user or tenant is from PostgreSQL runtime variables, which are read with `current_setting(...)`.
243
+
244
+ ### On the connection
245
+
246
+ ```ruby
247
+ connection = ActiveRecord::Base.lease_connection
248
+
249
+ connection.set_runtime_variable "rls.workspace_id", 42
250
+ connection.runtime_variable "rls.workspace_id" # => "42", or nil if never set
251
+ connection.reset_runtime_variable "rls.workspace_id"
252
+
253
+ connection.with_runtime_variable "rls.workspace_id", 42 do
254
+ Todo.all.to_a # only workspace 42's todos
255
+ end # the previous value is restored, even if the block raises
256
+ ```
257
+
258
+ Every method takes `scope:`:
259
+
260
+ - **`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.
261
+ - **`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.
262
+
263
+ Passing `nil` as the value resets the variable.
264
+
265
+ Variable names must be dotted identifiers such as `rls.workspace_id`. Other names raise an `ArgumentError`.
266
+
267
+ ### On models
268
+
269
+ Include `ActiveRecord::RLS::Model` to use a record's id as a runtime variable:
270
+
271
+ ```ruby
272
+ class Workspace < ApplicationRecord
273
+ include ActiveRecord::RLS::Model
274
+ end
275
+
276
+ workspace.with_rls_runtime_variable { Todo.all.to_a } # rls.workspace_id = workspace.id
277
+ workspace.set_rls_runtime_variable # until the transaction ends
278
+ workspace.set_rls_runtime_variable(scope: :session)
279
+ workspace.reset_rls_runtime_variable
280
+
281
+ Workspace.rls_runtime_variable_name # => "rls.workspace_id"
282
+ ```
283
+
284
+ 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.
285
+
286
+ To change the namespace for every model:
287
+
288
+ ```ruby
289
+ # config/initializers/rls.rb
290
+ ActiveRecord::RLS.config do |config|
291
+ config.default_runtime_variable_namespace = :app
292
+ end
293
+ ```
294
+
295
+ To change it for one model, override `rls_runtime_variable_namespace`. To change the whole name, override `rls_runtime_variable_name`:
296
+
297
+ ```ruby
298
+ class Tenant < ApplicationRecord
299
+ include ActiveRecord::RLS::Model
300
+
301
+ def self.rls_runtime_variable_name
302
+ "app.current_tenant"
303
+ end
304
+ end
305
+ ```
306
+
307
+ ### Setting the variable whenever a connection is checked out
308
+
309
+ 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:
310
+
311
+ ```ruby
312
+ # config/initializers/rls.rb
313
+ ActiveRecord::ConnectionAdapters::AbstractAdapter.set_callback :checkout, :after do |connection|
314
+ connection.set_runtime_variable "rls.workspace_id", Current.workspace&.id, scope: :session
315
+ end
316
+ ```
317
+
318
+ `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.
319
+
320
+ ## Role passwords
321
+
322
+ 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:
323
+
324
+ 1. `ENV["#{Rails.env}_DB_ROLE_<ROLE>_PASSWORD"]`, for example `production_DB_ROLE_APP_USER_PASSWORD`
325
+ 2. `ENV["DB_ROLE_<ROLE>_PASSWORD"]`, for example `DB_ROLE_APP_USER_PASSWORD`
326
+ 3. `Rails.application.credentials.database.<role>.password`
327
+
328
+ ```yaml
329
+ # bin/rails credentials:edit
330
+ ...
331
+
332
+ database:
333
+ app_user:
334
+ password: a-long-random-password
335
+ ```
336
+
337
+ `<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.
338
+
339
+ The first and third sources are only used when Rails is loaded.
340
+
341
+ ## schema.rb
342
+
343
+ `bin/rails db:schema:dump` adds the following to `schema.rb`, after your tables:
344
+
345
+ - every role on the PostgreSQL server, as `create_or_alter_role`
346
+ - default privileges, including the `target_role` they belong to
347
+ - privileges on tables, columns, sequences, schemas, and the current database, and role memberships
348
+ - policies
349
+ - which tables have RLS enabled and forced
350
+
351
+ Loading `schema.rb` recreates all of it. A few details:
352
+
353
+ - **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.
354
+ - **Tables outside `public`** are written with their schema, for example `"reporting.events"`.
355
+ - **Database privileges** are written with `current_database`, so they apply to whichever database the schema is loaded into.
356
+ - **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.
357
+ - **Schemas.** On Rails 8 and later, the dump covers the schemas in `ActiveRecord.dump_schemas`.
358
+
359
+ ## Testing your application
360
+
361
+ 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.
362
+
363
+ ### Two configurations for one database
364
+
365
+ ```yaml
366
+ # config/database.yml
367
+ default: &default
368
+ adapter: postgresql
369
+ url: <%= ENV["DATABASE_URL"] %>
370
+
371
+ ...
372
+
373
+ test:
374
+ primary:
375
+ <<: *default # the app's restricted role
376
+ database_tasks: false
377
+ bypass_rls:
378
+ <<: *default
379
+ database_tasks: true
380
+ schema_dump: "schema.rb"
381
+ url: <%= ENV["ADMIN_DATABASE_URL"] %>
382
+
383
+ ...
384
+ ```
385
+
386
+ - **`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.
387
+ - **`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.
388
+
389
+ ### Running test setup as the admin role
390
+
391
+ ```ruby
392
+ # test/test_helper.rb
393
+
394
+ ENV["RAILS_ENV"] ||= "test"
395
+ require_relative "../config/environment"
396
+
397
+ # Give tests a way to connect with the `bypass_rls` config:
398
+ ActiveRecord::Base.connects_to database: { test_setup: :bypass_rls }
399
+
400
+ # Create the ar_internal_metadata table with the `bypass_rls` config, because
401
+ # the app's role isn't allowed to create tables:
402
+ ActiveRecord::Base.connected_to role: :test_setup do
403
+ ActiveRecord::Base.connection_pool.internal_metadata.create_table
404
+ end
405
+
406
+ ...
407
+ ```
408
+
409
+ 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:
410
+
411
+ ```ruby
412
+ class ActiveSupport::TestCase
413
+ ...
414
+
415
+ def setup_fixtures
416
+ ActiveRecord::Base.connected_to(role: :test_setup) do
417
+ super
418
+ end
419
+ end
420
+
421
+ ...
422
+ end
423
+ ```
424
+
425
+ ### Parallel tests
426
+
427
+ 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:
428
+
429
+ ```ruby
430
+ class ActiveSupport::TestCase
431
+ ...
432
+
433
+ parallelize_setup do |index|
434
+ ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, include_hidden: true).each do |config|
435
+ config._database = "#{config.database}_#{index}" unless config.database.end_with?("_#{index}")
436
+ end
437
+ end
438
+
439
+ ...
440
+ end
441
+ ```
442
+
443
+ `_database=` is an internal Rails method, so check this still works when you upgrade Rails.
444
+
445
+ 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"`:
446
+
447
+ ```ruby
448
+ require "active_record/rls/test_databases"
449
+ ```
450
+
451
+ The roles still have to exist, so load the schema once, for example with `bin/rails db:test:prepare`, before running tests in parallel.
452
+
453
+ ## Reading the current setup
454
+
455
+ The schema dumper uses these methods, and you can call them too:
456
+
457
+ ```ruby
458
+ connection.all_roles
459
+ connection.all_privileges(schema: %w[public])
460
+ connection.all_default_privileges(schema: %w[public])
461
+ connection.all_policies(schema: %w[public], ignore: %w[schema_migrations])
462
+ connection.all_rls_policies(schema: %w[public])
463
+
464
+ connection.role_exists?("app")
465
+ connection.database_owner_role
466
+ ```
467
+
468
+ Each returns structs. For example, `all_policies` returns `Policy` structs with `table_name`, `name`, `permissive`, `roles`, `command`, `using`, `check`, and `schema`.
469
+
470
+ ## Names and SQL
471
+
472
+ - **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`.
473
+ - **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`.
474
+ - **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.
475
+ - **Function privileges** take their signature as written, for example `"add(integer, integer)"`.
476
+
477
+ ## Development
478
+
479
+ 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:
480
+
481
+ ```bash
482
+ bin/setup
483
+ bundle exec rake test
484
+ ```
485
+
486
+ Tests run against a PostgreSQL server reachable at host `db`, user `postgres`, password `postgres` (see `test/database.rb`). Every run:
487
+
488
+ - recreates the `active_record_rls_test` database
489
+ - loads `test/schema.rb` into a second database, `active_record_rls_test_fixture`
490
+
491
+ The end-to-end and migration tests use that second database.
492
+
493
+ `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:
494
+
495
+ ```bash
496
+ REGENERATE_SCHEMA=1 bundle exec rake test
497
+ ```
498
+
499
+ `bin/console` starts an interactive prompt with the gem loaded.
500
+
501
+ ## Contributing
502
+
503
+ 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](https://github.com/[USERNAME]/activerecord-rls/blob/main/CODE_OF_CONDUCT.md).
504
+
505
+ ## License
506
+
507
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
508
+
509
+ ## Code of Conduct
510
+
511
+ Everyone interacting in the ActiveRecord::RLS project's codebases, issue trackers, chat rooms, and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/activerecord-rls/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Development dependencies shared by the root Gemfile and every
4
+ # gemfiles/rails_*.gemfile. Each of those declares its own rails version.
5
+ gem "irb"
6
+ gem "rake", "~> 13.0"
7
+
8
+ gem "minitest", "~> 5.16"
9
+
10
+ gem "rubocop", "~> 1.21"
11
+ gem "rubocop-rails-omakase", require: false
12
+ gem "rubocop-minitest", "~> 0.41", require: false