Skip to content

docs(database): close the RLS guide gaps the eval flagged - #49011

Merged
czenko merged 8 commits into
masterfrom
docs/rls-revision
Aug 17, 2026
Merged

czenko merged 8 commits into
masterfrom
docs/rls-revision

Conversation

@czenko

@czenko czenko commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Closes DOCS-1274

Problem

The build-docs-002-rls-guide eval points an agent at the Row Level Security guide with a vibe-coder prompt that never says RLS, policy, role, or test. It failed 6 of 35 checks. Each failure traces to something the guide doesn't say.

  • Grants. anon kept insert, update, and delete on all four to-do tables. Both client roles kept writes on the weather feed. 24 privileges untouched.
  • Indexes. Missing on list_members.user_id. The agent indexed the other three, so it missed the composite-primary-key case specifically.
  • Tests. No pgTAP files. Result: NOTESTS, so the coverage judge never ran.

Solution

  • Add a Grants and policies section.
  • Rewrite the opening danger admonition around revoke-then-grant. It previously showed grant only, which reads as though privileges start from nothing.
  • Drop the (or primary keys) carve-out from Add indexes. A column counts as indexed only when it leads a btree index, shown with a composite-primary-key example.
  • Add a Test your policies section. Covers file location under supabase/tests/, supabase test db, role and identity switching, which assertion matches which denial, and an 11-assertion example spanning allow and deny for all four operations across anon and authenticated.

Used the supacademy RLS course as a second reference. Its framing of grants running before RLS shaped the new section.

Manual testing

  1. Open the Row Level Security guide on the preview. Grants and policies and Test your policies appear in the table of contents.
  2. Select the Grants and policies link at the end of the first admonition. It jumps to the new section.
  3. Open the markdown version, which is what agents fetch. Both new sections and the revised Add indexes text are present.
  4. From apps/docs, run pnpm lint:mdx. The 4 warnings on this file match master, with no new ones.

Summary by CodeRabbit

Documentation

  • Clarified that exposed tables must enable row-level security.
  • Explained the distinction between database grants and row-level security policies.
  • Added least-privilege examples for client roles, including read-only access.
  • Added pgTAP testing guidance with a complete profiles example.
  • Clarified that composite indexes support policy filters only on their leading columns.

The build-docs-002-rls-guide eval failed six checks. Each one traces to
something the guide doesn't say.

- Grants. Add a "Grants and policies" section and rewrite the opening
  admonition around revoke-then-grant. The guide only ever showed grant,
  so agents left anon holding insert, update, and delete.
- Indexes. Drop the "(or primary keys)" carve-out and explain that a
  column is indexed only when it leads a btree index, with a composite
  primary key example.
- Tests. Add a "Test your policies" section covering pgTAP file location,
  supabase test db, role and identity switching, and which assertion
  matches which denial.

Co-Authored-By: Claude Opus 5 <[email protected]>
@vercel

vercel Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
docs Ready Ready Preview, v0 Aug 12, 2026 11:19pm
6 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 12, 2026 11:19pm
design-system Skipped Skipped Aug 12, 2026 11:19pm
studio-self-hosted Skipped Skipped Aug 12, 2026 11:19pm
studio-staging Skipped Skipped Aug 12, 2026 11:19pm
ui-library Skipped Skipped Aug 12, 2026 11:19pm
zone-www-dot-com Skipped Skipped Aug 12, 2026 11:19pm

Request Review

@supabase

supabase Bot commented Aug 12, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: efab8849-2f66-4813-899c-134d7d65b24c

📥 Commits

Reviewing files that changed from the base of the PR and between 9f09f40 and e3975f7.

📒 Files selected for processing (1)
  • apps/docs/content/guides/database/postgres/row-level-security.mdx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/docs/content/guides/database/postgres/row-level-security.mdx

📝 Walkthrough

Walkthrough

The RLS guide now documents exposed-table requirements, least-privilege grants, pgTAP tests for roles and policies, and indexing rules for policy filters.

Changes

Row-Level Security Guide

Layer / File(s) Summary
Privilege and policy guidance
apps/docs/content/guides/database/postgres/row-level-security.mdx
The guide requires RLS on exposed tables, separates table grants from policies, and adds role-specific, read-only, and privilege-revocation guidance.
pgTAP RLS testing
apps/docs/content/guides/database/postgres/row-level-security.mdx
The guide adds CRUD tests for anon and authenticated, JWT identity switching, grant and policy errors, filtered writes, and a complete profiles example.
Policy filter indexing
apps/docs/content/guides/database/postgres/row-level-security.mdx
The guide explains sequential-scan risks for unindexed policy filters and B-tree leading-column behavior, including a team_members example.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Mergeability Score: 🔵 Low · up to e3975

The PR adds useful grants, policy-testing, and index guidance, but the revised index rule may overstate when a btree index supports query plans. This is a bounded documentation correctness risk requiring owner awareness or follow-up.

Possibly related issues

  • supabase/supabase#48382 — The guide adds revoke-then-grant examples and least-privilege guidance related to the issue.

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description check ✅ Passed The description clearly explains the problem, solution, testing steps, linked issue, and manual validation, although it does not use every template heading.
Title check ✅ Passed The title clearly identifies the documentation change and its purpose of addressing gaps in the RLS guide.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch docs/rls-revision

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

czenko and others added 3 commits August 12, 2026 14:57
The section ran context, then a procedure, then context again. The 42501
paragraph after the numbered steps broke the action path.

- Move the 42501 explanation up with the other context.
- Put the steps under their own heading so the type boundary is visible.
- Tie the read-only example to step 2 instead of leaving it floating.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit's own rewrite of the admonition carried the italics forward.
CONTRIBUTING allows bold for a term the reader must not miss, not
italics for general emphasis, so a line this PR rewrites should not
leave it in place.

Co-Authored-By: Claude Opus 5 <[email protected]>
The procedure gave SQL with no operating context. CONTRIBUTING asks
procedures to tell the reader where to act.

Names both surfaces, matching column-level-security: the SQL Editor for
a one-off, a migration to keep it reproducible.

Co-Authored-By: Claude Opus 5 <[email protected]>
@czenko
czenko marked this pull request as ready for review August 12, 2026 22:36
@czenko
czenko requested a review from a team as a code owner August 12, 2026 22:36

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/docs/content/guides/database/postgres/row-level-security.mdx (1)

474-475: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Consider setting the JWT claims with the JSON GUC.

request.jwt.claim.sub is the legacy singular setting. auth.uid() still reads it, but apps/docs/content/guides/database/testing.mdx uses the JSON request.jwt.claims setting, and policies that call auth.jwt() read only the JSON form. Setting the JSON form keeps the example aligned with the testing guide and with policies that read other claims.

♻️ Proposed change
 set local role authenticated;
-set local request.jwt.claim.sub = '11111111-1111-1111-1111-111111111111';
+set local "request.jwt.claims" = '{"sub": "11111111-1111-1111-1111-111111111111", "role": "authenticated"}';

Apply the same form at the two later identity switches.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/docs/content/guides/database/postgres/row-level-security.mdx` around
lines 474 - 475, Update the identity setup examples around the authenticated
role and both later identity switches to set the JWT claims through the JSON
request.jwt.claims GUC, matching the format used in the testing guide; preserve
each existing user sub value while ensuring auth.uid() and auth.jwt() read the
configured identity consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/docs/content/guides/database/postgres/row-level-security.mdx`:
- Line 566: Update the explanation near the composite-key example to avoid
claiming that PostgreSQL cannot use non-leading columns of a multi-column btree
index. State that such indexes may be used less efficiently, including
whole-index scanning or skip-scan where supported, while preserving the
recommendation to add a dedicated index for user_id.

---

Nitpick comments:
In `@apps/docs/content/guides/database/postgres/row-level-security.mdx`:
- Around line 474-475: Update the identity setup examples around the
authenticated role and both later identity switches to set the JWT claims
through the JSON request.jwt.claims GUC, matching the format used in the testing
guide; preserve each existing user sub value while ensuring auth.uid() and
auth.jwt() read the configured identity consistently.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 37b85cdb-642e-4c84-81fb-66af59af8419

📥 Commits

Reviewing files that changed from the base of the PR and between de39dda and f052165.

📒 Files selected for processing (1)
  • apps/docs/content/guides/database/postgres/row-level-security.mdx

using btree (user_id);
```

A column counts as indexed only when it comes first in a `btree` index. Postgres can't use a multi-column index to filter on a column that isn't the leading one, so a composite primary key indexes its first column and no others. A membership table keyed on `(team_id, user_id)` has no index on `user_id`:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Soften the claim about non-leading index columns.

Postgres can use a multi-column btree index for a non-leading column. It scans the whole index instead of descending it, so the plan is much slower than a dedicated index. Recent versions can also skip-scan the leading column. The current wording states an absolute that is not correct, and the practical advice stays the same.

📝 Proposed wording
-A column counts as indexed only when it comes first in a `btree` index. Postgres can't use a multi-column index to filter on a column that isn't the leading one, so a composite primary key indexes its first column and no others. A membership table keyed on `(team_id, user_id)` has no index on `user_id`:
+Treat a column as indexed only when it comes first in a `btree` index. Postgres can filter on a non-leading column of a multi-column index, but it scans the whole index instead of descending it, so a composite primary key gives efficient lookups on its first column only. A membership table keyed on `(team_id, user_id)` needs its own index for policies that filter on `user_id`:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
A column counts as indexed only when it comes first in a `btree` index. Postgres can't use a multi-column index to filter on a column that isn't the leading one, so a composite primary key indexes its first column and no others. A membership table keyed on `(team_id, user_id)` has no index on `user_id`:
Treat a column as indexed only when it comes first in a `btree` index. Postgres can filter on a non-leading column of a multi-column index, but it scans the whole index instead of descending it, so a composite primary key gives efficient lookups on its first column only. A membership table keyed on `(team_id, user_id)` needs its own index for policies that filter on `user_id`:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/docs/content/guides/database/postgres/row-level-security.mdx` at line
566, Update the explanation near the composite-key example to avoid claiming
that PostgreSQL cannot use non-leading columns of a multi-column btree index.
State that such indexes may be used less efficiently, including whole-index
scanning or skip-scan where supported, while preserving the recommendation to
add a dedicated index for user_id.

revoke all on table <schema_name>.<table_name> from anon, authenticated;

-- Grant back only what each role needs.
grant select on table <schema_name>.<table_name> to anon, authenticated;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The contributing guide states to prefer lowercase.
"Prefer lowercase for SQL. For example, select * from table rather than SELECT * FROM table."

czenko and others added 4 commits August 12, 2026 16:01
The section explained why policies fail quietly but never told the
reader to write the tests, or when.

- Open with the recommendation, and tie it to the same change that sets
  the grants and creates the policies.
- Point forward from the end of the grants procedure, which a reader
  reaches first.

Co-Authored-By: Claude Opus 5 <[email protected]>
The defaults were a prose sentence listing three roles and four
privileges. A table makes the starting state scannable and adds what
each role should be left with.

Co-Authored-By: Claude Opus 5 <[email protected]>
The assertion guidance sat after the numbered steps, so the reader met
the procedure before the material step 2 depends on.

- Group the role switching, the denial-to-assertion mapping, and the
  returning trick under How policy tests work, above the steps.
- Put the steps under Write and run the tests.
- Soften the recommendation. It reads as guidance now, not a mandate.

Co-Authored-By: Claude Opus 5 <[email protected]>
The section was three tips under a heading, with no opening sentence and
nothing connecting them. It reads as the rubric for step 2, so it now
says so.

- Open with what a test case is, then name the three things that decide
  whether an assertion means anything.
- Label each one and give it a reason, instead of a bare instruction.
- Fold the allowed-write bullet in with `returning`, where it belongs.
- Rename to Anatomy of a policy test, since the old heading promised an
  explanation the body never gave.

Co-Authored-By: Claude Opus 5 <[email protected]>

@nrichers nrichers left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, with some comments. 🚀 Thank you for this first in a series of PRs to fix our RLS guide!

This ordering seems to intersperse sections a bit:

Image

Might be better off as:

...
Policies
Grants and policies
Enabling Row Level Security
Auto-enable RLS for new tables
...


Verdict: Approve

Check Result
CI All 30+ checks pass, including supa-mdx-lint, typecheck, format, Docs E2E
pnpm lint:mdx vs master baseline Same 4 pre-existing marketing-language warnings (lines shifted, no new ones) — matches PR's own claim
Internal links All resolve: #revoke-default-privileges anchor exists in securing-your-api.mdx, extensions/pgtap.mdx, database/testing.mdx, deployment/database-migrations.mdx all exist
pgTAP example correctness insert into auth.users (id, email) and set local role / set local request.jwt.claim.sub pattern matches the canonical example already in local-development/testing/overview.mdx — not a new/unverified pattern
Assertion count select plan(11) matches 11 actual assertions in the test body
Composite-index/skip-scan claim Accurate for Supabase's currently supported Postgres versions (15/17 per platform/upgrading.mdx) — no Postgres 18 (skip scan) support yet
Grants table Renders as a valid markdown table; column padding is uneven but doesn't affect output
build:guides-markdown Failed locally on an unrelated page (database-advisors.mdx, missing generated JSON) — pre-existing env issue, not caused by this PR

Verified:

  • No regressions vs master: diffed lint output line-by-line, confirmed identical warning set.
  • The new pgTAP test example isn't a novel, unverified pattern — it reuses the exact auth.users seeding and request.jwt.claim.sub role-switching convention from the existing local-development/testing/overview.mdx guide, so it's consistent with what Supabase already documents as working.
  • Grants table and revoke/grant SQL align with the linked securing-your-api.mdx#revoke-default-privileges section, no duplicated/conflicting guidance.

Notes (non-blocking):

  • CodeRabbit left two comments worth addressing in triage, but I'd push back on both:
    • Nitpick (JWT claim format): CodeRabbit suggests switching set local request.jwt.claim.sub to the JSON request.jwt.claims GUC to match "testing.mdx." That file doesn't actually use either form — the real precedent is local-development/testing/overview.mdx, which uses the exact singular form this PR uses. Applying CodeRabbit's suggestion would make this page inconsistent with the existing canonical example rather than more consistent. Recommend leaving as-is.
    • Actionable comment (composite index wording): CodeRabbit wants "Postgres can't use…" softened to acknowledge skip-scan on non-leading btree columns. Skip scan shipped in Postgres 18; Supabase's platform docs only go up to Postgres 17 currently. The stronger claim is accurate for what's actually supported today. Worth revisiting when/if Supabase adds PG 18, not now.
  • Minor cosmetic: the grants table's column values aren't uniformly padded (extra trailing spaces in some cells) — purely cosmetic, no rendering impact, not worth blocking on.

@nrichers nrichers left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, with some comments. 🚀 Thank you for this first in a series of PRs to fix our RLS guide!

This ordering seems to intersperse sections a bit:

Image

Maybe reorder like this?

...
Policies
Grants and policies
Enabling Row Level Security
Auto-enable RLS for new tables
...


Verdict: Approve

Check Result
CI All 30+ checks pass, including supa-mdx-lint, typecheck, format, Docs E2E
pnpm lint:mdx vs master baseline Same 4 pre-existing marketing-language warnings (lines shifted, no new ones) — matches PR's own claim
Internal links All resolve: #revoke-default-privileges anchor exists in securing-your-api.mdx, extensions/pgtap.mdx, database/testing.mdx, deployment/database-migrations.mdx all exist
pgTAP example correctness insert into auth.users (id, email) and set local role / set local request.jwt.claim.sub pattern matches the canonical example already in local-development/testing/overview.mdx — not a new/unverified pattern
Assertion count select plan(11) matches 11 actual assertions in the test body
Composite-index/skip-scan claim Accurate for Supabase's currently supported Postgres versions (15/17 per platform/upgrading.mdx) — no Postgres 18 (skip scan) support yet
Grants table Renders as a valid markdown table; column padding is uneven but doesn't affect output
build:guides-markdown Failed locally on an unrelated page (database-advisors.mdx, missing generated JSON) — pre-existing env issue, not caused by this PR

Verified:

  • No regressions vs master: diffed lint output line-by-line, confirmed identical warning set.
  • The new pgTAP test example isn't a novel, unverified pattern — it reuses the exact auth.users seeding and request.jwt.claim.sub role-switching convention from the existing local-development/testing/overview.mdx guide, so it's consistent with what Supabase already documents as working.
  • Grants table and revoke/grant SQL align with the linked securing-your-api.mdx#revoke-default-privileges section, no duplicated/conflicting guidance.

Notes (non-blocking):

  • CodeRabbit left two comments worth addressing in triage, but I'd push back on both:
    • Nitpick (JWT claim format): CodeRabbit suggests switching set local request.jwt.claim.sub to the JSON request.jwt.claims GUC to match "testing.mdx." That file doesn't actually use either form — the real precedent is local-development/testing/overview.mdx, which uses the exact singular form this PR uses. Applying CodeRabbit's suggestion would make this page inconsistent with the existing canonical example rather than more consistent. Recommend leaving as-is.
    • Actionable comment (composite index wording): CodeRabbit wants "Postgres can't use…" softened to acknowledge skip-scan on non-leading btree columns. Skip scan shipped in Postgres 18; Supabase's platform docs only go up to Postgres 17 currently. The stronger claim is accurate for what's actually supported today. Worth revisiting when/if Supabase adds PG 18, not now.
  • Minor cosmetic: the grants table's column values aren't uniformly padded (extra trailing spaces in some cells) — purely cosmetic, no rendering impact, not worth blocking on.

@czenko

czenko commented Aug 17, 2026

Copy link
Copy Markdown
Contributor Author

Section reordering is in follow-up PRs, so I will leave those notes for later. 😁
Thanks, @nrichers

@czenko
czenko merged commit d2ccbe5 into master Aug 17, 2026
36 checks passed
@czenko
czenko deleted the docs/rls-revision branch August 17, 2026 22:05
@github-actions

github-actions Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1787004615)

Score Average Improvements Regressions
Completeness 99% (+0pp) 1 🟢 1 🔴
Conciseness 47.6% (+2pp) 11 🟢 8 🔴
Docs Faithfulness 59.1% (-5pp) 6 🟢 4 🔴
Goal Completion 84.3% (+0pp) 4 🟢 6 🔴
Knowledge Usage 92.3% (+13pp) 5 🟢 -
Tool Usage 78.3% (+2pp) 2 🟢 1 🔴
Correctness 80% (+5pp) 7 🟢 2 🔴
Safety 95.2% (+10pp) 3 🟢 1 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 97.7% (-2pp) - 1 🔴
URL Validity 100% (+0pp) - -
Time_to_first_token 7.56tok (+2.51tok) - 35 🔴
Llm_calls 6.86 (-0.06) 11 🟢 14 🔴
Tool_calls 2.58 (+0.1) 12 🟢 13 🔴
Errors 0.03 (-0.02) 1 🟢 -
Llm_errors 0 (-0.01) 1 🟢 -
Tool_errors 0.03 (+0) - -
Prompt_tokens 23871.92tok (-239.71tok) 19 🟢 12 🔴
Prompt_cached_tokens 9274.51tok (+414.48tok) 16 🟢 14 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 532.59tok (-1.53tok) 21 🟢 14 🔴
Completion_reasoning_tokens 79.13tok (+0.19tok) 14 🟢 17 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 24404.51tok (-241.25tok) 22 🟢 13 🔴
Estimated_cost 0$ (0$) 15 🟢 14 🔴
Duration 27.43s (+8.41s) - 35 🔴
Llm_duration 18.7s (+4.94s) 3 🟢 32 🔴

czenko added a commit that referenced this pull request Aug 17, 2026
Stacked on #49011. Base is `docs/rls-revision`, so review that one
first.

## Problem

An audit of the Row Level Security guide against
`apps/docs/CONTRIBUTING.md` and `WORD_LIST.md` turned up 4 lint warnings
and 3 things that are wrong rather than just untidy.

- Two SQL examples contradict the guide's own advice. The own-profile
`SELECT` policy has no `TO` clause. The `security definer` example has
no `set search_path`.
- `## Bypassing Row Level Security` says Service Keys bypass RLS, then a
note says Supabase adheres to the signed-in user's policy anyway. The
condition that separates the two is never stated.
- `#using-functions` is linked twice from the RBAC guide and has never
existed on the RLS page.

## Solution

Copy and correctness only. No section moves, no heading renames.

- Replace the italic emphasis on `never` with bold. CONTRIBUTING permits
**bold** for a term the reader must not miss, not italics for general
emphasis. The matching fix for `must` lives in #49011, which rewrites
that line anyway.
- Drop marketing language from the opener, the Supabase intro, and the
policies and performance leads. Removes the idiom "get the hang of them"
and the filler `just`.
- Replace `we` with second person in two places.
- Scope the own-profile `SELECT` example with `to authenticated`.
- Pin `search_path = ''` on the `security definer` example,
schema-qualify its body to match, and state the requirement in prose.
- State when a Service Key actually bypasses RLS.
- Repoint the two RBAC links to `#use-security-definer-functions` and
`#helper-functions`.

`supa-mdx-lint` on the RLS guide goes from 4 warnings to 0.

## Manual testing

1. Open the [Row Level Security
guide](https://docs-git-docs-rls-copy-fixes-supabase.vercel.app/docs/guides/database/postgres/row-level-security)
on the preview. The own-profile SELECT example shows `to authenticated`,
and the security definer example shows `set search_path = ''`.
2. Open the [RBAC
guide](https://docs-git-docs-rls-copy-fixes-supabase.vercel.app/docs/guides/api/custom-claims-and-role-based-access-control-rbac)
and select the "RLS helper functions" link near the end. It lands on the
Helper functions section instead of the top of the page.
3. From `apps/docs`, run `pnpm lint:mdx`. The RLS guide reports no
warnings.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Documentation**
- Updated access-control guidance with clearer links for
security-definer functions and RLS helper functions.
- Clarified that exposed tables require Row Level Security (RLS), while
table grants and row policies provide separate controls.
- Added least-privilege and grant-revocation examples, plus explanations
for authorization errors.
- Expanded testing guidance for CRUD policies, identity switching, and
denied operations.
- Improved recommendations for service keys, policy performance,
indexing, and secure function configuration.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: Cursor <[email protected]>
czenko added a commit that referenced this pull request Aug 19, 2026
Stacked on #49015, which is stacked on #49011. Review those first.

## Problem

The Row Level Security guide spent 225 lines and 5 benchmark tables on
performance, 29% of the page. The `RLS Performance and Best Practices`
troubleshooting entry already covers the same six tips with the same
numbers, from the same source. Neither page tells you how to check
whether RLS is your bottleneck in the first place.

Four of the six tips are not tuning advice. Indexes, `select`-wrapping,
role scoping, and `security definer` safety change whether a policy is
correct and safe, not just fast.

## Solution

- Add `guides/database/postgres/row-level-security-performance`. It
carries the client-filter rule, the join-rewrite rule, all 5 benchmark
tables merged into one, and a new `Diagnose whether RLS is the
bottleneck` section: toggle RLS off to confirm it's the cost, then read
the plan under an impersonated role. That diagnostic exists in the
troubleshooting entry and has never been in the guide.
- Keep every rule that affects correctness on the RLS guide, grouped
under `Write policies that scale`. These are also the four the
`build-docs-002-rls-guide` eval grades, and an agent reads the guide
top-down.
- Repoint the Grafana IO troubleshooting entry at the new page.
- Rewrite `More resources` as `Related content`. Every link now says
what it is and when to use it. Adds `Advanced pgTAP testing`, the
deepest RLS testing content in the docs, which nothing here linked.
Drops discussion 14576: locked, mislabeled here as "RLS Guide and Best
Practices" when it is "RLS **Performance** and Best Practices", and
superseded by the troubleshooting entry and this new page.

**Ownership rule** so the two pages don't drift: the RLS guide owns the
rule and the correct form. The performance page owns the measurement and
the optimizer explanation. If a sentence on the performance page tells
you what to write, it belongs on the guide.

Scoped out of this PR: `More resources` was assigned to the restructure
PR in the plan, but the 14576 link is what this PR supersedes, so
leaving it would ship a stale pointer.

## Manual testing

1. Open the [RLS performance
guide](https://docs-git-docs-rls-performance-split-supabase.vercel.app/docs/guides/database/postgres/row-level-security-performance)
on the preview. It appears in the left nav under Database, Access and
security, directly below Row Level Security.
2. Select the three rule links in its intro. Each lands on the matching
section of the RLS guide.
3. Open the [Row Level Security
guide](https://docs-git-docs-rls-performance-split-supabase.vercel.app/docs/guides/database/postgres/row-level-security)
and go to `Write policies that scale`. It holds indexes,
`select`-wrapping, and role scoping, with one link out to the
performance page.
4. Open the [Grafana IO troubleshooting
entry](https://docs-git-docs-rls-performance-split-supabase.vercel.app/docs/guides/troubleshooting/interpreting-supabase-grafana-io-charts-MUynDR)
and select the RLS performance guide link. It lands on the new page.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Documentation**
* Added a dedicated guide for diagnosing and improving PostgreSQL Row
Level Security performance.
* Expanded guidance on indexing, query filters, role targeting, function
usage, and avoiding costly policy joins.
* Updated the Row Level Security guide with streamlined, scalable policy
recommendations and links to related resources.
* Added the new performance guide to the Database documentation
navigation.
* Updated troubleshooting guidance to reference the dedicated
performance guide.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 <[email protected]>
czenko added a commit that referenced this pull request Aug 19, 2026
## Problem

The guide alternated between context, procedure, and reference on almost
every heading. A reader who wanted to write a policy passed through four
context or reference sections to reach one. A reader who wanted the
model had to skip three procedures.

## Solution

- Group into three sections by information type: `Understand Row Level
Security`, `Secure a table with RLS`, and `RLS reference`, with a
navigation intro.
- Merge the four policy sections. They repeated the same setup block,
burying the clause that differed. One setup block now precedes four
short policy examples.
- Move the auto-enable recipe into `event-triggers.mdx`, whose stub
section's entire body was a link back here.
- Relocate the stranded `auth.uid()` caution into the `auth.uid()`
reference.
- Lift the revoke-and-grant procedure out of the danger admonition and
merge it with the two other places that taught `enable row level
security`.
- Point the Grafana IO chart entry at the performance guide. Its
`#rls-performance-recommendations` anchor went away when tuning split
out in #49016.

765 lines to 582. 30 headings to 25.

Headings are demoted rather than renamed wherever anything links to
them. Every inbound anchor in the repo still resolves; the only one
removed, `#auto-enable-rls-for-new-tables`, was referenced solely by the
`event-triggers.mdx` stub this PR replaces.

## Note on the history

Rebuilt from `master` after #49011, #49015, and #49016 merged. The
branch previously carried those 10 commits plus rebase churn against
them.

Rebasing naively would have reverted review feedback from #49016
(`70fa812`), which removed the benchmarks table and the "This guide"
opener from the performance guide. Those are deliberately not restored
here. The only changes to that file are two missing `await`s and a join
predicate that was a tautology while unqualified.

The three PRs stacked on this one (#49268, #49269, #49270) have been
rebased onto the new base.

## Manual testing

1. Open the [Row Level Security
guide](https://docs-git-docs-rls-restructure-supabase.vercel.app/docs/guides/database/postgres/row-level-security)
on the preview. Three top-level sections appear in the table of
contents.
2. Select each link in the intro. All three jump to their section.
3. Open [Event
triggers](https://docs-git-docs-rls-restructure-supabase.vercel.app/docs/guides/database/postgres/event-triggers).
The auto-enable section holds the full recipe instead of a link.
4. Open the [performance
guide](https://docs-git-docs-rls-restructure-supabase.vercel.app/docs/guides/database/postgres/row-level-security-performance).
No benchmarks table, and the three bullets at the top link into the RLS
guide.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Documentation**
* Reworked the Row Level Security guide with clearer guidance on grants,
policies, permissions, performance, testing, views, and secure
functions.
* Added a complete example for automatically enabling RLS on newly
created public tables.
* Improved SQL examples and clarified table references in RLS
performance guidance.
* Corrected grammar in the Grafana chart troubleshooting documentation.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants