Go to Page Content

Setting Tenant Context per Request with SET LOCAL

James Fawks

A plain SET leaks tenant context between pooled connections. Learn how to scope Postgres RLS to each Rails request with SET LOCAL and a transaction.

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

In the first post, the policy on the invoices table compared each row’s account_id to a session variable, app.account_id, and the app set that variable at the start of each request inside a transaction. That detail is easy to skim past, but it’s the difference between a policy that protects you and one that quietly hands one customer’s data to another.

This post covers how Postgres session variables work, why a plain SET leaks between requests, and how to wire tenant context into a Rails app so every query runs with the right account.

Session variables in Postgres

Postgres lets you define your own settings, as long as the name has a dot in it, like app.account_id. The settings can be scoped two different ways:

  1. SET, or SET SESSION, changes the value for the rest of the database connection.
  2. SET LOCAL changes the value only until the current transaction commits or rolls back.

Policies read the value with current_setting('app.account_id'), and Postgres doesn’t care which way it was set. The difference is how long the setting sticks around.

Why SET leaks between requests

Rails doesn’t open a new database connection for every request. It keeps a pool of connections and hands them out as requests come in. When a request finishes, its connection goes back into the pool for the next request to use.

Now picture what happens with a plain SET or SET SESSION:

  1. Request A, for account 1, checks out a connection and runs SET app.account_id = '1'.
  2. Request A finishes. The connection goes back into the pool, still set to account 1.
  3. Request B, for account 2, checks out the same connection. Because of a bug, an exception, or an unconsidered code path, it never sets the account.
  4. Request B’s queries run as account 1.

RLS is doing exactly what it was told. It’s just been told the wrong account. There are no errors, and nothing shows up in your logs.

You could try to reset the variable at the end of every request, but that has to work every time, including when the request raises an exception halfway through. With SET LOCAL, you don’t have to remember. The value is tied to the transaction, so it disappears when the transaction ends. Request B starts with no account set, and the policy fails closed.

Wrapping each request in a transaction

SET LOCAL only works inside a transaction, so each request needs one. A small module keeps the transaction and the setting together:

# app/models/tenant_context.rb
module TenantContext
    def self.with(account_id:)
        ActiveRecord::Base.transaction do
            connection = ActiveRecord::Base.connection
            connection.execute(
            "SET LOCAL app.account_id = #{connection.quote(account_id.to_s)}"
            )

            yield
        end
    end
end

Since SET LOCAL doesn’t accept bind parameters, the value has to be part of the SQL string. Always pass it through connection.quote, which escapes it properly. Plain string interpolation here would open a SQL injection hole in the one place you’re trying to keep tenants apart.

Then an around_action wraps every controller action:

class ApplicationController < ActionController::Base
    before_action :authenticate
    around_action :scope_to_account

    private

    def scope_to_account(&action)
        TenantContext.with(account_id: Current.account.id, &action)
    end
end

Callbacks run in the order they’re declared, so authentication happens first, then the rest of the action, including rendering the view, runs inside the transaction with the account set. Views that lazily load records are covered too.

The same helper works anywhere else you need tenant context, like a Rails console session:

TenantContext.with(account_id: 42) do
    Invoice.where(status: "open").count
end

Finding the account before the account is set

There’s a chicken-and-egg problem hiding in that controller. To set the account, you have to look up the user and their account, and that lookup happens before the context exists.

The usual answer is to keep the tables you need for authentication, like users, sessions, and accounts, out of the tenant policies, or give them policies that don’t depend on app.account_id. If those tables do need protection, a small, carefully written database function can do the lookup. That’s the subject of the post on SECURITY DEFINER later in the series.

What a request-wide transaction changes

Running the whole request in one transaction is what makes SET LOCAL safe, but it changes a few things you’re used to in Rails:

  • Errors roll back everything. If a request saves a record and then raises an exception later, the save is rolled back too. That’s usually what you want, but it’s worth knowing.
  • after_commit callbacks wait for the request to finish. Model saves inside the request no longer commit on their own, so after_commit callbacks, including jobs enqueued from them, run when the whole request commits.
  • ActiveRecord::Rollback in a nested transaction is ignored. A transaction block inside the request joins the outer one. Raising ActiveRecord::Rollback inside it won’t roll anything back unless you use transaction(requires_new: true).
  • Slow work holds the transaction open. A request that calls a slow external API keeps its transaction, and any locks it holds, open the whole time. Move slow work to background jobs.
  • Streamed templates run outside it. With template streaming (render stream: true), the view is rendered after the action returns, so the transaction has already ended.

Why not SET with a reset?

Some RLS libraries take a different approach. They use a plain SET, set the value every time a connection is checked out of the pool, and reset it when the work is done. That’s a reasonable design, and it has one real advantage: there’s no request-wide transaction, so none of the changes in the previous section apply.

I still default to SET LOCAL for two reasons. With SET LOCAL, a failure fails closed: if something goes wrong, like a missed setup or a code path that uses the connection outside the normal flow, the next user of that connection doesn’t inherit the previous account. Also, session-level settings don’t work with PgBouncer’s transaction pooling.

If you do use session-level settings, don’t rely only on resetting the value at the end of the request. Set it every time a connection is checked out of the pool, using whatever your app knows about the current request:

ActiveRecord::ConnectionAdapters::AbstractAdapter.set_callback :checkout, :after do |connection|
    account_id = Current.account&.id
    connection.execute("SET SESSION app.account_id = #{connection.quote(account_id.to_s)}")
end

A connection then never starts with a value left over from a previous request. If no account is known yet, the value is cleared, and queries fail closed. Current.account must not need the database, though. If looking it up checks out a connection, the callback runs again and can recurse, so load the account before any connection is checked out, or store just its ID. Keep the reset at the end of the request too, but run it outside any transaction block. A reset inside a transaction that rolls back is undone along with everything else.

Connection poolers like PgBouncer

If you put PgBouncer in front of Postgres, the leak gets worse. In transaction pooling mode, PgBouncer gives your app a real server connection only for the length of a transaction, then hands that connection to whoever needs it next, which might be a different process or even a different app. A plain SET can end up applied to someone else’s queries.

SET LOCAL works correctly with transaction pooling because the setting and the queries that depend on it are in the same transaction, on the same server connection.

Running Rails behind PgBouncer in transaction mode also means turning off prepared statements in database.yml, unless you’re on PgBouncer 1.21 or newer with prepared statement support turned on. Migrations that rely on advisory locks should connect directly to Postgres instead of through PgBouncer.

Troubleshooting

  • “unrecognized configuration parameter” or “invalid input syntax for type bigint”. A query ran without the account set. Usually it’s code that runs outside the around_action, like middleware, an authentication library, or a callback that fires before the controller.
  • Read replicas. If you use connected_to to send reads to a replica, that’s a different connection, and the account is only set on the primary. Set the context on each connection you query.
  • Background jobs. Jobs don’t go through your controller, so they start with no account set. They need their own approach, which is the subject of Part 5.
  • Tests. Rails wraps each test in a transaction, so a SET LOCAL in a test lasts until the test finishes. That’s convenient, but it means tests won’t catch code that forgets to set the account inside its own transaction. Part 7 covers how to test this properly.

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
  3. Setting tenant context per request with SET LOCAL (this post)
  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 your app sets tenant context with a plain SET, or you’re not sure what happens to it between requests, I’d be glad to take a look. I can review how your app handles tenant context or help you set it up safely. Get in touch.

Related blogs

Your RLS Policies Might Not Be Doing Anything

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.
Read in 7 minutes

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