Go to Page Content

Your RLS Policies Might Not Be Doing Anything

James Fawks

Superusers and table owners bypass Postgres RLS, and most Rails setups connect as one. Learn how to check your roles and set up the ones you need.

Part 2 of a series on multi-tenant Rails with Postgres Row Level Security.

In the first post, we turned on Row Level Security for the invoices table, added a policy, and set the current account at the start of each request. If you are using the wrong user type or configuration, Postgres could be skipping your policy entirely. It’s like the policy isn’t there at all, and if you forget to add the account ID to the WHERE clause, you get every invoice in the database.

Which roles RLS doesn’t apply to

Postgres has three kinds of roles that RLS policies don’t restrict:

  • A superuser bypasses RLS on every table, always, and there’s no setting that changes this.
  • Roles with the BYPASSRLS attribute skip every policy.
  • Table owners are not subject to that table’s policies unless you explicitly force RLS on the table.

What to watch out for in development

You want to make sure your development environment is set up as close to production as possible and is using the RLS policies. Otherwise, you may get the “it works on my machine” response.

Here are a few things to watch out for:

  • Make sure you are not using the Postgres user used to create the Postgres service, as it is a superuser and will bypass any policy you set.
  • Even if the user is not a superuser, when running db:setup or db:migrate, any tables created will be owned by that user. If you don’t force row level security on those tables, that user bypasses every policy.
  • Make sure your test suite connects as the same restricted role as production. If it connects as a superuser or table owner, a test that checks tenant isolation will pass because the policy isn’t being evaluated at all.

Check which role is actually being used

Run this from a Rails console or bin/rails dbconsole, using the same configuration your app uses:

SELECT rolname, rolsuper, rolbypassrls
FROM pg_roles
WHERE rolname = current_user;

If rolsuper or rolbypassrls is true, your policies are being skipped. If both are false, check who owns your tables and whether RLS is forced on them:

SELECT c.relname AS table_name,
    pg_get_userbyid(c.relowner) AS owner,
    c.relrowsecurity AS rls_enabled,
    c.relforcerowsecurity AS rls_forced
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relkind = 'r'
ORDER BY c.relname;

If the owner is the same user your app connects as, and rls_forced is false, that table’s policies don’t apply to your app.

Limited user role for the app

In order to accurately enforce RLS, there should be two user roles for the app based on the job the user needs to perform:

  • An owner role (I’ll call it app_owner) that owns the schema and the tables, and runs migrations.
  • An app role (app_user) that Rails connects as to serve requests and run jobs. The app_user isn’t a superuser, can’t bypass RLS, and doesn’t own anything. It only gets the permissions it needs to read and write data.

Roles belong to the entire Postgres server, so you create them once:

CREATE ROLE app_owner LOGIN PASSWORD 'change-me';
CREATE ROLE app_user  LOGIN PASSWORD 'change-me';

Permissions, on the other hand, belong to a single database, so you run these in each database (development, test, and production), connected as app_owner:

GRANT USAGE ON SCHEMA public TO app_user;

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app_user;

-- Tables and sequences created by future migrations get the same grants
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT USAGE, SELECT ON SEQUENCES TO app_user;

Notice what app_user doesn’t get: It can’t create, alter, or drop tables. If someone ever gets SQL injection into your app, they can’t drop your schema or turn RLS off, because the role they’re running as isn’t allowed to.

Note: Since Postgres 15, regular roles can’t create tables in the public schema by default. Either make app_owner the owner of each database (ALTER DATABASE myapp_production OWNER TO app_owner;) or run GRANT CREATE ON SCHEMA public TO app_owner; so it can run migrations.

Force RLS on every table

Separating roles means the app never gets the owner’s bypass. Forcing RLS covers the case where something connects as the owner anyway, like a misconfigured server or a console session someone opened with the wrong credentials:

ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;

With FORCE, the owner is also subject to the table’s policies. Superusers and BYPASSRLS roles still skip them, which is one more reason to keep both away from your app.

Forcing RLS has one side effect worth knowing about: data migrations that run as the owner are now filtered like everything else. A migration that backfills a column on invoices will either error because no account is set, or touch only one account’s rows. That’s the right default. Background work that genuinely needs to span tenants gets its own post later in the series.

Wiring it into Rails

Rails doesn’t have a built-in way to use one set of credentials for migrations and another for the app, but environment variables get you there with very little code. Point database.yml at the app role by default:

default: &default
  adapter: postgresql
  encoding: unicode
  host: <%= ENV.fetch("DB_HOST", "localhost") %>
  username: <%= ENV.fetch("DB_USER", "app_user") %>
  password: <%= ENV["DB_PASSWORD"] %>

Then run anything that changes the schema as the owner. A small wrapper script keeps that from being tedious:

#!/usr/bin/env bash
# bin/db: run schema-changing tasks as the owner role
DB_USER=app_owner DB_PASSWORD="$OWNER_DB_PASSWORD" exec bin/rails "$@"

Now bin/db db:migrate and bin/db db:test:prepare run as the owner, while bin/rails server, your jobs, and your test suite run as app_user. In production, your deploy runs migrations with the owner’s credentials, and the app’s environment only ever has the app role’s password.

For local development with Docker, create both roles in an init script so every developer gets the same setup. The Postgres image runs any .sql file in /docker-entrypoint-initdb.d the first time the container starts. In development, give app_owner the CREATEDB attribute so bin/db db:create works.

The important part is that development and test match production. If your tests connect as a superuser, every isolation test you write is checking nothing.

Make tests fail loudly

Checking your configuration is a good start, but it isn’t proof. Real proof is testing the app’s behavior: act as one account that tries to read, create, update, and delete another account’s invoices, and confirm every attempt is blocked. Run these tests as app_user, and write them so they fail if they ever connect as a superuser or the table owner. I’ll walk through the full set of tests in the last post of the series.

Troubleshooting

  • “permission denied for table”. The app role is missing a grant, usually because a table or sequence was created before you set default privileges. Re-run the grant statements as the owner.

  • Grants missing in the test database. Rails dumps structure.sql without privileges, so a test database loaded from it has your tables and policies, but none of your grants. Run the grant statements again after loading the schema. I’ll show how I automate this when I introduce the gem I mentioned in the first part of this series.

  • Queries that return nothing. If RLS is enabled on a table but there’s no policy, Postgres denies everything by default, which can be confusing the first time you see it.

  • Default privileges are per role. ALTER DEFAULT PRIVILEGES only applies to objects created by the role that ran it. Run it as app_owner, since that’s the role your migrations run as.

  • What’s coming in this series

  1. Why RLS for tenant isolation in Rails
  2. Your RLS policies might not be doing anything: superusers, table owners, and the roles you actually need (this post)
  3. Setting tenant context per request with SET LOCAL
  4. Designing a schema around RLS
  5. Background jobs when every query needs a tenant
  6. Cross-tenant reads without punching holes: SECURITY DEFINER done safely
  7. Proving isolation: testing RLS in Rails

If you’re not sure which role your app connects as, or whether your policies are actually being enforced, I’d be glad to take a look. I can audit your current setup or help you put the right roles in place. Get in touch.

Related blogs

Tenant Isolation in Rails: Why I Let Postgres Enforce It

One missed WHERE clause can expose every customer’s data. Compare four ways to isolate tenants in Rails, and see why Postgres RLS makes the safer backstop.
Read in 8 minutes

Local SEO: What You Can Do Now Without Hiring an Agency

Small business owners keep asking me what they can do about local SEO before they have the budget for an agency. This is the short list I give them.
Read in 6 minutes

What Is Web Accessiblity?

Web accessibility ensures websites are usable for people with disabilities, helping small businesses reach more customers, comply with federal and local laws, and improve user experience.
Read in 6 minutes

Why do I not sign NDAs?

As a consultant and developer, I’m often asked to sign NDAs (Non-Disclosure Agreements). Here are my top 5 reasons I will not and my 6 criteria for signing one.
Read in 5 minutes