Cenk Kurtoğlu©26

Supabase security · 8 minute read

anon vs service_role vs sb_secret_: which Supabase key opens what

Every Supabase project ships with more than one API key, and the incident reports that turn into "we rotated everything" weekends start with a mis-scoped guess about which key was in the repo. The anon key belongs in your browser bundle. The service_role key — and its newer sb_secret_ form — belongs on a server you control, because it switches row-level security off. This article is the identification layer: tell them apart from the string alone, know what each one opens, and prove at runtime which role your request is actually running as.

The three keys at a glance

KeyShapeRole claimRLS applies?Belongs in
anon (public)JWT, three dot-separated segmentsanonYes — every policy appliesBrowser bundle, by design
user sessionJWT, minted at sign-inauthenticatedYes — policies see auth.uid()Client, after login
service_roleJWT, three dot-separated segmentsservice_roleNo — bypasses RLS entirelyServer only. Never shipped.
secret keysb_secret_… prefix, opaqueresolves to service-role semanticsNo — same bypassServer only. Never shipped.
publishable keysb_publishable_… prefix, opaqueresolves to anon semanticsYesBrowser bundle, by design

The two JWT keys and the two prefixed formats are differentrepresentations of the same split: one key that row-level security applies to, and one that it does not. Older projects show the JWT pair in the dashboard; newer ones show the prefixed pair. Both forms are live, so a repo can contain either and you need to recognise both.

Telling them apart from the string alone

1. JWT keys: read the payload, do not verify it

Both legacy keys are JWTs: three base64url segments separated by dots. The signature is what proves a token was minted by your project — but you are not verifying anything, you are classifying, and the payload of a project key is public information by design. Decoding the middle segment is enough to tell the three roles apart:

// classification only — no secret is verified, no request is sent
function keyType(key: string) {
  const part = key.split('.')[1];
  if (!part) return 'not a JWT (prefixed key format)';
  const payload = JSON.parse(atob(part.replace(/-/g, '+').replace(/_/g, '/')));
  return payload.role ?? 'no role claim';
  //           ^ 'anon' | 'authenticated' | 'service_role'
  // payload.iss = 'supabase', payload.ref = '<project ref>'
}

The payload also carries iss and ref, which tell you which project a leaked key belongs to — useful when you are triaging a repository that is not yours. Note what is not there under a service-role key: any user identity. A service_role payload identifies the project, not a person, so treat auth.uid() under it as null.

2. Prefixed keys: the prefix is the classification

The newer format is deliberately opaque — there is no payload to read, so the string prefix is the whole signal. Two prefixes exist, and they map one-to-one onto the two risk levels:

sb_publishable_…   → the anon boundary: RLS applies, ships in the browser
sb_secret_…      → the service_role boundary: RLS does not apply, server only

This is the grep that matters, because these keys cannot be identified by decoding. A sb_secret_ string in a client bundle or a public repo is a full bypass sitting in the wrong place, and nothing about its shape hints at that.

What each key actually opens

anon / publishable: the RLS boundary itself

Requests with the anon key run as the anon Postgres role. Every policy applies. That is the entire point: the key is safe to shipbecause RLS is the thing standing between it and your rows. The moment a table has RLS disabled, or a policy grants select to anon or public, that table becomes world-readable with a key that was public all along. Finding the anon key in your bundle is not a finding. Finding it next to a readable table is. The browser check for that is the free anon-key readability checker.

authenticated: the per-session JWT

There is no "authenticated project key" to leak. When a user signs in, Supabase mints a session JWT whose role claim is authenticated and whose sub is the user id. Your policies read auth.uid()to scope rows to that identity. The exposure here is not the token's existence — it is a policy that never consults auth.uid(), which lets any signed-in user read every row. That failure mode is covered in the always-true authenticated policy.

service_role / sb_secret_: the switch RLS cannot see

A request with the service-role key runs as service_role, which holds the BYPASSRLS attribute. Policies are not evaluated, not overridden — skipped. Every table, every row, every operation. It is the right key for a cron job that has to aggregate across tenants, and it is the wrong key everywhere it can reach a network boundary. The one-line version: if a sb_secret_ or service_role string appears anywhere a browser or an untrusted process can read, treat the whole database as exposed until you have rotated it, regardless of what a table-by-table review says.

The near-miss to watch for is the environment variable name. NEXT_PUBLIC_ is inlined into the shipped bundle at build time, so a variable holding a secret key with that prefix publishes it, whatever the comment above it says. That is the single most common shape of a self-inflicted service-role exposure, and it survives code review because the name looks intentional.

Proving which role a request runs as

Classification from the string is inference; the ground truth is what the database executes the request as. Run this with each key against the same project — it names the role PostgREST switched into and the claims the request carried:

select
  auth.role()                                              as jwt_role,
  auth.uid()                                               as jwt_sub,
  current_user                                             as db_role,
  coalesce(current_setting('request.jwt.claims', true), '{}')::json ->> 'role'
                                                            as claim_role;
-- anon key        : jwt_role = 'anon',         db_role = 'anon'
-- user session    : jwt_role = 'authenticated', jwt_sub = '<user id>'
-- service key     : jwt_role = 'service_role',  db_role = 'service_role'

And the differential probe that shows whether RLS is doing any work at all — one query, two keys, same table:

select count(*) from public.your_table;

-- with the anon key    : the rows RLS leaves visible
-- with the service key : the true row count
--
-- anon count == service count and count > 0  → the table is open to the public key
-- anon count == 0 and service count > 0     → RLS is filtering (good, but not proof:
--                                            the filter could be true for everyone)
-- both 0                                     → empty table, or policies filter
--                                            every role — check the policies, not
--                                            just the number

Equal counts with data in them is the finding worth escalating: it means the key that ships in your bundle reads the same row set the bypass key reads.

Where they hide in a repository

These are the same patterns a secret scanner runs, so run them first. Each one is a plain ripgrep against the default branch and, if you still write history by hand, against history:

rg -n 'eyJ'            .   # JWT header prefix — decode the payload
                                       # and read the role claim to classify
rg -ni 'service_role'  .   # role claim, or a variable name holding the key
rg -n  'sb_secret_'    .   # secret-key prefix — full bypass if found
rg -n  'sb_publishable_'  .   # publishable prefix — expected in client code
rg -n  'SUPABASE_.*(KEY|SECRET|SERVICE)' . --hidden -g '!.git'
rg -n  'NEXT_PUBLIC_.*SUPABASE' .        # fine for anon/publishable — verify the shape

Two placements outrank every other finding in that list, because they are where server keys survive review: CI and platform config — .github/workflows/*.yml, docker-compose.yml, render.yaml, vercel.json, a Jenkinsfile — and the .env* files that are one careless .gitignore pattern away from being committed. The file shape is also the tell: an "env example" file with real values, a README curl command with a live key pasted into it, a Dockerfile ENV line. All three exist in public repos right now, and all three are found by the same grep.

When one lands in the wrong place

The order is fixed and it is not "delete the file first": rotate, then purge. Deleting the commit does not invalidate the key — it is in every clone, every fork, every cache, and the crawlers that read public repos on a schedule already have it. The runbook:

  1. Rotate the key in the dashboard (or roll the secret key) so the leaked string stops working. Time-to-first-copy is measured in minutes.
  2. Verify the old key now reads 401 — if it still returns data, the rotation did not apply and nothing after this step matters.
  3. Purge from the working tree and history, and push the rewrite.
  4. Add a pre-commit hook (gitleaks or equivalent) and a paired-secret scan in CI so the next one never reaches the default branch.

The full sequence, with the check that proves your RLS held while the key was live, is in the service_role rotation runbook; the first-24-hours split is in exposed API key: the first 24 hours.

What a key inventory cannot prove

Knowing which keys you hold tells you the blast radius, not the state of the database. Three gaps stay open after a clean inventory:

Where this goes next

Inventory is the free half. The next steps, in the order they are worth your time: run the free anon-key readability check against the project that key belongs to, then keep it honest overnight with the free Supabase RLS drift monitor (thirteen read-only catalog checks, baseline diff, nothing that writes). If you want the count-with-two-keys and policy census run with evidence per finding, the $95 triage is one working day; the self-run version is the $29 audit kit. Work starts once the fixed-price milestone is funded — the review terms are on the page.

The one-line version

One Supabase key obeys row-level security and one switches it off, and they differ by a single field you can read without any secret. Classify every key in the repo by that field, keep the bypass kind on a server, and treat any sb_secret_ string in client code as a rotation event — not a cleanup task.

Prefer the verdict instead of running the toolkit yourself?

Fixed-price reviews with the evidence, the SQL and the written verdict. Fixes are quoted separately. Instant checkout, no account needed.

Want the free first step? The RLS Drift Monitor runs 13 read-only catalog checks on a schedule. It never reads application rows; zero findings is not proof of safety.

Prefer escrow? $49 drift monitor setup or $95 exposed-key triage on Upwork. Work starts only after the fixed-price milestone is funded.

Free entry

If you would rather run these checks yourself

Honest limit: a catalog check is not proof of a leak, and an empty log is not proof the key was never used. Zero findings does not mean safe. If you want a human: $29 self-run kit · $95 spot check (five tables, one working day) · $195 full audit — work starts only after payment is secured.

Template bundle

Review all 20 frontend starters in one bundle

20 editable frontend starters with live demos are $79 — one payment, no subscription.

View the Bundle — $79↗