How to Secure Your Supabase Database with Row Level Security Using an AI Agent
How to
2026-11-18
9 min read
Intended first value
You leave with RLS enabled on every exposed table, ownership and tenant policies you can paste in, tests that run as real client roles, and a clear rule for which agent connections respect RLS.
To secure a Supabase database with Row Level Security (RLS) using an AI agent, let the agent do the repetitive work (auditing tables, drafting policies, writing tests) while Postgres does the enforcing. Enable RLS on every exposed table, write the narrowest policies that work, test them as real client roles, and make sure the agent's own connection can't bypass the policies it just wrote. Then keep it that way: Dreambase Observability runs a daily security check on every connected Supabase project and alerts you when a new priority recommendation appears, so a table that ships without RLS gets caught the day it lands, not after a leak.
Why Supabase tables are exposed by default and what RLS actually does
Supabase exposes your database directly to the frontend through its Data API. The anon (publishable) key ships in your JavaScript bundle and is public by design, so holding it proves nothing about who the caller is. Without RLS, anyone with that key and a matching grant can read or write rows through the REST endpoints, skipping your middleware, route guards, and server functions entirely.
This isn't theoretical. In March 2025, researchers scanned 1,645 apps built with Lovable and found 170 of them (10.3%) with missing or inadequate RLS, exposing user data, payment records, and API keys (CVE-2025-48757).
RLS moves the authorization boundary into Postgres. The database evaluates a policy expression for every row a query touches, so access holds no matter which client sends the query. The Data API and Realtime private channels respect it. Anything connecting with the service role key, or as a role with BYPASSRLS, does not.
The silent gap: tables created with SQL ship with RLS off
The Table Editor in the Supabase Dashboard enables RLS by default. The SQL Editor, migrations, and external tools such as ORMs do not. Your app behaves the same whether a table is protected or not, so nothing fails to tell you about the gap. Supabase’s RLS docs include an event trigger that turns RLS on for every new table in the public schema, which is worth installing once.
Grants and policies are separate layers. A grant lets a role run an operation on a table. RLS policies then restrict which rows that operation can see or change. If the table has a grant and RLS is off, every row is exposed. On most existing projects, tables created in public are granted to the Data API roles automatically, so a new table is reachable the moment it lands; Supabase is moving that default so exposure becomes opt-in.
Enabling RLS with no policies flips the default to deny-all: reads return nothing and writes fail for any role subject to RLS. That's the expected intermediate state. Don't "fix" it by switching the app to the service role key.
Views are the other common gap. Postgres creates views as security definer by default, so a view owned by postgres ignores the RLS on its underlying tables. On Postgres 15 and later, create views with security_invoker = true, or keep them out of exposed schemas. Storage follows the same rules: access to private buckets is controlled by policies on storage.objects, while public buckets serve files to anyone with the URL.
Step 1: Enable RLS on every table before writing a single policy
Give the agent your schema (table names and columns) and ask it to generate one ALTER TABLE … ENABLE ROW LEVEL SECURITY; statement for every table in schemas exposed to the API, for example ALTER TABLE public.user_profiles ENABLE ROW LEVEL SECURITY;.
Have it audit the current state first:
Any row with rowsecurity = false is a table the Data API can expose. Don't assume a table is protected because someone created it in the Dashboard. After the statements run, leave the deny-all state in place while you write policies, and open only the access the app needs.
Step 2: Understand USING vs WITH CHECK before writing any policy
USING decides which existing rows an operation can see or touch. WITH CHECK decides whether the new row values an operation writes are allowed.
SELECT:
USINGfilters visible rows.INSERT:
WITH CHECKvalidates the new row; there's no existing row to filter.UPDATE:
USINGlimits which rows can be targeted,WITH CHECKlimits what they can become.DELETE:
USINGlimits which rows can be removed.
Describe intent to the agent in these terms. "Users can update their own posts but can't change the author" needs an ownership test in both USING and WITH CHECK. Review generated policies as a set: multiple permissive policies for the same operation are combined with OR, so one broad policy quietly overrides a narrow one.
Step 3: Write user-scoped ownership policies as the starting point
Start with the smallest permission set that works. In the ownership pattern, a user_id column references auth.users(id) and each policy compares it with (select auth.uid()). Wrapping auth.uid() in a subselect lets Postgres evaluate it once per query instead of once per row. Scope every policy TO authenticated so anonymous callers get nothing from it.
Prompt the agent with the table schema and: "Generate ownership policies for SELECT, INSERT, UPDATE, and DELETE, plus the indexes they need." For user_profiles:
Apply and test the SELECT policy first, then add the write policies one at a time, so an unexpected result points to a single policy. The repeated check isn't redundant: on insert it blocks creating rows for another user, and on update it blocks both editing someone else's row and handing your own row to someone else. Supabase’s docs also note that an UPDATE needs a matching SELECT policy to work as expected. If your app uses anonymous sign-ins, remember that anonymous users get the authenticated role too; check the is_anonymous claim where that matters.
Step 4: Multi-tenant and team-based access for SaaS apps
Ownership can't express "everyone in my organization can see this." Add an org_id (or tenant_id) column to each shared table and match it against the user's membership.
Give the agent your real membership schema and spell out the model, for example: "Users belong to organizations through org_members(user_id, org_id, role) with owner, admin, and member roles." Ask for:
A
security definerhelper function (in a schema not exposed to the API, with an emptysearch_path) that returns the org IDs the current user belongs to.Policies that check each row's
org_idagainst that function.An index on
org_idfor every shared table.
If you'd rather avoid a membership lookup at query time, put org_id and the tenant role in app_metadata (set server-side, for example through a Custom Access Token Auth Hook) and read them in policies with auth.jwt(). Never authorize from user_metadata, which users can edit themselves. Claims only refresh when a new token is issued, so membership changes take effect on the next token refresh.
If the table owner should also obey policies, add FORCE ROW LEVEL SECURITY. It doesn't affect roles with BYPASSRLS.
Step 5: Test policies as real clients, not in the SQL Editor
By default the SQL Editor runs as postgres, which bypasses RLS, so a query that works there tells you nothing about what a client can do. Use the editor’s role switcher to impersonate a user, or simulate the client role and user inside a transaction:
Use two test users to prove isolation: each can read their own rows and none of the other's. Do the same across two tenants. Then test writes as carefully as reads. Anonymous callers must not insert, update, or delete. Authenticated users must not insert rows with another user's ID, reassign ownership, or delete another user's rows. Teams often stop at SELECT, but a caller who can't read data can still damage it if a write policy is too loose.
Ask the agent to generate a pgTAP test file covering allowed and denied operations for both anon and authenticated, and run it with supabase test db in CI.
Finally, check policy coverage:
Compare it with your table list. A table with RLS on and no policies stays deny-all, which is safe but may not be what you meant.
How AI agents interact with RLS, and where it breaks down
An agent that writes policy SQL and an agent that queries user data need different levels of trust. RLS applies no matter who wrote a query, but only when the connection is subject to it.
As the signed-in user: Supabase's MCP server for your own app, announced at Supabase Select 2026, runs each tool call as the user who signed in, so your RLS policies decide what each agent can reach.
Through the Data API with the publishable key: the PostgREST MCP server is subject to RLS like any other client.
Through the Supabase MCP server's SQL tools: these are developer tools that run with your developer permissions, not as an end user, so policies written for anon and authenticated don’t scope them.
read_only=trueruns queries as a read-only Postgres user: it prevents writes, not data exposure.
Never give the service role key to an agent session that handles user data; it bypasses every policy. RLS also doesn't govern DROP TABLE, ALTER TABLE, or TRUNCATE, so limit the connecting role's schema privileges separately.
Supabase’s guidance for its MCP server is to connect to a development project or branch rather than production, scope it with project_ref, enable read_only when you must touch real data, and limit feature groups. Add your own guardrails on top: require human approval before the agent runs SQL, ship schema changes as migrations, and give any temporary database access its own role and an expiry, then test that revocation works. Our Supabase MCP server guide covers what each tool can reach.
Why letting agents query production directly is the wrong default
RLS can't control what an agent does with rows it's allowed to read, how many it pulls, or whether its queries saturate your connection pool. Complex policies with subqueries or joins already slow queries on large tables, and an agent issuing many ad hoc queries makes it worse.
The risk is real. In July 2025, General Analysis showed how a prompt injection in a support ticket could get a Cursor agent connected through the Supabase MCP server to leak private tables. The agent used the service_role key, so RLS never applied. A policy can't protect data from a credential that sits above it.
Dreambase takes agents off the production path. It snapshots Supabase data into pre-modeled, pre-calculated governed datasets queried with DuckDB and exposes them, with metrics, triggers, and domains, through one Dreambase MCP server. Agents and human dashboards read the same datasets, so what each one sees is explicit and explainable, and agent queries never reach production Postgres. For the full threat model, see our guide to MCP security.
If you do allow database-backed MCP access, restrict it to a specific schema or allowlisted tables. A search_path sets query defaults; it is not an access control. In regulated or PII-heavy environments, aim for the smallest data slice you can defend and access you can explain afterward. Keep RLS on underneath either way.
What to monitor alongside RLS from day one
Correct policies at deploy time don’t guarantee acceptable behavior at scale, and every new migration is a chance to ship a table without RLS. From the first deploy, track active connections, pool saturation, query latency, slow queries, and storage. Supabase’s Metrics API exposes about 200 Postgres health and performance metrics in Prometheus format, and our Supabase observability guide covers what to watch.
Realtime adds its own pressure. Postgres Changes checks RLS for each subscribed client on every change event, so thousands of subscribers on a hot table can hit a scaling cliff. Watch subscription counts next to query latency.
Slow queries often point to missing indexes on policy columns. Supabase’s Security and Performance Advisors flag tables with RLS disabled, views that bypass RLS, policies that re-evaluate auth.uid() per row, and multiple permissive policies, and its Index Advisor suggests missing indexes.
Dreambase turns those checks into a habit. Once a project is connected, it runs a daily check across security, performance, indexing, errors, and capacity and lists open recommendations by category. Its priority recommendation trigger sends new findings to Slack, email, a webhook, or an agent, as our Supabase alerts guide explains, and Common Supabase Fixes walks through resolving the RLS issues it flags. For an agent that watches all of this around the clock, see how to build a full-time SRE agent that monitors Supabase and Vercel.
How Dreambase compares with Supabase’s Security Advisor and RLS scanners
Three kinds of tools help keep RLS correct, and they answer different questions.
Supabase Security Advisor: built into the dashboard and the MCP server’s
get_advisorstool, at no extra cost. It’s the authority on what Supabase flags, including tables with RLS disabled and views that bypass it.Outside scanners such as Supaguard: they probe your app from the outside with the public key, the way an attacker would. That makes them the only one of the three that tests what a stranger can actually read, and a good check before launch.
Dreambase Observability: it checks every connected project and branch every day without anyone opening a dashboard, alerts the right people when a new priority recommendation appears, and gives agents governed datasets instead of production access.
None of them proves a policy is logically right. That still takes the pgTAP tests in Step 5. Use the Security Advisor to fix what Supabase flags, an outside scan before you launch, and Dreambase so a regression from next month’s migration doesn’t go unnoticed.
Good security and good observability are the same habit at different layers: define the boundary, then keep checking that it holds. Start for free to connect your Supabase projects, or meet with the team to talk through agent access to your data.
NEXT STEP
MCP Security: Giving an Agent Access to Operational Data Safely
With RLS in place, see how to give agents access to operational data without letting them leak it or take your database down.