Mastodon

Field notes

5 Supabase support questions, settled by reproducing them

Run REVOKE as postgres on PostGIS's spatial_ref_sys table, and the SQL editor shows no error, but anon can still delete from it. Postgres often answers a permission mistake with a warning, not an error, so I reproduced five real Supabase questions in a Supabase-shaped Postgres and let the database settle each one.

· 5 cases · 11 offline tests

gives every project a Postgres database, with an API, sign-in and file storage built on it. Many of the questions people ask about it on GitHub come down to Postgres permissions: who can read a table, who granted what, and which role is asking.

So I built a small kit that starts a throwaway database shaped like a Supabase project's, and used it on five real threads. In two of them, the replies contradict each other. Each case runs the question step by step, as the right role, and every step is also a test. Here's what the runs settled, and the reply I'd send for each.

How each case runs

A real thread
The question and its replies
From Supabase's GitHub. In two of the five, the replies contradict each other
In Node.js
A Supabase-shaped Postgres
Supabase's roles, auth functions and default privileges, fresh on every run, in about a second
Out
A reply and a test
The reply I'd send, and steps that fail npm test if Postgres stops behaving that way
Five threads from Supabase's GitHub, reproduced on 25 and 26 November 2026.

The kit: a Supabase-shaped Postgres in Node.js

The kit runs , real Postgres compiled to WebAssembly, inside Node.js. There's nothing to install beyond npm and nothing to sign up for, and every run starts from a clean database. On top, it adds the parts support questions usually turn on, copied from Supabase's own repositories:

  • Roles: supabase_admin as the superuser, postgres as an ordinary role that can create roles, as on hosted projects, and the API roles anon, authenticated and service_role.
  • Functions: auth.uid(), auth.role(), auth.email() and auth.jwt(), reading the request's JWT claims.
  • Tables: auth.users, storage.buckets and storage.objects, with Supabase's column types and owners.
  • Privileges: Supabase's default privileges, which is why tables supabase_admin creates in public reach the API roles.

Most row level security questions are answered by one view: the same query, run as each identity.

Using the kit
import { startSupabaseDb, USERS } from "./src/supabase-db.js";

const db = await startSupabaseDb();
await db.run("create table public.notes (owner uuid, body text)", { as: "postgres" });

// The view that answers most row level security tickets:
const view = await db.whoSees("select * from public.notes", [
  { as: "anon" },
  { as: "authenticated", user: USERS.alice },
  { as: "service_role" },
]);

Each identity is reached the way a real connection reaches it. postgres logs in as itself, like the SQL editor. The API roles connect as authenticator and switch role, as the Data API does, and a signed-in user's id goes into the JWT claims:

src/supabase-db.js, lines 79 to 90
// Become the identity the way a real connection would, so that permission checks
// which look at the session user (such as SET ROLE) behave as they do on Supabase:
// - API roles: connect as authenticator, then SET ROLE, which is what PostgREST does
// - any other role (postgres, a migration role...): log in as that role directly
const becomeIdentity = API_ROLES.has(as)
  ? `set local session authorization authenticator; set local role ${quoteIdent(as)};`
  : `set local session authorization ${quoteIdent(as)};`;
const prelude =
  as === "supabase_admin"
    ? "begin;"
    : `begin; ${becomeIdentity}
       select set_config('request.jwt.claims', ${quoteLiteral(JSON.stringify(jwt))}, true);`;

That detail matters. The first version switched to postgres with SET ROLE from a superuser session. Postgres checks a role switch against the session user, so switches went through that should have been refused, and a step expecting "permission denied" caught it.

The kit has limits. There's no Data API, auth server or storage server, so questions about those need a real project. And PGlite runs Postgres 19, while hosted projects run 15 or 17: the behaviour in these cases is the same, but some messages are worded differently.

1. A REVOKE that only warns

The question (): PostGIS is installed in public. The poster ran REVOKE ALL on its spatial_ref_sys table as postgres, yet anon can still delete from it.

What the run showed: the table is created by supabase_admin, and Supabase's default privileges grant it in full to anon and authenticated, with supabase_admin as the grantor. In Postgres, only the role that made a grant can revoke it, so as postgres the REVOKE succeeds with warnings and changes nothing:

Case #52113, from its transcript (shortened)
-- As postgres, the role the SQL editor uses
revoke all on table public.spatial_ref_sys from anon, authenticated;
-- Succeeded, with no rows returned. Notices:
--   WARNING: no privileges could be revoked for "spatial_ref_sys"
--   WARNING: no privileges could be revoked for column "tableoid" of relation "spatial_ref_sys"
--   ...and 10 more like these, one for each column

select has_table_privilege('anon', 'public.spatial_ref_sys', 'DELETE') as anon_can_delete;
-- true

-- As supabase_admin, the role that made the grants
revoke all on table public.spatial_ref_sys from anon, authenticated;
select has_table_privilege('anon', 'public.spatial_ref_sys', 'DELETE') as anon_can_delete;
-- false

The reply, in short: the REVOKE didn't fail. It had nothing it was allowed to revoke, and the SQL editor doesn't display warnings, so it looked as if it worked. describes the same effect with pg_net. The fix the thread gave is right: reinstall PostGIS in the extensions schema. Plan it as a migration with a backup first, because dropping the extension also drops the geography columns that depend on it.

2. A foreign key to auth.users

The question (): a separate migration role should create public.profiles, with a foreign key to auth.users and a NOLOGIN role as its owner. One reply said to grant the migration role USAGE on auth and REFERENCES on auth.users. Two others said to create the table as postgres.

What the run showed: the grants only warn, with no privileges were granted for "auth", because postgres holds those privileges without the grant option. The migration role then gets permission denied for schema auth. Creating the table as postgres works. Handing it to the NOLOGIN owner first fails with must be able to SET ROLE "app_owner", and works after two extra steps:

As postgres, after creating the table
grant app_owner to postgres with set true, inherit false;  -- postgres created app_owner, so it may do this
alter table public.profiles owner to app_owner;            -- app_owner also needs CREATE on schema public

The reply, in short: create the table and its foreign key as postgres, grant the app role what it needs, and hand the table over only if the owner must change. One thing to plan for: with ON DELETE RESTRICT, deleting a user fails while they have a profile.

3. A membership postgres can't remove

The question (): on Postgres 17, a migration creates NOLOGIN owner roles, and a guard requires them to have no members. But postgres, which created them, is a member, so the guard fails. Three replies disagreed: one said the membership can't be revoked, another gave two REVOKE statements that leave "0 rows", and a third corrected the second.

What the run showed: Postgres 16 and later add the membership themselves when a role without superuser rights creates a role. This is the row it adds:

MemberGrantorADMININHERITSET
postgressupabase_admintruefalsefalse

Both REVOKE statements only warn, and the row stays, so the "0 rows" answer doesn't hold. The membership is also harmless. With INHERIT and SET off, postgres can't use the role's privileges or switch to it. It can only manage who else belongs to it.

The reply, in short: keep the guard, but let it accept exactly that row. Anything else, such as a role that can SET or INHERIT the owner role, still fails it:

A guard that passes when it returns no rows
select r.rolname as role, m.rolname as member, g.rolname as grantor,
       am.admin_option, am.inherit_option, am.set_option
from pg_auth_members am
join pg_roles r on r.oid = am.roleid
join pg_roles m on m.oid = am.member
join pg_roles g on g.oid = am.grantor
where r.rolname = 'trucking_importer_owner'
  and not (m.rolname = 'postgres' and g.rolname = 'supabase_admin'
           and am.admin_option and not am.inherit_option and not am.set_option);
-- No rows: the guard passes.

4. Multi-tenant row level security

The question (): a safe pattern for a multi-tenant app, where users belong to organisations and a platform owner can see everything. The thread was already well answered: look up organisations through a security definer helper, write separate policies for each command, freeze organization_id with a trigger, and read the platform-owner flag from a table, not the JWT.

What the run showed: the pattern holds. Here's who sees which products:

WhoSees
anonnothing
Alice, in AcmeAcme's product
Bob, in Acme and Globexboth products
Carol, the platform ownerboth products
service_roleboth products

It also found two edge cases the answers don't spell out. First, with check alone doesn't stop a row moving between organisations: Bob belongs to both, so it would let him move one, and only the freeze trigger stops it. Second, the platform owner's updates fail silently. Carol has no update policy, so her update matches no rows and returns no error.

The reply, in short: the pattern is solid. Keep the trigger, and give platform-owner writes their own deliberate path, such as a server-side function using the service role.

5. A docs example that failed for everyone

The issue (): the Storage guide's copy and move policies compared storage.objects.owner_id, a text column, with auth.uid(), which returns uuid. Every one of those policies failed when it was created. It was the next day.

The policy's check, before and after the fix
-- Before the fix: operator does not exist: text = uuid
owner_id = (select auth.uid())

-- After the fix: each user sees only their own objects
owner_id = (select auth.jwt()->>'sub')

-- Keeping auth.uid() also works, with a cast
owner_id = (select auth.uid()::text)

The case runs both versions, plus the fixed folder-based upload policy, which lets Alice upload into her own folder but not into Bob's. It stays in the kit as a regression test: if the fixed examples ever break again, npm test fails.

Three patterns across the five

  1. Warnings the SQL editor doesn't show. Two of the five are GRANT or REVOKE statements that only warned. Showing warnings under the result, as psql does, would remove a whole class of "it said success but nothing changed" tickets.
  2. Postgres 16 changed role membership. A role's creator becomes its admin automatically, and can't hand over ownership without SET (cases 2 and 3). A Knowledge Base entry would save the next ticket as more projects move to Postgres 17.
  3. SQL examples in docs can break unnoticed. Running every SQL example against a Supabase-shaped database in CI, the way this kit runs cases, would fail the build before anyone copied a broken one.

How I used AI

I used Claude Code throughout: to read Supabase's source, vet the threads, build the kit and draft the replies. Then I checked its work the way I'd check an answer before sending it to a customer. Every claim is a passing test against real Postgres. Supabase's definitions come from its repositories and are cited, not written from memory. And the cases caught the kit's own first mistake, the SET ROLE shortcut above.

Not every thread was worth answering. Two of the first candidates were already fixed or had a fix pending, and I kept only questions that are real and reproducible.

The sample

Everything above comes from : the kit, the five cases, each with its reply and a transcript of the run, and 11 offline tests. covers how I'd sort and answer a support queue, and what to escalate.

src/supabase-db.js (129 lines)
src/supabase-db.js
/**
 * A throwaway Postgres shaped like a Supabase project's database, running inside Node.js.
 *
 * It uses PGlite (real Postgres compiled to WebAssembly), so there's nothing to install
 * beyond `npm install`, nothing to sign up for, and every run starts from a clean database.
 *
 * "Supabase-shaped" means the parts support questions usually turn on (see bootstrap.sql):
 * - the superuser is supabase_admin, and postgres is an ordinary role, as on hosted projects
 * - the anon, authenticated and service_role roles the Data API switches to
 * - auth.uid(), auth.role(), auth.email() and auth.jwt(), copied from Supabase's auth repo
 * - minimal auth.users and storage tables, with Supabase's column types and owners
 *
 * What it is not: it has no Data API (PostgREST), no auth server and no storage server.
 * Questions about those need a real project.
 */

import { readFileSync } from "node:fs";
import { PGlite } from "@electric-sql/pglite";

const BOOTSTRAP_SQL = readFileSync(new URL("./bootstrap.sql", import.meta.url), "utf8");

/** The roles the Data API switches to. Requests reach them through authenticator. */
const API_ROLES = new Set(["anon", "authenticated", "service_role"]);

/** Fixed users for the cases, so outputs are the same on every run. */
export const USERS = {
  alice: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
  bob: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
  carol: "cccccccc-cccc-4ccc-8ccc-cccccccccccc",
};

/** Starts a fresh Supabase-shaped database. */
export async function startSupabaseDb() {
  const pg = new PGlite();

  // PGlite boots as a superuser called "postgres". On Supabase, that name belongs to an
  // ordinary role and the superuser is supabase_admin. Give the boot superuser Supabase's
  // name, so that grants and errors read exactly as they would on a hosted project.
  // (A role can't be renamed while it's the session user, hence the temporary superuser.)
  await pg.exec(`
    create role pglite_boot_tmp superuser;
    set session authorization pglite_boot_tmp;
    alter role postgres rename to supabase_admin;
    set session authorization supabase_admin;
    drop role pglite_boot_tmp;
  `);
  await pg.exec(BOOTSTRAP_SQL);
  return new SupabaseDb(pg);
}

/** Turns an identity into a label: "postgres", "authenticated (alice)" and so on. */
export function describeIdentity({ as = "supabase_admin", user } = {}) {
  const name = Object.entries(USERS).find(([, id]) => id === user)?.[0];
  return user ? `${as} (${name ?? user})` : as;
}

export class SupabaseDb {
  constructor(pg) {
    this.pg = pg;
  }

  /**
   * Runs SQL as one identity and reports what happened, without throwing.
   *
   * as     a role name: "postgres" (the SQL editor), "anon", "authenticated", "service_role",
   *        "supabase_admin", or any role a case creates
   * user   for "authenticated": the signed-in user's id. It's put in the JWT claims,
   *        so auth.uid() and auth.jwt() return it, as they would for an API request.
   * claims extra JWT claims, for example { app_metadata: { role: "platform_owner" } }
   *
   * Returns { ok, rows, error: { message, code }, notices: ["WARNING: ..."] }.
   * Everything runs in one transaction, which is committed if every statement succeeds.
   */
  async run(sql, { as = "supabase_admin", user, claims = {} } = {}) {
    const notices = [];
    const onNotice = (notice) => notices.push(`${notice.severity}: ${notice.message}`);
    const jwt = { role: as, ...(user ? { sub: user } : {}), ...claims };

    // Become the identity the way a real connection would, so that permission checks
    // which look at the session user (such as SET ROLE) behave as they do on Supabase:
    // - API roles: connect as authenticator, then SET ROLE, which is what PostgREST does
    // - any other role (postgres, a migration role...): log in as that role directly
    const becomeIdentity = API_ROLES.has(as)
      ? `set local session authorization authenticator; set local role ${quoteIdent(as)};`
      : `set local session authorization ${quoteIdent(as)};`;
    const prelude =
      as === "supabase_admin"
        ? "begin;"
        : `begin; ${becomeIdentity}
           select set_config('request.jwt.claims', ${quoteLiteral(JSON.stringify(jwt))}, true);`;

    try {
      const results = await this.pg.exec(`${prelude}\n${sql}\n;commit;`, { onNotice });
      const withRows = results.filter((result) => result.fields?.length);
      // The last result with columns is the one to show. The prelude's set_config
      // also returns a row, so skip it when the case's own SQL returned nothing.
      const own = withRows.filter((result) => result.fields[0]?.name !== "set_config");
      return { ok: true, rows: own.at(-1)?.rows ?? [], error: null, notices };
    } catch (error) {
      await this.pg.exec("rollback;").catch(() => {});
      return { ok: false, rows: [], error: { message: error.message, code: error.code }, notices };
    }
  }

  /**
   * Runs the same query as several identities: the "who sees what" view that answers
   * most row level security questions. Returns [{ identity, ok, rows, error }].
   */
  async whoSees(sql, identities) {
    const results = [];
    for (const identity of identities) {
      const result = await this.run(sql, identity);
      results.push({ identity: describeIdentity(identity), ...result });
    }
    return results;
  }

  async close() {
    await this.pg.close();
  }
}

function quoteIdent(name) {
  return `"${String(name).replace(/"/g, '""')}"`;
}

function quoteLiteral(text) {
  return `'${String(text).replace(/'/g, "''")}'`;
}

To run it, you need Node.js. After npm install, npm test runs every case as a test, and npm run case -- 52113 runs one and prints what happened.

Your turn

Which question would you reproduce next?

If you answer Postgres or Supabase questions, for customers or for your own team, I'd like to hear which case you'd add.

Get in touch

More support casebooks: Databento, self-hosted Bitwarden and MCP servers in Factory's Droid. Everything else is on Developer resources.