Skip to content
RowShield
All posts

anon, authenticated, service_role: the real boundaries

What each Supabase role exists for, exactly where it bypasses row-level security, and the deployment mistakes that blur the lines between them.

RowShield13 min read

Supabase projects ship with three principal roles whose trust levels differ enormously — and most authorization bugs are really boundary violations between them. This article maps what each role may do, where each bypasses RLS outright, and how to prove your own boundaries hold.

Every request your application ever makes arrives at Postgres wearing one of three names. Which name it wears determines everything: which policies evaluate, which grants apply, whether any of that machinery runs at all. Yet the roles are routinely treated as interchangeable plumbing — anon used as if it were trusted, service-role sprinkled into convenience code, postgres reached for when policies feel restrictive. The result is a system whose real trust boundaries live nowhere anyone documented them.

This article draws those boundaries precisely: what each role is for, where each one skips the rules entirely, and the recurring deployment mistakes that quietly merge three carefully separated trust levels into one.

Three roles, three trust levels

The roles form a ladder, and every design question about data access reduces to "which rung is this caller on?"

RoleWho wears itTrust levelPolicy relationship
anonAnyone holding your public key — every visitor, crawler, scriptZero; by definition adversarialSubject to all RLS; gets only what policies explicitly give
authenticatedA verified user, via their personal JWTTheir identity is proven; their intent is notSubject to all RLS; policies scope rows per user
service_roleYour server-side code onlyFull trust of your backendBypasses RLS completely (BYPASSRLS)

The role attributes documentation defines BYPASSRLS; Supabase's database roles guide shows how these roles are provisioned per project. The load-bearing word in the table is adversarial. The anon key ships inside every browser bundle you deploy, appears in network requests to your domain, and cannot be rotated away from public visibility — treating it as merely "the low-privilege key" understates the situation. It is the key of everyone who is not logged in and everyone probing without an account, and the entire security model stands on policies written for it.

A four-question triage places any code path on the right rung:

  1. Does the operation act on one user's data, driven by that user's request? It belongs to authenticated, scoped by policy.
  2. Must it work with no session at all? It belongs to anon — and the exact rows it needs become a public-surface decision worth writing down.
  3. Does it span users legitimately (digests, cleanup, webhooks), such that no single caller could own it? It belongs behind service_role, on a server, after its own explicit authorization logic.
  4. Is it schema work? That is the owner path — migrations and admin tooling, kept out of request handling entirely.

Most boundary violations are paths that skipped the triage and landed wherever was convenient. Answering the questions in order takes seconds and produces an auditable trail of intent.

anon: the role everyone on Earth holds

Anyone can compose a request to your API with your anon key. There is no gate before this point — the key is handed out by design so browsers can bootstrap sessions. What separates a deliberate public surface from an accidental one is the policy set targeting anon.

Three properties make anon distinctly dangerous to reason about:

Scale is unbounded. Authenticated abuse ties back to accounts; anon abuse ties back to nothing. Any table readable by anon is readable by scripts at whatever rate your infrastructure permits, which makes even "harmless" public reads worth pairing with explicit pagination limits and, where warranted, rate limiting at the edge.

Enumeration is cheap. An anon-readable table with guessable identifiers — sequential IDs, slugs, phone numbers — is a bulk-download surface even when each individual row feels innocuous. If a listing must be public, ask whether counting it must also be public.

Silence looks identical everywhere else. When anon policies are absent, callers get empty arrays — indistinguishable from an app bug. Teams discover missing anon policies from production behavior rather than review precisely because nothing errors. The anon-table-readable rule exists because outside probing finds these tables faster than inside review does; our field notes are in what the anon key can reach.

The design posture worth adopting: anon receives nothing until a feature explicitly requires public access, and anything it does receive was chosen, documented, and tested on purpose — the full discipline is anonymous access done deliberately's home cluster on /solutions.

authenticated: proven identity, unproven intent

Signing in upgrades one fact about a caller: who they are. It upgrades nothing about what they may touch — that remains the exclusive business of policies. The distinction matters because a surprising amount of implicit reasoning treats login as authorization ("only members see the dashboard" conflates authentication with the row-scoping that actually protects other members' data).

Mechanically, an authenticated caller's power comes from two sources, and keeping them separate clarifies every policy discussion:

Their claims. The token's sub anchors ownership comparisons; admin-controlled app_metadata can carry entitlements. These are read-only facts supplied per request — a user cannot inflate their own sub, and the signature check guarantees they present exactly one identity.

Your policies. Everything they can read or write follows from clauses targeting authenticated. Two users differ only in claim values, which means cross-user attacks are claim-substitution attacks: user A performing operations with user B's identifiers planted in payloads or URL parameters. Every such attack is defeated the same way — policies compare stored columns against (select auth.uid()), never against client-supplied values, and every write carries a WITH CHECK that re-establishes ownership of the resulting row.

The practical review habit: for each table, imagine two colluding accounts with free rein over each other's client-side state. If the policy set survives that thought experiment — neither can read, plant, or steal rows belonging to the other — the boundary is drawn correctly. Making that experiment concrete is the purpose of the tenant-isolation test's checklist family on this site.

service_role: root for your backend

The service-role key exists because some work must ignore row security: webhook processors writing rows on behalf of users, cleanup jobs touching expired sessions across all tenants, admin tooling. Its role claim resolves to a Postgres role carrying BYPASSRLS, so policy evaluation never happens for it — not stricter policies, no policies. It also outranks ordinary grants in practice because it typically holds broad table privileges by provisioning.

That total exemption dictates placement more than any other security decision in a Supabase stack:

It belongs behind a server boundary. Edge Functions receive it automatically as an environment variable — Supabase's functions auth documentation covers the mechanism — as do traditional servers via environment configuration. The pattern is always the same: user traffic hits a route that verifies identity first, then performs service-grade operations deliberately.

It must never cross to the client. Not in environment variables exposed by framework prefixes, not in git-tracked config, not in "temporary" debug builds. A leaked service-role key is not a finding requiring a policy fix; it is total database access requiring rotation — see service role exposure for detection and rotation guidance for the response sequence.

Every use deserves justification. Because it skips all policies, service-role code re-assumes responsibility that policies would otherwise carry: tenancy checks move from declarative clauses into imperative code, where omissions compile silently. A healthy codebase can enumerate its service-key call sites on one screen; anything beyond that usually means policies were loosened under pressure somewhere.

One nuance completes the picture: the dashboard's SQL editor connects as the owning postgres role, which also bypasses policies — by ownership rather than attribute. Both paths see everything; they differ in audit trail and in what code tends to run there. Neither belongs in the request path of an end user.

The mistakes that blur the boundaries

Most real-world boundary failures reduce to a handful of recurring moves:

MistakeWhat actually happensTypical discovery
Service key referenced in client code (wrong env prefix, copied snippet)Entire database readable/writable by anyone with devtoolsProbe scanning your deployed bundle
Table left with no anon policy but grants intactEmpty results mask the gap until someone "fixes" it with using (true)Empty-state debugging session
Policies target authenticated while feature assumes publicFeature silently broken for logged-out visitors; pressure to widen laterQA pass on fresh incognito profile
Backend helper connects as table owner for "convenience"Owner bypass makes every policy moot for that pathCode review, if the path is visible
One privileged key embedded in a mobile/desktop buildSame as bundle leak, harder to rotateKey scanning on release artifacts
Client-supplied IDs trusted in write payloads without WITH CHECKRows planted into other tenants' scopesCross-account complaint, post-incident

Notice the pattern down the right column: almost none of these are caught by functional testing, because each one produces working software. Boundaries fail outward — toward more access — and more access never raises exceptions. That asymmetry is why static checks, probes, and continuous monitoring carry weight equal to tests here; the failure modes simply don't announce themselves through normal use.

Proving the boundaries: a boundary-expressing schema

Boundaries become concrete when a schema forces every role decision into policy syntax. Here is the minimal shape that exercises all three roles correctly — runnable as-is on any project:

-- Tier 1: genuinely public. Readable by anyone; writable by no client.
create table public_announcements (
  id uuid primary key default gen_random_uuid(),
  title text not null,
  body text not null,
  published_at timestamptz not null default now()
);
alter table public_announcements enable row level security;

create policy "announcements_public_read"
  on public_announcements for select
  to anon, authenticated
  using (published_at <= now());

-- Tier 2: user-scoped. Full CRUD for owners; invisible to anon.
create table workspace_documents (
  id uuid primary key default gen_random_uuid(),
  workspace_id uuid not null,
  title text not null,
  owner_id uuid not null
);
alter table workspace_documents enable row level security;

create policy "documents_select"
  on workspace_documents for select
  to authenticated
  using ((select auth.uid()) = owner_id);

create policy "documents_insert"
  on workspace_documents for insert
  to authenticated
  with check ((select auth.uid()) = owner_id);

create policy "documents_update"
  on workspace_documents for update
  to authenticated
  using ((select auth.uid()) = owner_id)
  with check ((select auth.uid()) = owner_id);

create policy "documents_delete"
  on workspace_documents for delete
  to authenticated
  using ((select auth.uid()) = owner_id);

-- Tier 3: server-only. Enabled, zero policies: clients of either
-- kind see nothing; background jobs reach it via service_role.
create table notification_queue (
  id bigint generated always as identity primary key,
  user_id uuid not null,
  payload jsonb not null,
  created_at timestamptz not null default now()
);
alter table notification_queue enable row level security;

Read the tiers as boundary declarations:

  • Tier 1 grants anon exactly one narrow capability — reading published announcements — and takes care to exclude drafts via the USING predicate. Public does not mean unconditional.
  • Tier 2 never mentions anon at all. Logged-out visitors hit default deny; signed-in owners get complete CRUD over their own rows, with both halves of update constrained.
  • Tier 3 is the quiet one: RLS enabled, no policies anywhere. Both client roles see an empty world; the queue fills and drains exclusively through server contexts running as service_role. This tier is where "backend-only table" intent should live — not in hopes that nobody guesses the endpoint.

Verifying costs four queries through the impersonation harness:

begin;
set local role anon;
select count(*) as announcements_expect_gt_0 from public_announcements;
select count(*) as documents_expect_0 from workspace_documents;
select count(*) as queue_expect_0 from notification_queue;
rollback;

Anon sees the public tier and nothing else. Re-running as authenticated adds visibility only of owned documents. And the same three counts under a service-role connection return everything — which is precisely the point: the tiers are enforced for clients and dissolved for the server, on purpose, per role.

The full expected matrix, as verified against this exact schema:

Callerpublic_announcementsworkspace_documentsnotification_queue
anonPublished rows only0 rows0 rows
authenticated (non-owner)Published rows only0 rows0 rows
authenticated (owner)Published rows onlyOwn rows, full CRUD0 rows
service_role (server)EverythingEverythingEverything

A boundary audit for your own project is the same exercise with your table names. For each tier you intend to exist, write down which roles see which tables and with what predicates; then impersonate each role and compare reality against the list. Every mismatch is either an undocumented grant or a missing policy, and both are cheaper to fix on paper than in an incident review. When your own project can be described this tersely, boundaries are real; when it can't, the gaps are findable the same way — probe your public surface and compare what returns against what you meant to publish.

Common questions

Is exposing the anon key actually safe?

Safe is the wrong axis — it is unavoidable. The key identifies your project, not a user, and the model assumes its publication. Safety lives entirely in the anon-targeted policy set, which is why auditing that set (and monitoring its drift) matters more than guarding the string itself.

Can I turn off anonymous access entirely?

Yes, structurally: no policies targeting anon means default deny across every table, regardless of who holds the key. Keep the key distributed for bootstrapping sign-in flows — it stops being interesting the moment it grants nothing.

Where may service_role legitimately appear in a web stack?

Only behind server boundaries: API routes, server components that never serialize secrets to the client, edge functions, scheduled jobs. The test is mechanical — if the value ends up in anything the browser downloads, executes, or can inspect, it is compromised by definition and needs rotation, not debate.

Does the postgres role make RLS pointless for migrations?

Migrations are exactly why the owner bypass exists — schema changes shouldn't fight row security. The risk is habit creep: application code connecting as postgres because it was convenient during development. Reserve owner-grade connections for schema work and genuine administrative jobs, and prefer FORCE ROW LEVEL SECURITY on tables where even owner-path mistakes must respect isolation.

How do I check which keys my deployed app actually ships?

Inspect what the browser downloads: view-source and devtools on your built assets, plus a search of the bundle for key prefixes. For continuous coverage, an outside probe that fetches your app and flags service-grade material catches the copy-paste regressions manual searches miss — that check is part of RowShield's scan, described on the rule's page.


Check where your own boundaries stand today: run the free scan — paste your app URL, and see your project as an anonymous stranger sees it, findings and proposed remediation included.

RowShield is an independent product and is not affiliated with, endorsed by, or sponsored by Supabase, Inc.

RowShield checks what a deployed Supabase app exposes: a free anonymous, read-only probe, and scheduled policy-metadata and drift checks for connected projects. Run a free audit.

RowShield is a Veristria product. More about RowShield.