agentleFS
bybren-llcbybren-llc/safe-agentic-workflow/.agents/skills/rls-patterns/SKILL.md

rls-patterns

Skill419 starsChanged 4 months agoMITView on GitHub

Row Level Security patterns for database operations. Use when writing any database query, creating API routes that access data, implementing webhooks that write to the database, or working with user data. Enforces withUserContext, withAdminContext, or withSystemContext helpers. NEVER use direct ORM/DB calls without RLS context wrappers.

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

3 rules. About 0 are common, 3 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use for: All user-facing operations

    line 70
  2. Distinctive:

    Always test with the application-level DB user role (not a superuser):

    line 149
  3. Distinctive:

    Linting Rules: Check linting config for direct DB call enforcement

    line 211

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

RLS Patterns Skill

TEMPLATE: This skill uses {{PLACEHOLDER}} tokens. Replace with your project values before use.

Purpose

Enforce Row Level Security (RLS) patterns for all database operations. This skill ensures data isolation and prevents cross-user data access at the database level.

When This Skill Applies

  • Writing any database query (ORM or raw SQL)
  • Creating or modifying API routes that access the database
  • Implementing webhook handlers that write to the database
  • Working with user data, payments, subscriptions, or enrollments
  • Accessing admin-only tables

Critical Rules

NEVER Do This

// FORBIDDEN - Direct DB calls bypass RLS
const user = await db.user.findUnique({ where: { user_id } });

// FORBIDDEN - No context set
const payments = await db.payments.findMany();

Linting will block direct DB calls. See linting configuration for enforcement rules.

ALWAYS Do This

import {
  withUserContext,
  withAdminContext,
  withSystemContext,
} from "{{RLS_IMPORT}}";

// CORRECT - User context for user operations
const user = await withUserContext(db, userId, async (client) => {
  return client.user.findUnique({ where: { user_id: userId } });
});

// CORRECT - Admin context for admin operations
const webhooks = await withAdminContext(db, userId, async (client) => {
  return client.webhook_events.findMany();
});

// CORRECT - System context for webhooks/background tasks
const event = await withSystemContext(db, "webhook", async (client) => {
  return client.webhook_events.create({ data: eventData });
});

Context Helper Reference

withUserContext(db, userId, callback)

Use for: All user-facing operations

  • User profile access
  • Payment history
  • Subscription management
  • Enrollments and personal data
const payments = await withUserContext(db, userId, async (client) => {
  return client.payments.findMany({ where: { user_id: userId } });
});

withAdminContext(db, userId, callback)

Use for: Admin-only operations (requires admin role)

  • Viewing all webhook events
  • Managing disputes
  • Accessing payment failures
const disputes = await withAdminContext(db, adminUserId, async (client) => {
  return client.disputes.findMany();
});

withSystemContext(db, contextType, callback)

Use for: Webhooks and background jobs

  • Webhook handlers (Stripe, auth provider, etc.)
  • Background job processing
  • System-initiated operations
await withSystemContext(db, "webhook", async (client) => {
  await client.payments.create({ data: paymentData });
});

Admin Pages: Force Dynamic Rendering

CRITICAL: Admin pages using RLS queries MUST force runtime rendering (in Next.js):

// REQUIRED - RLS context unavailable at build time
export const dynamic = "force-dynamic";

async function getAdminData() {
  return await withAdminContext(db, userId, async (client) => {
    return client.someTable.findMany();
  });
}

Without forced dynamic rendering, frameworks may try to pre-render at build time, causing "permission denied" errors.

Protected Tables

User Data Tables (User Isolation)

TablePolicy TypeAccess
userUser isolationOwn data only
paymentsUser isolationOwn payments only
subscriptionsUser isolationOwn subscriptions only
invoicesUser isolationOwn invoices only

Admin/System Tables (Role-Based)

TablePolicy TypeAccess
webhook_eventsAdmin+SystemAdmins and webhooks only
disputesAdmin onlyAdmins only
payment_failuresAdmin onlyAdmins only

Testing Requirements

Always test with the application-level DB user role (not a superuser):

# Basic RLS functionality test
{{RLS_TEST_COMMAND}}

# Comprehensive security validation
{{RLS_VALIDATION_COMMAND}}

Common Patterns

API Route with User Context

import { NextResponse } from "next/server";
import { requireAuth } from "{{AUTH_IMPORT}}";
import { withUserContext } from "{{RLS_IMPORT}}";
import { db } from "{{DB_IMPORT}}";

export async function GET() {
  const { userId } = await requireAuth();

  const payments = await withUserContext(db, userId, async (client) => {
    return client.payments.findMany({
      where: { user_id: userId },
      orderBy: { created_at: "desc" },
    });
  });

  return NextResponse.json(payments);
}

Webhook Handler with System Context

import { withSystemContext } from "{{RLS_IMPORT}}";
import { db } from "{{DB_IMPORT}}";

export async function POST(req: Request) {
  // Verify webhook signature first...

  await withSystemContext(db, "webhook", async (client) => {
    await client.webhook_events.create({
      data: {
        event_type: event.type,
        payload: event.data,
        processed_at: new Date(),
      },
    });
  });

  return new Response("OK", { status: 200 });
}

Authoritative References

  • RLS Implementation Guide: docs/database/RLS_IMPLEMENTATION_GUIDE.md
  • RLS Policy Catalog: docs/database/RLS_POLICY_CATALOG.md
  • Migration SOP: docs/database/RLS_DATABASE_MIGRATION_SOP.md
  • Linting Rules: Check linting config for direct DB call enforcement
  • RLS Context Helpers: {{RLS_CONTEXT_FILE}}

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.