Repository navigation
Conversation
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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
6 Skipped Deployments
|
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
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: |
There was a problem hiding this comment.
🚫 [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. |
There was a problem hiding this comment.
🚫 [rdjsonl] reported by reviewdog 🐶
[Rule004ExcludeWords] Don't use singular first person. (configure rule at supa-mdx-lint.config.toml)
| 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. |
Stacked on #49017. Review that first.
Problem
The
build-docs-002-rls-guideeval 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:pgTAP test file(s) written under supabase/tests/.sqlfile existssupabase test db runs at least 8 assertions and all passplan(4), below the floor even if copied perfectly.tests assert allow and deny per operation on the seeded tables, for anon and authenticatedThe guide already had a
Test your policiessection, 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 RLSalready opened by saying a table isn't secured until the suite passes, but the procedure underneath it ended ongrant. A reader following the numbered steps finished without ever being told to write a test.Lock down the tablegains step 4:supabase test new <table>_rls.test, thensupabase test db. The procedure now ends on a passing suite.create policyexamples.Test your policiesshrinks to creating and running the files. It no longer carries content that has to survive extraction.How that maps to the three checks
announcements_rls.test.sqlisplan(8)andprofiles_rls.test.sqlisplan(12). Either file alone meets or clears the floor; together they are 20. Both were run — see below.profilesasserts allow and deny for all four operations. Allowed writes usereturning+results_eq, so they prove state changed rather than that nothing raised.using-filtered denials useis_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 withset local roleand identity withset local request.jwt.claim.sub, and coveranonas well asauthenticated.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 securityand who it doesn't apply to, revokingexecuteon helper functions without breaking the policy that calls them,null = user_idbeing unknown rather than false, updates needing a select policy,auth.jwt()returning jsonb, views running with owner rights, composite index leading columns, andupdateUser().The worst one: the team membership policy never ran at all.
team_id in (select auth.jwt() -> 'app_metadata' -> 'teams')fails atcreate policywithoperator does not exist: uuid = jsonb.New sections
Avoid recursive policies— two tables whose policies read each other raise42P17. Sharing features produce exactly that shape. Broken with a security definer helper.Expose a view safely— a materialized view consults no policy, and Postgres rejects bothsecurity_invokerandenable row level securityon one.Debug a policy— which role ran the query,pg_policies, and separating a hidden row from an absent one.search_pathstated as a principle rather than the literal'', which contradicted the event trigger recipe inevent-triggers.mdx.Related content.Verification
Everything asserted here was executed against a local Postgres 17 before being written down.
Files=2, Tests=20, Result: PASSFailed test 2ERROR: operator does not exist: uuid = jsonb, atcreate policyERROR: 42P17: infinite recursion detected in policy for relation "lists"security_invokeron a matviewERROR: unrecognized parameter "security_invoker"ERROR: ALTER action ENABLE ROW SECURITY cannot be performedcreate policyon a matviewERROR: "mv2" is not a tablesearch_path = ''resolvespg_catalogformat()andcurrent_setting()resolve unqualifiedThe 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_eqoverINSERT … RETURNINGandinsert into auth.users (id, email)both work.The public-read example table is named
announcements. It wasweather_readings, which matched a fixture table in the eval and coupled the guide to a harness readers can't see.Manual testing
Secure a table with RLSopens with a four-step definition of done that ends onsupabase test db.Lock down the table. The procedure runs 1–4 and ends on writing and running the test, not on the grant.DELETE policies. The four policies are followed immediately byprofiles_rls.test.sql, not by a pointer to a later section.Avoid recursive policiesandDebug a policyappear in the table of contents underRLS reference.