Welcome to Nebutra Sailor Docs 🎉
ChangelogIntroductionLicensing
Help Center (External) ↗

Row-Level Security

How PostgreSQL RLS enforces tenant data isolation at the database level, and how Nebutra wires it through Prisma.

Row-Level Security (RLS) is a PostgreSQL feature that restricts which rows a database session can read or write, based on a policy evaluated for each row. Nebutra uses RLS as the primary mechanism for multi-tenant data isolation.

Why RLS instead of application-level filtering

Application-level WHERE tenantId = ? clauses work but have one critical weakness: a missing clause exposes all tenants' data. RLS moves the enforcement to the database engine itself, so even a query with no tenant filter is automatically restricted to the rows the current session is permitted to see.

ApproachEnforcement layerRisk if developer forgets
WHERE tenantId = ?Application codeFull data leak across tenants
Row-Level SecurityPostgreSQL engineQuery returns empty set — safe by default

How withRls works

withRls from @nebutra/tenant returns a Prisma client extension that:

  1. Opens a PostgreSQL transaction
  2. Sets the session-local variable app.current_tenant_id to the provided tenantId
  3. Executes the query — PostgreSQL evaluates RLS policies using this variable
  4. Tears down the session variable on completion
import { db } from "@nebutra/db";
import { getCurrentTenant, withRls } from "@nebutra/tenant";

const tenant = getCurrentTenant();
const tenantDb = withRls(db, tenant.id);

// PostgreSQL enforces: only rows WHERE tenant_id = 'org_abc123'
const projects = await tenantDb.project.findMany();

Under the hood, withRls executes:

SET LOCAL app.current_tenant_id = 'org_abc123';
SELECT * FROM projects;  -- RLS policy filters automatically

Policies are generated, never hand-written

Per ADR 2026-09-25 database convergence, packages/platform/db/prisma/schema.prisma is the only file people edit. Every table's access rule is an /// @rls comment above the model — inferred automatically from a tenantId / organizationId column or a single tenant-scoped parent, or declared explicitly with one of: global | deny | off | self | via(field) | using(sql) | read(sql) write(sql).

A custom Prisma generator (prisma/generators/rls.mjs) turns those annotations into generated/rls.sql on every prisma generate — one policy per table, <table>_rls (or the pair <table>_read / <table>_write), with no TO clause: a policy binds every role that is neither the table owner nor BYPASSRLS.

/// @rls off
model Session {
  id       String @id @default(cuid())
  userId   String
  // ...
}

scripts/lint-database.mjs (wired into pnpm lint) fails the build if CREATE POLICY shows up anywhere outside generated/rls.sql, or if a migration touches a policy, RLS switch, function, grant, or role — migrations are structure-only.

Applying it: pnpm db:deploy

One command, any host — runs prisma migrate deploy, then platform.sql + generated/rls.sql in a single locked transaction, then verifies. It exits non-zero on any pending migration, structural drift from schema.prisma, or a policy that differs from generated/rls.sql.

pnpm db:deploy    # migrate, then apply platform.sql + generated/rls.sql, then verify
pnpm db:check     # the read-only half — reports drift without applying anything

Every deploy workflow runs db:deploy as its first job, before the app deploys — a drifted database stops the deploy rather than shipping code against a schema it doesn't match.

The tenantId column convention

Every table that stores tenant-specific data should include a tenantId (or organizationId) column so its access rule is inferred automatically:

model Project {
  id          String   @id @default(cuid())
  name        String
  tenantId    String                         // ← inferred access rule; no /// @rls needed
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@index([tenantId])                        // ← index required for performance
}

Never omit @@index([tenantId]) on large tables. Without an index, PostgreSQL performs a full sequential scan on every RLS policy check, which degrades query performance significantly as data grows.

Bypassing RLS for administrative operations

Some operations — such as cross-tenant analytics, billing jobs, or admin dashboards — need to query across all tenants. Use a separate database role with BYPASSRLS for these, not the application service role.

// Admin client — bypasses RLS entirely
// ONLY for internal background jobs and admin tooling
export const adminDb = new PrismaClient({
  datasources: {
    db: { url: process.env.DATABASE_ADMIN_URL },
  },
});

Never expose the adminDb client through a user-facing API route. It bypasses all tenant isolation. Restrict it to background workers, cron jobs, and internal admin tooling only.

Performance: indexes on tenantId

RLS policies add a filter on tenant_id to every query. For this to be fast, PostgreSQL needs an index on that column. Always add @@index([tenantId]) in the Prisma schema, which generates:

CREATE INDEX "projects_tenant_id_idx" ON "projects"("tenant_id");

For tables that are almost always queried by both tenantId and another column (e.g. status), use a composite index:

@@index([tenantId, status])

Verifying RLS is active

To confirm a table has RLS enabled and policies applied, run this query in your database:

-- Check RLS status for all tenant-scoped tables
SELECT
  tablename,
  rowsecurity AS rls_enabled,
  forcerowsecurity AS rls_forced
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY tablename;

-- List all policies on a specific table
SELECT policyname, cmd, qual, with_check
FROM pg_policies
WHERE tablename = 'projects';

Using the DB Client

How to use withRls in server components and API routes

Multi-Tenancy

Tenant context, AsyncLocalStorage, and isolation strategy

Schema & Migrations

Adding tenantId columns and indexes in migrations

Database Overview

Architecture, schemas, and key models

How is this guide?

Edit on GitHub

Last updated on

On this page

Why RLS instead of application-level filtering
How withRls works
Policies are generated, never hand-written
Applying it: pnpm db:deploy
The tenantId column convention
Bypassing RLS for administrative operations
Performance: indexes on tenantId
Verifying RLS is active