Skip to content

docs(database): correct the RLS guide and close its remaining gaps - #49274

Closed
czenko wants to merge 7 commits into
masterfrom
docs/rls-guide-corrections
Closed

czenko wants to merge 7 commits into
masterfrom
docs/rls-guide-corrections

Conversation

@czenko

@czenko czenko commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #49017. Review that first.

Problem

The build-docs-002-rls-guide eval points an agent at this guide with a vibe-coder prompt that never says RLS, policy, role, or test. Grants, policies, access probes, indexes, and security-definer placement all pass now. Three checks still fail, and they have failed on every recorded run:

Check What it measures Why it failed
pgTAP test file(s) written under supabase/tests/ Any .sql file exists The agent never wrote one.
supabase test db runs at least 8 assertions and all pass The suite runs, ≥8 assertions, none failing Nothing to run. The guide's only example was plan(4), below the floor even if copied perfectly.
tests assert allow and deny per operation on the seeded tables, for anon and authenticated LLM judge on coverage Never reached the judge: "no test files to review".

The guide already had a Test your policies section, so this isn't a strength problem. It's a placement problem. Agents don't read the page — they fetch it through an LLM extraction guided by their own query, and that query asked for enabling RLS, policy syntax, auth.uid(), indexes, and security definer functions. It never mentioned tests. A separate testing section never enters the extract, so more testing prose cannot reach the agent.

Separately, a claim-by-claim check against the RLS basics and RLS performance skill references and the Supacademy RLS course found inaccuracies and three uncovered failure modes.

Solution

Testing is now a step of the procedure, not advice at the end

Secure a table with RLS already opened by saying a table isn't secured until the suite passes, but the procedure underneath it ended on grant. A reader following the numbered steps finished without ever being told to write a test.

  • Lock down the table gains step 4: supabase test new <table>_rls.test, then supabase test db. The procedure now ends on a passing suite.
  • The two worked examples each carry their test file inline, so a test file rides along in the extracts an agent actually pulls — one after the enable/revoke/grant block, one after the four create policy examples.
  • Test your policies shrinks to creating and running the files. It no longer carries content that has to survive extraction.
  • Each file leads with its own path as a comment, so it survives if the fence metadata is dropped.

How that maps to the three checks

Check Addressed by
Test files written A complete test file now sits inside both of the extracts the agent's own query pulls, and step 4 of the procedure names the command that creates one.
≥8 assertions, all passing announcements_rls.test.sql is plan(8) and profiles_rls.test.sql is plan(12). Either file alone meets or clears the floor; together they are 20. Both were run — see below.
Coverage judge profiles asserts allow and deny for all four operations. Allowed writes use returning + results_eq, so they prove state changed rather than that nothing raised. using-filtered denials use is_empty, asserting the row is unchanged rather than that an error was raised — the case the rubric explicitly fails suites for getting wrong. Both files switch role with set local role and identity with set local request.jwt.claim.sub, and cover anon as well as authenticated.

What this does not do: the judge requires assertions naming every seeded table in its fixture. A guide can't know those. It teaches two shapes — owner-private and public-read — and says to repeat the file for every table you secure, including member and non-member cases for shared tables. The agent still has to generalize.

Corrections

Permissive vs restrictive combination, force row level security and who it doesn't apply to, revoking execute on helper functions without breaking the policy that calls them, null = user_id being unknown rather than false, updates needing a select policy, auth.jwt() returning jsonb, views running with owner rights, composite index leading columns, and updateUser().

The worst one: the team membership policy never ran at all. team_id in (select auth.jwt() -> 'app_metadata' -> 'teams') fails at create policy with operator does not exist: uuid = jsonb.

New sections

  • Avoid recursive policies — two tables whose policies read each other raise 42P17. Sharing features produce exactly that shape. Broken with a security definer helper.
  • Materialized views, in Expose a view safely — a materialized view consults no policy, and Postgres rejects both security_invoker and enable row level security on one.
  • Debug a policy — which role ran the query, pg_policies, and separating a hidden row from an absent one.
  • search_path stated as a principle rather than the literal '', which contradicted the event trigger recipe in event-triggers.mdx.
  • Custom claims and RBAC, Storage access control, and Realtime authorization added to Related content.

Verification

Everything asserted here was executed against a local Postgres 17 before being written down.

Claim Result
Both test files run Files=2, Tests=20, Result: PASS
…and aren't vacuous Sabotaging one expected value produced Failed test 2
Published team policy is broken ERROR: operator does not exist: uuid = jsonb, at create policy
Its replacement works Member of a team sees exactly their row; member of none sees zero
Mutually recursive policies fail ERROR: 42P17: infinite recursion detected in policy for relation "lists"
The helper breaks the cycle Member who isn't the owner reads the list; non-member reads nothing
security_invoker on a matview ERROR: unrecognized parameter "security_invoker"
RLS on a matview ERROR: ALTER action ENABLE ROW SECURITY cannot be performed
create policy on a matview ERROR: "mv2" is not a table
A granted matview leaks Non-owner reads 0 rows from the base table, 1 from the matview
search_path = '' resolves pg_catalog format() and current_setting() resolve unqualified

The SQL was re-extracted from the rendered MDX and run again, so the published blocks are the ones that were tested.

Two hypotheses were refuted by running them, and are deliberately not changed: results_eq over INSERT … RETURNING and insert into auth.users (id, email) both work.

The public-read example table is named announcements. It was weather_readings, which matched a fixture table in the eval and coupled the guide to a harness readers can't see.

Manual testing

  1. Open the Row Level Security guide on the preview. Secure a table with RLS opens with a four-step definition of done that ends on supabase test db.
  2. Read Lock down the table. The procedure runs 1–4 and ends on writing and running the test, not on the grant.
  3. Scroll to DELETE policies. The four policies are followed immediately by profiles_rls.test.sql, not by a pointer to a later section.
  4. Check Avoid recursive policies and Debug a policy appear in the table of contents under RLS reference.
  5. Open the markdown version, which is what agents fetch. Both test files are present, each leading with its path.

czenko and others added 6 commits August 19, 2026 12:29
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.

- Group into Understand Row Level Security, Secure a table with RLS, and
  RLS reference, with a navigation intro. Headings are demoted rather
  than renamed wherever anything links to them, so every inbound anchor
  survives.
- Merge the four policy sections. They repeated the same 10-line create
  table and enable RLS block, burying the clause that differed. One setup
  block now precedes four short policy examples.
- Move the auto-enable event trigger recipe out to event-triggers.mdx. It
  was 70 lines of advanced recipe sitting before the reader saw a policy.
- Relocate the "auth.uid() returns null" caution, which was stranded
  inside that event trigger section, 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.

765 lines to 582. 30 headings to 25.

Co-Authored-By: Claude Opus 5 <[email protected]>
The Example trigger function - auto enable Row Level Security section
existed, but its entire body was a link back to the RLS guide, where the
recipe sat as 70 lines of advanced material a reader passed on the way to
their first policy. The recipe belongs with the other event trigger
examples.

Two changes to the recipe itself, from review:

- Re-raise after logging, so a table whose RLS could not be enabled
  aborts the DDL transaction instead of being created unprotected.
- Say that the trigger applies only to tables created after it is
  installed. Existing tables still need RLS enabled by hand.

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

The #rls-performance-recommendations anchor went away when tuning split
into its own guide, so the Grafana entry linked to nothing. Also restores
the missing verb in that bullet.

Two fixes in the performance guide, from review:

- Await the two client query examples. Destructuring the result of
  .select() without awaiting yields the builder, not the response.
- Qualify the join policy's outer team_id. Unqualified, it binds to
  team_user.team_id, which makes the predicate a tautology and the
  example a no-op.

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

Checked the restructured guide claim by claim against the
supabase-postgres-best-practices skill references, the Supacademy RLS
course, and Postgres itself. Corrections:

- Permissive policies OR together; a restrictive policy ANDs and only
  narrows access a permissive policy already granted. The MFA example
  used `as restrictive` without ever saying what it meant.
- Table owners skip RLS unless forced, and `force row level security`
  still does not apply to superusers or roles with `bypassrls`. On
  Supabase `postgres` is not a superuser but does have `bypassrls`, so
  the SQL Editor skips policies even after forcing them.
- Revoke `execute` on helper functions from `public`, then grant `usage`
  and `execute` to the role the policy uses. Policy expressions run as
  the caller, so revoking from that role breaks the policy. New
  functions grant `execute` to `public` by default.
- `null = user_id` is unknown, not false. Prefer `to authenticated` over
  an `is not null` guard.
- An update that reads the row needs a matching select policy. That is
  most updates, not only Data API ones.
- `auth.jwt()` returns claims as jsonb, not the token string.
- Views run with owner rights because `security_invoker` defaults to
  false, not because Postgres marks them `security definer`.
- A composite primary key leads with its first column, so a filter on a
  later column still needs its own index. Dropped the claim that
  Postgres can never use a non-leading column.
- `supabase.auth.update()` is not a method. It is `updateUser()`.
- The team policy `team_id in (select auth.jwt() -> 'app_metadata' ->
  'teams')` does not run at all. It fails at create policy with
  `operator does not exist: uuid = jsonb`. Replaced with the jsonb
  containment operator, which was verified against a live database.

Co-Authored-By: Claude Opus 5 <[email protected]>
The guide had a Test your policies section and agents still wrote no
tests. The reason is how they read the page: the fetch runs an LLM
extraction guided by the agent's own query, and that query asks about
enabling RLS, policy syntax, and auth.uid(). A separate testing section
never enters the extract, so more testing prose cannot help.

Put the test files in the examples the extract already carries instead.

- The public-read example gains its policy and the matching
  weather_readings_rls.test.sql, so the enable-RLS extract carries a test
  file.
- The four policy examples are followed immediately by
  profiles_rls.test.sql, covering allow and deny for every operation,
  with `returning` proving an allowed write changed state and `is_empty`
  proving a using-filtered write matched nothing.
- The security definer example says to add member and non-member cases
  to that table's file.
- Test your policies shrinks to creating and running the files. The
  later, skippable example is gone.

Each file leads with its path as a comment, so it survives if the fence
metadata is dropped.

Both test files were run against a local stack on the schema this guide
prescribes: Files=2, Tests=20, Result: PASS.

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

Three gaps the guide left open, each one a failure mode the eval or a
reference source treats as core. Every statement below was run against a
local Postgres 17 before being written down.

- Avoid recursive policies. Two tables whose policies read each other
  raise 42P17 and the query fails outright. Sharing features produce the
  shape: a policy on lists reads list_members, and a policy on
  list_members reads lists. The section shows the cycle and breaks it with
  a security definer helper, which reads membership as its owner so the
  second policy never runs.

- Materialized views. Expose a view safely covered views only. A
  materialized view stores its own copy of the rows, so it consults no
  policy, and Postgres rejects both security_invoker and enable row level
  security on one. Granting select hands the client every row it holds.

- Debug a policy. Which role actually ran the query, pg_policies for the
  policy set, a privileged read against the client's read to separate a
  hidden row from an absent one, and grants before rewriting anything.

Also states the search_path rule as a principle rather than a literal
value. It said to set search_path = '' on every security definer
function, which the event trigger recipe in event-triggers.mdx does not
do. Pinning to any schema callers cannot write to is what makes it safe,
and '' still resolves pg_catalog, which Postgres always searches.

Adds Custom claims and RBAC, Storage access control, and Realtime
authorization to Related content. RLS behaves differently in the last two
and the guide never said where to look.

Co-Authored-By: Claude Opus 5 <[email protected]>
@czenko
czenko requested a review from a team as a code owner August 19, 2026 21:22
@vercel

vercel Bot commented Aug 19, 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 19, 2026 9:46pm
6 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 19, 2026 9:46pm
design-system Skipped Skipped Aug 19, 2026 9:46pm
studio-self-hosted Skipped Skipped Aug 19, 2026 9:46pm
studio-staging Skipped Skipped Aug 19, 2026 9:46pm
ui-library Skipped Skipped Aug 19, 2026 9:46pm
zone-www-dot-com Skipped Skipped Aug 19, 2026 9:46pm

Request Review

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f5b4af04-a47e-4910-8d6d-8273ca773295

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

Secure a table with RLS opens by saying a table is not secured until the
suite passes, but the procedure underneath it stopped at the grant. A
reader following the numbered steps finished without being told to write
the test. Adds it as step 4, with the two commands.

Also renames the public-read example table from weather_readings to
announcements. The old name matched a fixture table in the RLS docs eval,
which coupled the guide to a test harness readers can't see.

Both test files were re-run after the rename: Files=2, Tests=20,
Result: PASS.

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

Break the cycle with a [security definer function](#use-security-definer-functions). It reads the membership table as its owner, so the second policy never runs and there's nothing to recurse into:

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.

🚫 [rdjsonl] reported by reviewdog 🐶
[Rule003Spelling] Word not found in dictionary: recurse (configure rule at supa-mdx-lint/Rule003Spelling.toml)

3. Compare a privileged read against the client's read. If a [secret key](/docs/guides/getting-started/api-keys) returns the row and `authenticated` doesn't, the row exists and a policy is hiding it. If neither returns it, the row isn't there and the policy is not your problem.
4. Check the grants before rewriting anything. A missing grant raises `42501` before any policy runs. See [Grants and policies](#grants-and-policies).

An empty array from the Data API is not proof that no matching row exists. See [Why is my select returning an empty data array?](/docs/guides/troubleshooting/why-is-my-select-returning-an-empty-data-array-and-i-have-data-in-the-table-xvOPgx) for the same problem from the client side.

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.

🚫 [rdjsonl] reported by reviewdog 🐶
[Rule004ExcludeWords] Don't use singular first person. (configure rule at supa-mdx-lint.config.toml)

Suggested change
An empty array from the Data API is not proof that no matching row exists. See [Why is my select returning an empty data array?](/docs/guides/troubleshooting/why-is-my-select-returning-an-empty-data-array-and-i-have-data-in-the-table-xvOPgx) for the same problem from the client side.
An empty array from the Data API is not proof that no matching row exists. See [Why is select returning an empty data array?](/docs/guides/troubleshooting/why-is-my-select-returning-an-empty-data-array-and-i-have-data-in-the-table-xvOPgx) for the same problem from the client side.

Base automatically changed from docs/rls-restructure to master August 19, 2026 21:51
@czenko

czenko commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Split into #49276 (go-to-green: tests in the procedure) and #49277 (technical corrections), so the eval-facing change can land on its own.

The union of the two is byte-identical to this PR's tree. Closing.

@czenko czenko closed this Aug 19, 2026
@czenko
czenko deleted the docs/rls-guide-corrections branch August 19, 2026 21:53
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.

1 participant