Skip to content
Research

Three Ways Row-Level Security Still Broke: Email Rewrite, Writable Columns, and Sign-Inverted RPCs

In a 52-minute autonomous Breachger Assault assessment of a Next.js and Supabase SaaS API, table-level SELECT RLS held cleanly across every user table – yet three distinct bypasses let an external caller hijack any tenant's recovery email without a session, overwrite their own credit balance via PostgREST PATCH, and mint a million credits through open RPCs.

Row-Level Security was turned on. Cross-tenant SELECT queries against users, api_keys, and usage_logs all failed closed. Not a single customer email address, password hash, session token, or payment record leaked from any read endpoint. Yet in 52 minutes, an external attacker could still redirect any tenant's password-recovery email to an attacker-controlled inbox with zero authentication, raise their own account balance to 5,000 credits with a single PATCH, and spend those self-minted credits on paid metered API endpoints.

During an authorised 52-minute Breachger Assault engagement against a production Next.js and Supabase metered API platform, our autonomous swarm and independent verification engine mapped the live client bundle, API routes, PostgREST surface, and Supabase Auth settings. Eleven candidate issues were discovered; four unverified candidates were dropped automatically during isolated replay, and seven findings reproduced cleanly – reducing to three root authorization defects, one public-key enabler, and one unconfirmed framework version fingerprint. Client identity, domains, Supabase project references, API key prefixes, product-specific metered routes, bundle hashes, deployment identifiers, user UUIDs, and exact account values have been anonymized throughout this write-up.

Summary

  • Unauthenticated identity rewrite (F-1): A Next.js onboarding route (POST /api/auth/setup) used a privileged service_role client to run UPDATE users SET email = body.email WHERE id = body.user_id with no session check – allowing anyone with a tenant UUID to hijack that account's Supabase password-recovery email.
  • Row-level security without column-level grants (F-2): Allowing authenticated users to UPDATE their own users row left credits_balance writable over PostgREST. Paired with mailer_autoconfirm: true, any self-registered user could PATCH their balance to 5000 and immediately spend it on paid API routes.
  • Open SECURITY DEFINER RPCs with sign inversion (F-3–F-5): Three sibling billing functions (add_credits, deduct_credits, force_deduct_credits) remained executable by anon with no auth.uid() guard – reading any balance, minting 1,000,000 credits in one call, and flipping sign on negative input so force_deduct_credits credited instead of deducting.
  • Honest triage over scanner panic (F-6, F-7): The client bundle's Supabase anon JWT was classified as an enabler (Medium), not a "Critical leaked secret," because rotating it fixes nothing. A Next.js 16.1.6 version match (CVE-2026-27980) stayed Info because /_next/image returned 400 on every URL tested.
  • The fix: Derive user_id strictly from verified server sessions, restrict authenticated UPDATE grants on users to non-billing profile columns, revoke EXECUTE on all billing RPCs from PUBLIC/anon/authenticated, and enforce positive amount bounds inside every ledger function.

What 52 minutes of proof-gated testing established

After DNS ownership verification, Breachger Assault ran an external assessment across the target's live web application, API layer, and backing Supabase interface. Every finding below was independently replayed by an isolated verification engine before entering the report.

IDFindingSeverityCVSS v3.1CWE
F-1Unauthenticated POST /api/auth/setup rewrites any tenant's users.email, redirecting password recoveryCritical9.1CWE-306
F-2Client-writable users.credits_balance via PostgREST PATCH honoured by billing and paid routesHigh6.5CWE-915
F-3Anon-callable SECURITY DEFINER RPC add_credits reads any balance and mints 1,000,000 creditsHigh8.2CWE-862
F-4Anon-callable SECURITY DEFINER RPC deduct_credits discloses any user's balance with no sessionHigh8.2CWE-862
F-5Anon-callable SECURITY DEFINER RPC force_deduct_credits mutates balances in both directions (negative input credits)High8.2CWE-862
F-6Public Supabase anon JWT in client bundle + mailer_autoconfirm: true (enabler for F-2–F-5)Medium5.3CWE-798
F-7Next.js 16.1.6 disclosed in bundle (CVE-2026-27980), /_next/image precondition unconfirmedInfo0.0CWE-1395

Equally important is what held up – and where the report explicitly drew the line:

  • Controls that held up. Row-level SELECT isolation worked properly across users, api_keys, and usage_logs. Each account's JWT returned only its own records, and no cross-account read succeeded on GET /api/keys, GET /api/credits, or PostgREST tables. Zero customer email addresses, phone numbers, IP addresses, password hashes, session tokens, or payment details appeared in any unauthenticated or cross-tenant response.
  • Unverified noise excluded and boundaries logged. Four candidate issues hit transient egress 504 timeouts during isolated replay and were automatically excluded rather than padded into the report. Two open follow-ups were documented cleanly for a second pass: completing the final post-recovery login after the 303 #access_token redirect (interrupted by rate limiting), verifying cross-account PATCH /api/keys behavior, and auditing the checkout webhook where payment amounts appeared client-supplied.

Defect 1: The unauthenticated service_role setup route (F-1)

Teams using Supabase often invest heavily in database Row-Level Security – and then accidentally punch a hole right over the top of it inside a Next.js API route.

To finish onboarding a newly created user, the application exposed POST /api/auth/setup. Because the handler needed to write user profile state without tripping client-side permissions, it used Supabase's privileged service_role client – which bypasses RLS completely. The fatal omission was authentication: the route trusted user_id and email directly from the JSON request body without verifying a session cookie, bearer token, or ownership claim, and without checking whether the account had already completed onboarding.

Sending an unauthenticated POST with no cookies and no Authorization header succeeded immediately (host, UUID, and inbox anonymized):

curl -s -X POST \
  -H 'Content-Type: application/json' \
  -d '{"user_id":"00000000-0000-4000-8000-000000000011","email":"attacker@inbox.example"}' \
  https://app.target.example/api/auth/setup

The route answered HTTP/2 200:

{"success":true}

Verification did not stop at "success":true. Reading the target row back via PostgREST using the victim account's own JWT confirmed that users.email had actually been overwritten in the database to attacker@inbox.example. From there, the recovery chain was walked live:

  1. Calling POST https://project-ref.supabase.example/auth/v1/recover with the public anon apikey and {"email":"attacker@inbox.example"} triggered a password-recovery email directly to the attacker-controlled inbox.
  2. Following the recovery link to /auth/v1/verify returned HTTP 303 carrying #access_token=... in the redirect fragment.
  3. Upstream 429 throttling interrupted the final session replay against /api/keys, so the report documented the exact point reached rather than claiming a completed post-reset replay that had not finished.

Honest blast-radius scoping

Two details shaped the 9.1 Critical rating (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N):

  • UUIDs limit blind enumeration, not targeted takeover. Because user_id values are random UUIDv4 strings rather than sequential integers, an attacker cannot iterate 1..N blindly. However, any tenant UUID learned from a shared link, client response, log, or webhook becomes an instant unauthenticated takeover target.
  • Dual impact: hijacking plus owner lockout. Overwriting users.email both routes recovery tokens to the attacker and locks the legitimate owner out of self-service account recovery.

Defect 2: Row-level security without column-level grants (F-2)

Even if every custom Next.js API route were locked down and every RPC revoked, this application still had a second, quieter billing bypass baked directly into its users table permissions.

Many developers assume that writing a clean Supabase UPDATE policy – using (auth.uid() = id) with check (auth.uid() = id) – makes self-service profile edits safe. It does not. Row-Level Security restricts which rows a user can touch; it says nothing about which columns on that row they are allowed to modify.

On this target, users stored both user profile fields and the account's live credits_balance column in the same table, with table-wide UPDATE granted to the authenticated role and no column-level restriction or server-side trigger guarding credits_balance.

Meanwhile, GET /auth/v1/settings with the public anon key showed:

{
  "disable_signup": false,
  "mailer_autoconfirm": true
}

Because mailer_autoconfirm was enabled, any attacker could create an account and obtain a valid authenticated JWT in a single request without verifying an email address. With that own-account JWT, a single PostgREST PATCH rewrote their balance directly:

curl -s -X PATCH \
  -H 'apikey: <PUBLIC_ANON_KEY>' \
  -H 'Authorization: Bearer <USER_ACCESS_TOKEN>' \
  -H 'Content-Type: application/json' \
  -H 'Prefer: return=representation' \
  -d '{"credits_balance":5000}' \
  'https://project-ref.supabase.example/rest/v1/users?id=eq.00000000-0000-4000-8000-000000000042'

To prove this was not a dead display column ignored by billing, we queried the application's own billing endpoint and ran real metered requests using the account's API key:

  1. GET https://app.target.example/api/credits immediately returned "credits_balance": 5000 alongside the platform's per-route credit costs.
  2. Calling a 1-credit metered route (POST /api/enrich) succeeded and dropped the balance to 4999.
  3. Calling a 5-credit metered route (POST /api/query with mode=deep) succeeded and dropped the balance to 4994.

The self-written balance was live currency across the entire paid API. Under CVSS v3.1, authenticated self-tampering of integrity with no confidentiality loss scores 6.5 Medium (AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:N), while contextually on a metered SaaS API with open auto-confirmed signups it is an immediate High revenue-gate bypass.

Defect 3: Open SECURITY DEFINER RPCs and sign inversion (F-3–F-5)

Alongside the service_role route and writable table column sat a third classic PostgreSQL/Supabase failure pattern: three sibling billing functions (add_credits, deduct_credits, and force_deduct_credits) declared SECURITY DEFINER, left executable by PostgreSQL's PUBLIC / Supabase's anon role, and trusting p_user_id from the request body with no auth.uid() check.

Sending only the public browser apikey header – zero session cookie and zero Authorization header – reached all three RPCs:

curl -s -X POST \
  -H 'apikey: <PUBLIC_ANON_KEY>' \
  -H 'Content-Type: application/json' \
  -d '{"p_user_id":"00000000-0000-4000-8000-000000000042","p_amount":0}' \
  https://project-ref.supabase.example/rest/v1/rpc/add_credits

What each sibling function did when probed unauthenticated:

  • add_credits (F-3): p_amount: 0 returned the target account's live credit balance as a bare JSON scalar; p_amount: 1000000 minted one million credits onto the target account in a single request.
  • deduct_credits (F-4): p_amount: 0 returned the same live balance unauthenticated, exposing the sibling debit surface on the identical public interface.
  • force_deduct_credits (F-5): Not only did it expose and mutate arbitrary accounts without a session, it performed unchecked subtraction on p_amount – meaning passing a negative integer (p_amount: -1001) inverted the arithmetic and credited the target account instead of deducting from it.

One subtle classification detail matters for engineering teams reading reports: malformed values in p_user_id or p_amount returned PostgreSQL type-cast error 22P02, confirming both parameters were strictly typed (uuid and integer) rather than string-concatenated SQL. This was missing function-level authorization (CWE-862), not SQL injection – diagnosing the exact root cause prevents teams from wasting time "parameterizing" already-typed PL/pgSQL while leaving anon EXECUTE open.

Honest triage: the public anon key and Next.js CVE (F-6, F-7)

Most automated scanners would have paged engineering at 2 a.m. with two loud "Critical" alerts from this same run – and both would have wasted the team's first hour.

Why the Supabase anon key is an enabler, not a leaked secret (F-6)

The client JavaScript bundle initialized createClient("https://project-ref.supabase.example", "<PUBLIC_ANON_KEY>"). Static secret scanners routinely flag every Supabase JWT in a frontend chunk as a Critical credential exposure and advise "rotate the key immediately."

Rotating a Supabase anon key fixes nothing. The anon key is public by design – it ships to every visitor's browser in the next deploy. The real issue is the authority granted to anon and authenticated inside PostgreSQL (and mailer_autoconfirm: true letting anyone mint an authenticated JWT effortlessly). That is why F-6 was triaged at 5.3 Medium strictly as the access enabler for F-2 through F-5.

Why Next.js 16.1.6 (CVE-2026-27980) stayed Info (F-7)

The client bundle reported window.next = { version: "16.1.6" }, placing it inside the affected range of GHSA-3x4c-7xq6-9pq8 / CVE-2026-27980 (unbounded /_next/image disk-cache growth, fixed in 16.1.7 via images.maximumDiskCacheSize).

Rather than rubber-stamping a version match as a live Medium/High DoS, Breachger tested the live precondition and ruled out adjacent advisories:

  • Every tested URL against /_next/image (local assets and remote images alike) returned HTTP 400 text/plain (INVALID_IMAGE_OPTIMIZE_REQUEST), meaning no request ever reached the disk cache.
  • Adjacent advisories were explicitly excluded: CVE-2025-55182 did not apply (React 19.3.0), CVE-2026-94482 had no exposed Server Action IDs, and self-hosted or Windows-only advisories did not apply to the managed Linux deployment.

The result is clean operational guidance: upgrade to Next.js 16.1.7+ and configure images.maximumDiskCacheSize in normal maintenance, without pulling engineers off the live account takeover and billing bypasses.

Hardening a Next.js + Supabase stack in one migration

Every root defect above closes cleanly with surgical changes across the Next.js route handler and a single PostgreSQL migration.

1. Bind /api/auth/setup to the verified server session

Never accept user_id from a JSON body inside a service_role route. Resolve the caller from the verified Supabase server session (supabase.auth.getUser()), and if an onboarding helper only exists for first-run setup, reject calls once the user profile is already initialized:

const { data: { user }, error } = await supabaseServer.auth.getUser();
if (error || !user) {
  return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

// Use user.id from the verified JWT – never req.body.user_id.
// Never allow arbitrary email rewrites via service_role; route email changes
// through supabase.auth.updateUser({ email }) so Supabase sends confirmation links.

2. Replace table-wide UPDATE with column-level allowlists

Lock users so authenticated callers can only update explicitly safe profile columns – never credits_balance, email, role, or billing state:

-- Strip broad table-level UPDATE from client roles
revoke update on public.users from public, anon, authenticated;

-- Re-grant UPDATE strictly on safe profile columns (adjust to your schema)
grant update (display_name, avatar_url) on public.users to authenticated;

As defense in depth, move credit balances into an append-only ledger table or add a BEFORE UPDATE trigger that rejects any change to credits_balance unless auth.role() = 'service_role'.

3. Revoke EXECUTE on all billing RPCs and reject negative amounts

Audit every SECURITY DEFINER function in public, lock down the entire credit helper family at once, strip future default grants, and reject non-positive amounts inside the function body so sign inversion is impossible even from backend callers:

revoke all on function public.add_credits(uuid, integer) from public, anon, authenticated;
grant execute on function public.add_credits(uuid, integer) to service_role;

revoke all on function public.deduct_credits(uuid, integer) from public, anon, authenticated;
grant execute on function public.deduct_credits(uuid, integer) to service_role;

revoke all on function public.force_deduct_credits(uuid, integer) from public, anon, authenticated;
grant execute on function public.force_deduct_credits(uuid, integer) to service_role;

-- Prevent future migrations from re-exposing new functions to PUBLIC or anon
alter default privileges in schema public
  revoke execute on functions from public, anon;

Inside each debit/credit function, guard the sign explicitly (if p_amount <= 0 then raise exception 'p_amount must be positive'; end if;) and consider returning a structured JSON row rather than a bare scalar so mutations are unambiguous in telemetry and logs.

4. Priority remediation and verification matrix

RefTimeframeActionDeterministic retest check
F-1Immediate (0–24 hours)Require verified session in /api/auth/setup, ignore body user_id, route email changes through confirmed Auth flowsUnauthenticated POST /api/auth/setup returns 401; User A cannot alter User B's users.email
F-2Immediate (0–7 days)Revoke table-wide UPDATE on users from authenticated; allowlist profile columns only and guard credits_balance via trigger/service rolePATCH /rest/v1/users?id=eq.<own_uuid> with {"credits_balance": 5000} returns 403 permission denied
F-3–F-5Immediate (same migration)Revoke EXECUTE on add_credits, deduct_credits, and force_deduct_credits from PUBLIC/anon/authenticated; add p_amount > 0 checksUnauthenticated POST /rest/v1/rpc/* with only anon apikey fails closed with 401/403
F-6Short term (7 days)Keep anon key public but disable mailer_autoconfirm where unverified signups should not mint live authenticated sessionsGET /auth/v1/settings shows "mailer_autoconfirm": false and unconfirmed signups cannot hit paid routes
F-7Routine (7–30 days)Upgrade Next.js to 16.1.7+, configure images.maximumDiskCacheSize, and verify /_next/image config if image optimization is neededClient bundle reports >= 16.1.7; disk-cache bound configured

Takeaways for teams shipping Next.js and Supabase

  • RLS is row-level, never column-level. An auth.uid() = id UPDATE policy still lets every signed-in user rewrite their own credits_balance, plan, or is_admin column unless you enforce column-level grants or move billing out of user-writable tables.
  • Every service_role API route is an RLS bypass by definition. Treat onboarding, setup, and webhook helpers with the same session-binding rigor as admin routes – never trust a body-supplied user_id.
  • Audit RPC families together and validate signs. Default PostgreSQL PUBLIC execute grants expose SECURITY DEFINER helpers straight through PostgREST, and unchecked arithmetic turns a deduct helper into an unauthenticated credit minter on negative input.
  • Don't waste an incident rotating a public anon key. Shrink what anon and authenticated can execute and mutate in Postgres instead – and think twice before leaving mailer_autoconfirm: true open on a metered product.
  • Demand proof-gated triage. Separating a live 9.1 identity takeover and a proven billing bypass from an unconfirmed /_next/image version banner is what lets teams ship the right fix in an hour instead of drowning in false alarms.

This full assessment – from DNS ownership verification through autonomous discovery, isolated replay verification, and honest severity triage – completed in 52 minutes on Breachger Assault. If your team builds on Next.js, Supabase, or metered APIs and wants to verify your real identity and billing boundaries before your next release, you can start with a Single-App Proven Audit – one application and its APIs tested in 24 hours, with 100% of the $2,500 fee credited toward Continuous Assault within 30 days.