Row-Level Security in PostgreSQL: A Second Wall for a Multi-Tenant Laravel App: 08 of 08
How PostgreSQL row-level security backs up a Laravel tenant scope: policies, a per-transaction company setting, the roles that silently bypass it, a guard test, and the real costs of adding it.
Imagine a developer on call who opens a database console on production to answer a quick question: what is the total of the invoices issued this month? She types the query, gets a number, and it is the sum for every company in the system. Nothing went wrong in the Laravel app. The global scope from the first article of this series is doing its job. The query just never went through Laravel.
That is the limit of an application-level scope. It protects every query that passes through your Eloquent models, and nothing else: not a console session, not a report script, not a second service reading the same tables, not a raw DB::table() call that slipped through review. PostgreSQL has a feature that moves the rule into the database itself, where every client has to obey it. This article shows how to add it as a second wall behind the scope, what it does and doesn't give you, and when it is not worth the trouble.
What Row-Level Security Does
Row-level security (RLS) lets a table carry policies that decide which rows a role can see or change. Per the PostgreSQL documentation, once you enable it on a table, all normal access must be allowed by a policy. If the table has no policy, a default-deny rule applies and no rows are visible or can be modified. That default is what makes it a good fit for tenancy: forgetting something returns nothing instead of everything.
A policy has a USING expression for the rows you can see, and optionally a WITH CHECK expression for the rows you may write. If you give only USING, PostgreSQL uses the same expression for WITH CHECK. For tenancy that is what you want: a company can neither read nor insert nor move rows that belong to another.
The missing piece is how the database knows which company is asking. It has no idea, unless the application tells it.
Telling the Database Which Company Is Asking
The usual approach is a custom setting, read inside the policy with current_setting(). The application sets it at the start of the unit of work. The detail that decides whether this is safe is how long the setting lives.
If you set it for the whole session, it stays on that connection after your request ends. Laravel apps that run on Octane, or any setup with persistent connections or a connection pooler, reuse connections between requests. The next request on that connection starts with the previous company's id still set, which is the exact leak you were trying to prevent. The safe choice is a setting that is local to the transaction, so that it disappears on commit or rollback. PostgreSQL's set_config(name, value, true) does that, and it only works inside a transaction.
In the TenantContext from the first article, that means runAs opens a transaction and sets the value in it. It also puts the previous value back on the way out, so that nested calls and tests that wrap everything in a transaction don't inherit a stale company:
public function runAs(int $companyId, Closure $callback): mixed
{
$previous = $this->companyId;
$this->companyId = $companyId;
try {
return DB::transaction(function () use ($companyId, $previous, $callback) {
$this->setDatabaseCompany($companyId);
$result = $callback();
$this->setDatabaseCompany($previous);
return $result;
});
} finally {
$this->companyId = $previous;
}
}
private function setDatabaseCompany(?int $companyId): void
{
DB::select(
"select set_config('app.company_id', ?, true)",
[$companyId === null ? '' : (string) $companyId],
);
}
If the callback throws, the transaction (or the savepoint, when nested) rolls back and the setting goes with it. The cost is already visible: every request and every job now runs inside a transaction.
The Policy Itself
The policy is plain SQL, so it goes in a migration. One per tenant-owned table:
return new class extends Migration
{
public function up(): void
{
DB::statement('ALTER TABLE invoices ENABLE ROW LEVEL SECURITY');
DB::statement('ALTER TABLE invoices FORCE ROW LEVEL SECURITY');
DB::statement(<<<'SQL'
CREATE POLICY company_isolation ON invoices
USING (company_id = NULLIF(current_setting('app.company_id', true), '')::bigint)
SQL);
}
public function down(): void
{
DB::statement('DROP POLICY company_isolation ON invoices');
DB::statement('ALTER TABLE invoices NO FORCE ROW LEVEL SECURITY');
DB::statement('ALTER TABLE invoices DISABLE ROW LEVEL SECURITY');
}
};
Two details in the expression. The true in current_setting('app.company_id', true) tells PostgreSQL to return NULL instead of raising an error when the setting was never defined. And NULLIF(..., '') covers a setting that was defined earlier and later cleared: it can read back as an empty string, and casting an empty string to bigint raises an error. Either way, with no company set, the comparison is never true and the query sees no rows.
The policy only looks at the current row's own column. That is deliberate. The documentation calls policies that consider only current row values the simplest and best-performing case, and warns that policies which consult other tables can create race conditions that leak information.
The Part That Quietly Disables Everything
This is the section most tutorials skip, and it is where most RLS setups fail without anyone noticing. The documentation lists who is not subject to the policies:
- Superusers and roles with the
BYPASSRLSattribute always bypass row security. - Table owners normally bypass it too, unless the table has
FORCE ROW LEVEL SECURITY.
Now think about a typical Docker development setup. The database image is created with a user that is a superuser, and the Laravel app connects with it. Every policy exists, and none of them applies. Your tests pass, and nothing was ever tested.
The fix is to separate roles, including in development and CI:
-- A separate migration role (created elsewhere) owns the tables and is used only at deploy time.
-- Runtime role: not a superuser, not an owner, no BYPASSRLS.
CREATE ROLE app_runtime LOGIN PASSWORD '<secret>';
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_runtime;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO app_runtime;
The app connects as app_runtime. Migrations run with a different set of credentials, which most deploy pipelines can supply as separate environment variables. FORCE ROW LEVEL SECURITY stays on as a second guard in case somebody connects as the owner by mistake. Future tables need the same grants, so look at ALTER DEFAULT PRIVILEGES for the migration role.
A Guard for the Table You'll Forget
The guard test from the testing article checks that every model with a company_id uses the trait. The database version asks PostgreSQL directly which tenant tables have no row security:
it('has row-level security on every table with a company_id', function () {
$missing = DB::select(<<<'SQL'
select c.relname
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
join pg_attribute a on a.attrelid = c.oid
and a.attname = 'company_id' and not a.attisdropped
where c.relkind = 'r'
and n.nspname = 'public'
and (not c.relrowsecurity or not c.relforcerowsecurity)
SQL);
expect(collect($missing)->pluck('relname')->all())->toBe([]);
});
And a behavioral test that proves the policy works even for code that bypasses Eloquent:
it('hides rows from raw queries outside the right company', function () {
[$a, $b] = twoCompanies();
$tenant = app(TenantContext::class);
$tenant->runAs($a->id, fn () => Invoice::factory()->create());
expect(DB::table('invoices')->count())->toBe(0);
expect($tenant->runAs($b->id, fn () => DB::table('invoices')->count()))->toBe(0);
expect($tenant->runAs($a->id, fn () => DB::table('invoices')->count()))->toBe(1);
});
Both tests need PostgreSQL and the non-privileged role. An in-memory SQLite database can't run them.
What RLS Doesn't Solve
It is a second wall, not a replacement for the first, and it has holes of its own.
- Constraints see everything. The documentation says referential integrity checks, such as unique and foreign key checks, always bypass row security. A global unique index on
invoices.numbercan reveal that another company already uses a number, through the error you get. A foreign key can point a row of one company at a parent row of another. Use composite constraints that includecompany_id, for example a unique index on(company_id, number). - Tables without
company_id. Thecompaniestable, users and the membership pivot sit outside this scheme. Their access rules stay in the application. - Legitimate cross-company work. The nightly job that lists every company, or an admin tool that moves a record, can't run under a one-company policy. Give those paths a separate connection that uses a role with
BYPASSRLS, keep it out of the default configuration, and put its call sites on the allowlist from the testing article. - Silence. A forgotten context doesn't raise an error in the database. It returns zero rows. Keep the application's
MissingTenantContextexception, because a loud failure in the app is easier to debug than a page that looks empty.
What It Costs, and When to Pay
The bill is concrete:
- A transaction around every request and job, which holds a connection and its locks longer.
- PostgreSQL only. MySQL has no equivalent, so a project that may run on both can't depend on it.
- Two roles to manage, extra grants, and a migration step for every new tenant table.
- A test and development setup that has to match production's roles, or it proves nothing.
For a small team with one application, the Eloquent scope, the fail-closed exception and the leak tests are usually enough. I would add RLS when more than one thing reads the database (a second service, a BI tool, support staff with console access), when contracts or regulation ask for isolation you can show at the database level, or when the team is large enough that someone will eventually write a raw query. Until then, a good test suite is the cheaper wall.
Conclusion
The on-call developer in the opening got a total across every company because the database trusted whoever was asking. RLS moves that trust out of your code: with it, a query that doesn't say which company it is acting for gets nothing back. It works only if the setting dies with the transaction, the app connects as a role that policies apply to, and a test tells you when a new table skips the policy.
Before deciding, run one experiment: connect to your development database the way the app does and check whether that user is a superuser. If it is, you already know that no policy would be enforced there.