RLS beyond tables: Storage, Realtime, and Edge Functions
How row-level security extends to storage objects, realtime streams and edge functions - what each surface needs, where RLS stops, and how to verify all three.
Table policies are the heart of Supabase authorization, but data leaves through other doors too: files, live subscriptions, and server-side code. This article maps where row-level security extends to those surfaces, where it stops, and the configuration each one needs.
Teams that harden their tables often stop there, reasonably assuming the rest of the platform inherits the protection. Some of it does — Supabase's surfaces share an identity model deliberately, so a policy you wrote for a table can govern file access and live subscriptions too. But "can inherit" and "does inherit" differ surface by surface, and each surface has its own configuration that must exist before inheritance kicks in.
The good news is structural: once you can read table policies — the USING/WITH CHECK model from the evaluation reference — you already know most of what governs the other surfaces. Storage speaks the same policy language against different columns; Realtime literally reuses your table policies; only Edge Functions genuinely change the paradigm, and they change it by removing constraints rather than adding syntax. What's left is learning each surface's configuration points and verification habit, which is exactly what follows.
This article walks the three main non-table surfaces in order of how often they surprise teams: Storage, whose objects have their own policy system keyed to paths rather than rows; Realtime, which reuses your table policies in ways worth understanding precisely; and Edge Functions, which invert the model entirely by running in a context that can bypass everything. Each section ends with what to verify, because these surfaces drift independently of your tables.
Three surfaces, one identity model
The unifying design: every client request carries the same JWT regardless of which surface it hits, and that token's role claim plus sub value drive authorization everywhere. Your anon key identifies the anonymous caller to Storage exactly as it does to PostgREST; a signed-in user's token scopes file reads through the same auth.uid() that scopes row reads.
That shared identity is why cross-surface holes feel surprising when found — the who is consistent, so defects come from the what: missing configuration on a surface nobody remembered to configure. The recurring shapes:
| Surface | Authorization basis | Default posture | Common defect |
|---|---|---|---|
| Database tables | Row security policies | Deny-all once enabled | Flag off, or tautology policies |
| Storage objects | Object policies on storage.objects | Depends on bucket visibility | Public buckets; missing path scoping |
| Realtime streams | Table SELECT policies (per subscriber) | Nothing subscribes without policies | Assuming presence/broadcast are DB-gated |
| Edge Functions | Execution context + code discipline | Verify-JWT configurable | Service-role work reachable unauthenticated |
Read down the last column: none of these are exotic failures, all are configuration-shaped, and each has ended up in this site's detection catalog because it recurs. The sections below give you the working mechanics plus the verification habit for each.
Storage: buckets get their own policies
Storage objects live in a real table — storage.objects — and their access rules are genuine row-level security policies, just written against object metadata instead of business columns. The working pattern for a private avatar bucket:
create policy "avatars_read"
on storage.objects for select
to authenticated
using (bucket_id = 'avatars');
create policy "avatars_upload_own_folder"
on storage.objects for insert
to authenticated
with check (
bucket_id = 'avatars'
and (storage.foldername(name))[1] = (select auth.uid())::text
);
The insert policy is the interesting half. Object names double as paths, so (storage.foldername(name))[1] extracts the first folder segment, and requiring it to equal the uploader's identity means Alice can only write beneath her own prefix — Bob's folder rejects her uploads at the policy layer with the standard row-security error. This was executed during preparation of this article, including the rejection case; it behaves exactly like table WITH CHECK, because it is table WITH CHECK, applied to object rows.
Complete the set for a production bucket: update and delete policies scoped the same way, so users can't overwrite or remove each other's objects:
create policy "avatars_update_own"
on storage.objects for update
to authenticated
using ((storage.foldername(name))[1] = (select auth.uid())::text)
with check (
bucket_id = 'avatars'
and (storage.foldername(name))[1] = (select auth.uid())::text
);
create policy "avatars_delete_own"
on storage.objects for delete
to authenticated
using ((storage.foldername(name))[1] = (select auth.uid())::text);
For serving files to non-owners without making buckets public, signed URLs are the tool: your server generates short-lived credentials per object, authorization happens at generation time through your own logic, and expiry bounds the exposure window. Signed access and policy access compose cleanly — policies govern direct API reads, signatures govern time-boxed share links.
Two structural facts shape everything else about Storage:
Bucket visibility overrides nuance. A public bucket serves objects to anyone holding URLs — no policies consulted, no auth check, period. Public is legitimate for genuinely public assets (marketing images), but it's binary: nothing inside a public bucket is private. Teams discover this backwards, after uploading something sensitive alongside the logos. Audit buckets first (the exposure rule), then audit policies within private ones.
Path conventions are load-bearing. The own-folder pattern above works only while clients actually name objects inside the user's prefix. Enforce the convention server-side or in upload helpers; a client that writes avatars/shared/whatever.png lands outside any user's scope, which is either a feature (shared assets) or a leak (unscoped attachments) depending entirely on whether you decided.
Realtime: your SELECT policies, per subscriber
Realtime's Postgres-change streams authorize through your existing table policies: a subscriber receives INSERT/UPDATE/DELETE events only for rows the database would let them SELECT. No separate rule language exists to misconfigure — the same documents_member_read style policy that gates REST reads gates live updates, evaluated per subscription rather than per connection.
That per-subscription evaluation is the part to internalize. Two clients subscribed to the same channel receive different filtered streams based on their identities; Bob never sees Alice's inserts into rows he can't read. It also means Realtime inherits your policy defects silently: if a table's select policy is a tautology, live subscriptions stream everything, immediately, to everyone authorized to subscribe at all.
Three verification points cover the surface:
- Subscribe as two personas and confirm each receives only its policy-visible changes — inserts into another tenant's rows should simply never arrive.
- Confirm protected tables require policies at all: if a subscription delivers rows for a table whose select policy you just dropped, that's a finding about Realtime's configuration, not just the table.
- Distinguish channel types. Postgres-changes streams are DB-backed and policy-checked; broadcast and presence messages are application-relayed and know nothing of your tables. Anything sensitive sent over broadcast is protected by your function/code logic, never by RLS — a distinction covered further in realtime channels and RLS.
The third point causes real incidents in chat-style apps: developers assume "it's a Supabase channel" means "the platform authorizes it," then ship room IDs guessable from outside. Policies protect what lives in tables; messages relayed between sockets were never in a table unless you put them there.
One operational note completes the Realtime picture: subscription authorization is checked when subscriptions attach and re-checked as policies change, but client libraries cache aggressively. After tightening a policy, existing subscribers should lose access to newly-forbidden rows on subsequent events — if your testing shows stale streams continuing, restart the clients as part of the fix, and add the behavior to your policy-change checklist so operators aren't surprised by either direction of staleness.
Edge Functions: trusted context, borrowed identity
Edge functions invert the model: instead of constraining callers, they run in a context that holds power — service-grade credentials arrive automatically as environment variables — and their job is to use that power only on behalf of verified identities.
The authorization contract therefore lives in the function's own code, in three lines of discipline:
// 1. Verify the caller with the ordinary (anon-key) client:
const { data: { user } } = await supabase.auth.getUser(token);
if (!user) return new Response("Unauthorized", { status: 401 });
// 2. Only now touch the privileged client:
const admin = getAdminClient();
// 3. Scope every operation to the VERIFIED identity:
await admin.from("audit_log").insert({ user_id: user.id, action });
Each line fails differently when skipped. Without step 1, anyone who finds the function URL operates with backend power. Without step 3, even verified users act beyond their scope — the function becomes an authorization-free proxy. And without the boundary discipline keeping admin clients out of shared modules, copy-paste spreads steps 2–3 into contexts that never had step 1. The full containment pattern, spread paths, and rotation response live in service-role leakage.
One configuration flag belongs in review: whether the platform requires a valid JWT before invoking at all. Leaving verification enabled makes functions fail closed by default; disabling it for a webhook endpoint is sometimes necessary, and then the endpoint must verify authenticity itself (signature checks, shared secrets) before doing privileged work:
// Webhook pattern: no user JWT exists, so verify the SENDER instead.
const signature = req.headers.get("x-provider-signature");
const expected = await crypto.subtle
.sign("HMAC", secretKey, rawBody);
if (!signatureMatches(signature, expected)) {
return new Response("Invalid signature", { status: 401 });
}
The principle is constant across both patterns — user JWT or sender signature — something must be verified before anything privileged runs. "It's an internal URL" is not verification; URLs are discovered, shared, and committed to public repos by accident daily.
Nothing in that flag flips other functions' configs, which is both convenient and worth monitoring: the per-function setting changes independently on every deploy, so a hardened default regresses one function at a time, exactly when nobody's looking at that function. Include per-function settings in whatever review covers deployment diffs.
Surfaces drift independently
Because each surface keeps its own configuration, each accumulates drift on its own schedule. The matrix worth checking monthly:
| Change event | Tables affected? | Storage? | Realtime? | Functions? |
|---|---|---|---|---|
| New migration adds table | Yes | No | Possibly — new subscriptions | No |
| Bucket created for a feature | No | Yes | No | No |
| Policy edited in dashboard | Yes | If storage policy | Yes — streams follow | No |
| Function deployed | No | No | No | Yes |
Nothing in that table propagates automatically across rows. A team with rigorous migration review can still grow a public bucket, because buckets aren't created by migrations; a team with pristine buckets can still have a function deployed with verification disabled, because functions don't appear in catalogs your table checks examine. Independent surfaces need independent observation — which is why outside probing covers all reachable surfaces rather than stopping at tables, and why monitoring that watches only one layer reports only one layer's drift.
The matrix also explains a familiar organizational pattern: the "storage person" and the "database person" being different contributors, each assuming the other owns cross-surface checks. Ownership per surface is fine; ownership of the matrix — the periodic confirmation that every row got its check — must belong to someone explicitly, or to automation that doesn't forget.
A unified verification pass
Fifteen minutes per month, framed for auditing your own project. The point of unifying these checks into one pass is coverage memory: three surfaces checked ad hoc at three different times reliably leaves one stale, while a single checklist with a date on it doesn't.
| Check | Method | Pass looks like |
|---|---|---|
| Buckets inventory | List buckets, flags | Every non-public bucket marked private |
| Object policy probe | Fetch object URL as anon | Denied on private buckets |
| Own-folder enforcement | Upload into another user's prefix (your own project, test account) | Rejected |
| Realtime isolation | Subscribe as two test tenants | Neither receives other's rows |
| Function reachability | Call each function URL without credentials | 401/403 except deliberate webhooks |
| Bundle scan | Search built assets for secret material | Nothing service-grade present |
Every pass result earns a checkbox in whatever launch/hardening document you maintain; every failure maps to one of the sections above. When the list stays green month over month, you've achieved the actual goal: not three extra surfaces to fear, but three more places where the same identity model demonstrably holds.
And when the list turns red — as it eventually will, because these are exactly the surfaces that change outside migrations — the red cell comes with its section reference, its fix pattern, and its verification step already written. Drift on well-mapped surfaces is a maintenance ticket, not an investigation.
Common questions
Do I need policies if my bucket is private?
Yes — private bucket means "not URL-served publicly," but reads and uploads still flow through policies for signed-in callers. Private-with-no-policies typically manifests as mysterious permission errors for legitimate users; private-with-thoughtful-policies is the actual goal.
Can one storage policy serve multiple buckets?
Technically yes (bucket_id in (...)), deliberately rarely. Per-bucket policies keep each bucket's access story readable and prevent one bucket's logic change from silently altering another's. The sprawl dynamics from table policies apply here identically.
How do I see which Realtime subscriptions exist?
Check client code for subscription setup, then map each back to its source table and confirm that table's SELECT policies match intended audience. Server-side, Realtime exposes subscription-related state for auditing; treat any subscription to sensitive tables as requiring the same two-persona proof as REST reads.
Do storage policies have the same performance concerns as table policies?
The same mechanics apply at smaller scale — object counts per bucket can reach the hundreds of thousands in media-heavy apps, so bucket and path predicates benefit from the same thought given to table columns. The practical difference: object paths are strings, and prefix matching via foldername or like patterns resists indexing more than uuid equality does. Keep path structures shallow and conventional, and measure with the same plan-reading habit before assuming.
Should Edge Functions call the database directly instead of going through PostgREST?
Direct connections bypass row security entirely (owner-grade), while PostgREST calls through a client carry whatever identity you attach. Neither is wrong — they're different tools for different trust levels. The review question is whether each function's database access matches its actual privilege need: functions doing user-scoped work should behave like users (verified identity through policies), while genuinely privileged operations should be explicit, justified, and inventoried as service-grade.
Verify all your surfaces at once: run the free scan — paste your app URL and see storage exposure, key leakage, and table findings together, with proposed fixes.
RowShield is an independent product and is not affiliated with, endorsed by, or sponsored by Supabase, Inc.