roninforge/roninforge-drizzle/drizzle-rls

Claude Code and agent skill by roninforge/roninforge-drizzle

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Scaffold Postgres Row-Level Security with Drizzle: pgPolicy declarations, enableRLS() (0.45.x) or pgTable.withRLS() (1.0-rc), permissive vs restrictive policies, owner / role / public patterns, setting auth context per request, Supabase + Neon Authorize integration.

Install

npx vskill@latest install roninforge/roninforge-drizzle/drizzle-rls

SKILL.md

The same SKILL.md was published earlier as roninforge/roninforge-drizzle/drizzle-rls.

Scaffold Postgres RLS with Drizzle

When to Use

When designing a multi-tenant or per-user-isolated table on Postgres. Postgres RLS pushes authorization to the database, so a missing WHERE user_id = $1 in application code cannot leak data.

Drizzle has first-class RLS support from 0.32 (primitives) and 0.33 (GA).

Instructions

Step 1: Decide the policy shape

Three common patterns:

PatternMeaningExample
OwnerEach row belongs to one user; only that user can read/writeper-user notes, drafts
TenantEach row belongs to one tenant; any user in that tenant can readshared workspace data
Public-read, owner-writeAnyone can read; only the owner can mutatepublished posts

Pick one before writing the policy.

Step 2: Add the schema with pgPolicy + enableRLS() (0.45.x)
typescript
// src/db/schema/notes.ts
import {
pgTable,
pgPolicy,
integer,
text,
timestamp,
index,
} from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm";
import { authenticatedRole } from "drizzle-orm/supabase"; // or define your own role const
export const notes = pgTable(
"notes",
{
id: integer().primaryKey().generatedAlwaysAsIdentity(),
userId: text().notNull(), // matches auth.uid() type
title: text().notNull(),
body: text().notNull(),
createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
},
(t) => [
index("notes_user_id_idx").on(t.userId),
pgPolicy("owner_select", {
as: "permissive",
for: "select",
to: authenticatedRole,
using: sql`user_id = (auth.uid())::text`,
}),
pgPolicy("owner_insert", {
as: "permissive",
for: "insert",
to: authenticatedRole,
withCheck: sql`user_id = (auth.uid())::text`,
}),
pgPolicy("owner_update", {
as: "permissive",
for: "update",
to: authenticatedRole,
using: sql`user_id = (auth.uid())::text`,
withCheck: sql`user_id = (auth.uid())::text`,
}),
pgPolicy("owner_delete", {
as: "permissive",
for: "delete",
to: authenticatedRole,
using: sql`user_id = (auth.uid())::text`,
}),
],
).enableRLS();

Critical: `.enableRLS()` is required. Adding pgPolicy calls without it does nothing - Postgres only enforces policies on tables where RLS is explicitly enabled.

Step 2 (alternative): v1.0-rc syntax
typescript
// 1.0-rc.1+ moves enableRLS to the constructor
export const notes = pgTable.withRLS("notes", {
id: integer().primaryKey().generatedAlwaysAsIdentity(),
userId: text().notNull(),
title: text().notNull(),
body: text().notNull(),
createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
}, (t) => [
pgPolicy("owner_select", { as: "permissive", for: "select", to: authenticatedRole, using: sql`user_id = (auth.uid())::text` }),
// ... insert / update / delete as above
]);

If your project pins drizzle-orm@1.x, use pgTable.withRLS. Otherwise stay on .enableRLS().

Step 3: Generate the migration
bash
pnpm drizzle-kit generate

The generated SQL should include both ALTER TABLE notes ENABLE ROW LEVEL SECURITY; and CREATE POLICY ... statements. Review the file.

Step 4: Set the auth context per request

Policies are evaluated against auth.uid() (Supabase / Neon Authorize convention). You must set the JWT claims on the connection before queries run:

typescript
// Per-request, before any query
await db.execute(sql`SET LOCAL "request.jwt.claims" = ${JSON.stringify({ sub: userId, role: "authenticated" })}`);
const myNotes = await db.select().from(notes); // RLS-filtered to this user

SET LOCAL scopes the change to the current transaction. Wrap your request handler in a transaction so the setting is automatically discarded:

typescript
await db.transaction(async (tx) => {
await tx.execute(sql`SET LOCAL "request.jwt.claims" = ${JSON.stringify(claims)}`);
return tx.select().from(notes);
});

For Supabase, the platform sets these for you when you use the supabase-js client server-side. For Neon Authorize, the same. For self-hosted Postgres, write the middleware yourself.

Step 5: Test the policies

Use Testcontainers Postgres + the per-test-transaction-rollback pattern:

typescript
// tests/notes-rls.test.ts
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { db } from "./setup";
import { notes } from "../src/db/schema/notes";
import { sql } from "drizzle-orm";
// asUser sets the RLS auth context for the duration of `fn` and lets the
// caller decide whether to commit or roll back. There is NO automatic rollback
// here - RLS isolation tests need rows that survive across multiple `asUser`
// calls within a single test, so the helper has to commit by default.
async function asUser<T>(userId: string, fn: (tx: typeof db) => Promise<T>): Promise<T> {
return await db.transaction(async (tx) => {
await tx.execute(sql`SET LOCAL "request.jwt.claims" = ${JSON.stringify({ sub: userId, role: "authenticated" })}`);
return await fn(tx as typeof db);
});
}
describe("notes RLS", () => {
// Truncate after each test so committed rows do not leak.
afterEach(async () => {
await db.execute(sql`TRUNCATE TABLE notes RESTART IDENTITY CASCADE`);
});
it("alice cannot see bob's notes", async () => {
await asUser("alice", async (tx) => {
await tx.insert(notes).values({ userId: "alice", title: "a", body: "x" });
});
await asUser("bob", async (tx) => {
await tx.insert(notes).values({ userId: "bob", title: "b", body: "y" });
});
await asUser("alice", async (tx) => {
const rows = await tx.select().from(notes);
expect(rows.map(r => r.title)).toEqual(["a"]);
});
});
it("alice cannot insert as bob (withCheck blocks)", async () => {
await expect(
asUser("alice", async (tx) => {
await tx.insert(notes).values({ userId: "bob", title: "spoof", body: "x" });
}),
).rejects.toThrow();
});
});
Step 6: Disable bypass for the application role

Postgres roles with BYPASSRLS see every row regardless of policy. The application's connection role should NOT have it.

sql
-- run once per environment
CREATE ROLE app_user;
ALTER ROLE app_user NOBYPASSRLS;
GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;

Application connects as app_user. Migrations and admin tasks connect as a different role with BYPASSRLS (or as the table owner).

Common policy shapes

The snippets below assume authenticatedRole, anonRole, and pgPolicy / sql are already imported at the top of the file (see Step 2 for the full import block).

Tenant isolation
typescript
pgPolicy("tenant_select", {
as: "permissive",
for: "select",
to: authenticatedRole,
using: sql`tenant_id = ((auth.jwt() ->> 'tenant_id')::int)`,
}),

JWT contains the tenant claim. Policy filters every query.

Public-read, owner-write
typescript
pgPolicy("public_select", {
as: "permissive",
for: "select",
to: anonRole, // unauthenticated
using: sql`published = true`,
}),
pgPolicy("owner_modify", {
as: "permissive",
for: "all", // SELECT, INSERT, UPDATE, DELETE
to: authenticatedRole,
using: sql`user_id = (auth.uid())::text`,
withCheck: sql`user_id = (auth.uid())::text`,
}),
Restrictive (additional constraints, AND'ed with permissive)
typescript
pgPolicy("max_5_per_user", {
as: "restrictive",
for: "insert",
to: authenticatedRole,
withCheck: sql`(SELECT count(*) FROM notes WHERE user_id = (auth.uid())::text) < 5`,
}),

Permissive policies are OR'd; restrictive policies are AND'd on top. Use restrictive sparingly - they affect every operation.

Anti-patterns to avoid

  • Forgetting `.enableRLS()` - policies exist but Postgres ignores them silently. Test that bob cannot read alice's rows; if he can, RLS is off.
  • Letting the application role have `BYPASSRLS` - policies become decorative.
  • `SET` instead of `SET LOCAL` - the auth context leaks across requests on the same pooled connection.
  • Per-row checks in app code in addition to RLS - duplication, two sources of truth, eventually one drifts. Trust RLS or trust app code, pick one.
  • Policy `using` clause with mutable functions - using: sqlnow() < expires_at` is fine; using: sqlsome_volatile_func()` is not. Postgres caches policy evaluation aggressively.
  • Skipping `withCheck` on INSERT/UPDATE - using only filters reads; without withCheck a user can write rows tagged with someone else's user_id.

What to ship

  • Schema file with pgPolicy declarations and .enableRLS() (or pgTable.withRLS() on v1).
  • Generated SQL migration that includes ALTER TABLE ... ENABLE ROW LEVEL SECURITY; and CREATE POLICY ....
  • Middleware that sets SET LOCAL "request.jwt.claims" per request inside a transaction.
  • Tests that verify cross-user isolation (the spoofed-userId case).
  • A app_user Postgres role with NOBYPASSRLS for the application connection.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/roninforge/roninforge-drizzle/drizzle-rls/badge)](https://verified-skill.com/skills/roninforge/roninforge-drizzle/drizzle-rls)

Something wrong with this skill or its page? Tell us.