# Supabase

> Connect AI coding agents to Supabase through Osevel: what is tested, what init sets up, and how it differs from plain Postgres.

Source: https://osevel.com/docs/guides/supabase/

## Status

- **Spike run** on `supabase/postgres:17.11.0.019` and `supabase/postgres:15.19.0.019`, connected
  as `postgres` (not a superuser on Supabase; `supabase_admin` is). Script:
  `e2e/spikes/supabase-spike.ts`.
- **Installer verified** on both images by the container suite `e2e/install/supabase-15.test.ts`
  and `supabase-17.test.ts` (the same 14 tests as on plain Postgres 15/16/17 with a superuser
  admin), plus a manual install/uninstall into the image's real `postgres` database (with the
  `auth`/`storage` schemas and an RLS table referencing `auth.users`).

What `postgres` is on both images: `rolsuper = false`, `CREATEROLE`, `CREATEDB`, `BYPASSRLS`,
`REPLICATION`, `INHERIT`; it owns `public` and every table created through the dashboard or
migrations.

### How to run

```sh
# Spike (prints one JSON line per probe):
node e2e/spikes/supabase-spike.ts
SUPABASE_IMAGE=supabase/postgres:15.19.0.019 node e2e/spikes/supabase-spike.ts
# Installer suite (both Supabase images; AR_SUPABASE_IMAGES=a,b to override, AR_SKIP_SUPABASE=1 to skip):
pnpm vitest run --project e2e e2e/install/supabase-15.test.ts e2e/install/supabase-17.test.ts
```

## Observed behaviour and what the installer does about it

| #   | Question                                                                                                                                                                                                                                   | Observed (15 and 17)                                                                                  | Installer                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1   | Can `postgres` create the roles?                                                                                                                                                                                                           | Yes.                                                                                                  | Creates `<prefix>_owner` (NOLOGIN) and `<prefix>_agent/_migrator/_journal/_approver/_undo/_remote/_auditor` (LOGIN) with explicit NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT, a connection limit and per-role timeouts. Only attributes that differ are altered on re-install. Prefix default `ar`, configurable (roles are cluster-wide).                                                                                               |
| 2   | Can journal objects be handed to `ar_owner`?                                                                                                                                                                                               | Yes after `GRANT ar_owner TO postgres` (PG16+: the creator gets only ADMIN, not SET/INHERIT).         | `GRANT <owner> TO <admin> [WITH INHERIT TRUE, SET TRUE]`, then `ALTER ... OWNER TO <owner>` for the three schemas, journal tables and the owner-owned routines. The membership stays: the admin-owned gate and management routines use it to read the journal and to create in the trash schema.                                                                                                                                                                      |
| 3   | `SECURITY DEFINER` capture function with fixed `search_path`?                                                                                                                                                                              | Yes.                                                                                                  | `agent_reverse.capture_row()` owned by the owner role, `search_path = pg_catalog, pg_temp`, EXECUTE revoked from PUBLIC.                                                                                                                                                                                                                                                                                                                                              |
| 4   | Row trigger with `WHEN (session_user IN (...))` on a `postgres`-owned table?                                                                                                                                                               | Yes; app writes by `postgres` not captured, agent writes captured with correct op/changed_cols/xid.   | One trigger per managed table, `ENABLE ALWAYS` (so it fires even under `session_replication_role = replica`), gated on agent, migrator **and undo** (undo is journaled). Also placed on every table of the capture closure (cascading FKs, inheritance children, any schema).                                                                                                                                                                                         |
| 5   | `ar_agent` on an RLS table without a policy?                                                                                                                                                                                               | Sees 0 rows silently; INSERT fails `42501`.                                                           | **RLS mode is a required option** whenever a managed table has RLS (`RLS_MODE_REQUIRED` otherwise, nothing changed). `bypass`: `BYPASSRLS` on agent and undo. `policy`: permissive `FOR ALL USING (true) WITH CHECK (true)` policies `agent_reverse_agent` / `agent_reverse_undo` per RLS table (the journal and approver roles never get any RLS treatment: they have no user-table privilege), also added when RLS is enabled later (event trigger) or by `sync`.   |
| 6   | Fix A (per-table permissive policy) / Fix B (`ALTER ROLE ... BYPASSRLS`)?                                                                                                                                                                  | Both work. `postgres` has BYPASSRLS itself, so it can grant it on both majors.                        | Both offered (see 5). `doctor` notes when the admin lacks BYPASSRLS (then only `policy` is possible); `install` refuses `bypass` in that case.                                                                                                                                                                                                                                                                                                                        |
| 7   | Can `ar_agent` disable triggers, set `session_replication_role` (also via `set_config`), `SET ROLE`, `SET SESSION AUTHORIZATION`, read/write/call anything in `agent_reverse`, TRUNCATE, DROP/ALTER TABLE, toggle RLS, CREATE in `public`? | All denied (`42501`).                                                                                 | Asserted by SQLSTATE in the suite on every image, plus: CREATE SCHEMA, CREATE TRIGGER/POLICY, `setval`, unmanaged tables, the gate and the management routines. Key denials for the migrator, journal, approver and undo roles are asserted too.                                                                                                                                                                                                                      |
| 8   | READ ONLY transactions block writes (also via a writing function)?                                                                                                                                                                         | Yes (`25006`).                                                                                        | Unchanged; the executor must open reads with `BEGIN READ ONLY`.                                                                                                                                                                                                                                                                                                                                                                                                       |
| 9   | `GRANT postgres TO ar_migrator` (plan: migrator is a member of the table owner)?                                                                                                                                                           | **Refused on PG16+** ("permission denied to grant role"); a dedicated table-owner role fails as well. | **Design changed (D1).** The migrator gets no table privileges and no memberships. Schema changes run through `agent_reverse_api.run_approved_schema_change(id)`, owned by `postgres`, `SECURITY DEFINER`, EXECUTE only for the migrator, which executes only the statements stored on an approved, unexpired, unconsumed approval row. Works on both images.                                                                                                         |
| 10  | Can `postgres` create event triggers?                                                                                                                                                                                                      | Yes, and they fire for `postgres`'s own DDL.                                                          | Installs `agent_reverse_ddl` (ddl_command_end) and `agent_reverse_drop` (sql_drop), both `ENABLE ALWAYS`: new tables in managed schemas get trigger + grants immediately; disabling/dropping a capture trigger revokes the agent's and undo's writes. Also installs the DDL guard `agent_reverse_guard` (ddl_command_start, see below). If creation is refused (`42501`), install falls back silently, records it, and `verify` warns `no_event_trigger`; use `sync`. |
| 11  | `ALTER ROLE ... SET session_replication_role` by `postgres`?                                                                                                                                                                               | Denied (`42501`) on both images.                                                                      | `verify` still checks role and database settings for it (a superuser could set it on plain Postgres), and the capture trigger is `ENABLE ALWAYS` anyway.                                                                                                                                                                                                                                                                                                              |
| 12  | `ALTER ROLE ... NOREPLICATION` by `postgres` on PG15?                                                                                                                                                                                      | Accepted (PG15 core alone would demand superuser; the image permits it).                              | Only attributes that differ from the target are mentioned in `ALTER ROLE`, so this is not needed for freshly created roles.                                                                                                                                                                                                                                                                                                                                           |
| 13  | Uninstall as `postgres`?                                                                                                                                                                                                                   | The spike's `DROP OWNED BY` failed: "permission denied to drop objects".                              | `uninstall` never uses `DROP OWNED`/`REASSIGN OWNED`. Order: refuse if the trash holds tables (unless `force`), drop event triggers, drop capture triggers and `agent_reverse_*` policies, `DROP SCHEMA ... CASCADE` for the three schemas, revoke every remaining privilege found in `pg_shdepend` for this database, `DROP ROLE`. Tested on both images: nothing named `agent_reverse*` or `ar_*` remains.                                                          |

## Security round (red-team findings F-01, F-03, F-13, R6)

Observed on both images (`supabase/postgres:15.19.0.019`, `17.11.0.019`), as an ordinary login
role created by `postgres`:

- **supautils (`supautils.version` 4.0.0)** lists dblink, http, pg_net, pg_cron, postgres_fdw,
  pg_tle, pgsodium, supabase_vault, wrappers and ~60 others in
  `supautils.privileged_extensions` and creates them as `supabase_admin` for **any** role,
  regardless of `CREATE` on the database. This is F-01.
- **The installer's DDL guard stops it.** An event trigger on `ddl_command_start` (all commands,
  `ENABLE ALWAYS`, function owned by `postgres`, `SECURITY DEFINER`) fires before supautils hands
  the command to `supabase_admin`, and `session_user` is still the login role there. Verified on
  both images with a direct connection as the agent role: `CREATE EXTENSION IF NOT EXISTS
http|dblink|pg_net|pg_cron|postgres_fdw`, the same inside `DO ... EXECUTE`, `CREATE TEMP
TABLE`, `CREATE FUNCTION pg_temp.f()` all fail with `42501` and no extension is created. The
  same holds for the journal, approver, undo and (outside the gate) migrator roles.
- On Supabase an install without the guard (`eventTrigger: false`, or the event trigger later
  dropped) is a **blocking `verify` violation** (`ddl_guard_missing`); install refuses. On plain
  Postgres with a non-superuser admin (no event triggers possible) it is a warning: the login
  roles cannot create extensions or persistent objects there (CREATE is revoked everywhere), only
  temporary objects.
- **How capabilities are granted** (after `CREATE EXTENSION` by `postgres`):

  | Extension                  | Schema (default) | PUBLIC has schema USAGE | Callable by an ordinary role                                                                                                           |
  | -------------------------- | ---------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
  | pg_net                     | `net`            | yes                     | all 12 functions incl. `net.http_get/http_post`; INSERT on `net.http_request_queue`                                                    |
  | pgsodium                   | `pgsodium`       | yes                     | 55 functions incl. `pgsodium.create_key` (SECURITY DEFINER)                                                                            |
  | http, dblink, postgres_fdw | `extensions`     | no                      | none (EXECUTE is granted to PUBLIC, but the schema is not usable); callable as soon as installed into a usable schema such as `public` |
  | pg_cron                    | `cron`           | no                      | none                                                                                                                                   |
  | supabase_vault             | `vault`          | no                      | none                                                                                                                                   |

  Built-ins: `lo_create`, `lo_from_bytea`, `lowrite`, `lo_unlink`, `pg_notify` are executable by
  PUBLIC (as on plain Postgres); server-file functions (`pg_read_file`, `lo_import`, ...) are not.
  No foreign-data wrapper or server is usable by PUBLIC.

- **What the installer does (R5):** `verify` and the cheap `verifyCapabilities` (for the
  executor to run periodically) list every capability the agent role can actually use (EXECUTE
  plus schema USAGE): pg_net, http, dblink, postgres_fdw, foreign wrappers/servers, pg_cron,
  pgsodium, supabase_vault, wrappers, pg_tle, server files. Each is a **blocking violation**
  unless the installing human accepts it by name (`acceptRisks`, stored in
  `install_settings.accepted_risks`); an extension enabled after install (e.g. pg_net through
  Database Webhooks) turns the next periodic check red. Large-object writers and `pg_notify` are
  warnings; every non-system SECURITY DEFINER function the agent can call is a warning with
  remediation. Direct grants of such functions to our roles are revoked by install; grants to
  PUBLIC are left alone (revoking them would change the application) and reported with
  remediation (`REVOKE USAGE ON SCHEMA net FROM PUBLIC`, then grant to the roles that need it).
- **R6, Data API exposure:** the real `postgres` database has
  `ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO anon,
authenticated, service_role` (also for functions and sequences). A table created through the
  approval gate is owned by `postgres` and therefore gets ALL (including TRUNCATE) for `anon` and
  `authenticated` immediately, with RLS off: it is exposed through the Data API until RLS is
  enabled. Observed on both images. `verify` and `doctor` report every managed table without RLS
  that `anon`/`authenticated` can access (`exposed_without_rls`, warning). Scratch databases do
  not have these default privileges; the test suite recreates them.

## Capture path and user-defined casts (R9)

Verified on both Supabase images and plain Postgres 17: before the fix, a user enum/range type with
`CREATE CAST (t AS json) WITH FUNCTION ...` made the capture trigger run that function as the owner
role on every agent write (the test function inserted 18 policy rows and deleted `row_log`). Since
the fix, capture renders such columns as text (`agent_reverse_api.row_image`) and no user code runs
in the capture path; behaviour is identical on Supabase and plain Postgres.

## Second round: fail-closed capabilities and rules (F-23, F-25)

Verified on both images: our `ddl_command_end` event triggers fire for extensions that supautils
creates as `supabase_admin` on behalf of `postgres` (each script command arrives with
`in_extension = true`, then the outer `CREATE EXTENSION`), and for `GRANT`/`REVOKE`,
`ALTER DEFAULT PRIVILEGES` and `CREATE RULE` by `postgres`. When a network/escape capability
becomes usable by the agent role (e.g. `CREATE EXTENSION dblink WITH SCHEMA public`, or
`GRANT USAGE ON SCHEMA <ext schema> TO PUBLIC`) and was not accepted at install, the database
revokes all of the agent role's privileges on the managed tables in the same transaction (reads
included); `sync` restores them only once the capability is gone or accepted. Not observable:
role memberships granted to the agent role and `ALTER ROLE` (shared objects), superuser catalog
edits. A rewrite rule on a managed or capture-closure table fails closed the same way for writes.

## Third round (F-23 residual, F-24, F-25, F-29)

- **Complete cut-off works on both images as `postgres`.** Inside the event trigger (SECURITY
  DEFINER, owned by `postgres`) `ALTER ROLE <agent> NOLOGIN` succeeds (`postgres` holds ADMIN on
  roles it created; CREATEROLE on 15) and `pg_terminate_backend` on the agent's sessions succeeds
  (`postgres` is a member of `pg_signal_backend`). Verified with a live session: it receives
  "terminating connection due to administrator command".
- **SECURITY DEFINER functions:** on a fresh `postgres` database of both images no SECURITY
  DEFINER function is callable by an ordinary role (`auth`, `extensions`, `graphql`, `vault`,
  `realtime`, `storage` are closed to PUBLIC; `pgsodium` and `pg_net` are not installed by
  default and are covered by their own named risks). A default install therefore needs no
  acknowledgement; application wrappers in `public` do (`security_definer_functions`).
- **Foreign tables:** `postgres_fdw`/`wrappers` foreign tables granted to PUBLIC or the agent
  (directly or through a view) are the `foreign_tables` risk; granting one cuts the agent off.

## Accepted SECURITY DEFINER items (F-30)

Identical on both images and plain Postgres: any schema change run through the approval gate while
SECURITY DEFINER functions or triggers are accepted re-opens those acceptances and cuts the agent
off (functions) or revokes its writes on the affected tables (triggers) until a human re-accepts
them at install. Changes made by the application's own roles to code those functions call are not
detected and remain the application owner's responsibility.

## Differences between plain Postgres and Supabase

| Aspect                                                                                         | Plain Postgres (admin = superuser)                                      | Supabase (admin = `postgres`, not superuser)                                                               |
| ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| Approved schema changes (gate) run as                                                          | the superuser                                                           | `postgres` (cannot do superuser-only things)                                                               |
| Tables managed                                                                                 | every table in the managed schemas (the superuser can act as any owner) | tables whose owner `postgres` can act as; others (e.g. owned by `supabase_admin`) are skipped and reported |
| Event triggers                                                                                 | yes                                                                     | yes (allowed for `postgres` on these images)                                                               |
| `ALTER ROLE ... SET session_replication_role`, `... SUPERUSER`, giving objects to a login role | possible for the admin; `verify` detects them                           | refused to `postgres`                                                                                      |
| `pg_authid` (to inspect SCRAM verifiers)                                                       | readable                                                                | not readable                                                                                               |

## Things to know

- **Role split (R1):** the MCP server holds `journal` (recorder) and `agent`/`migrator`; the CLI
  holds `approver` (decisions, policy) and `undo` (restores). Neither `journal` nor `approver`
  has any privilege on a user table, so no user code runs with the rights that decide approvals.

- **Hosted only, not reproducible here:** network policies, SSL enforcement, Supavisor. With a
  pooler, `session_user` is still the login role, so capture holds; the executor needs a
  session-scoped transaction per statement (session mode or a direct connection).
- **Supabase default privileges** (`ALTER DEFAULT PRIVILEGES ... IN SCHEMA public ... TO anon,
authenticated, service_role`) still apply to tables created through the gate. They do not involve
  the osevel roles. The installer resets privileges of its own objects to exactly the
  documented set, whatever default privileges exist.
- **`auth.users` cascades** into `public` tables are done by Supabase roles, not the agent, and are
  not captured (by design: app writes are not journaled).
- The SCRAM verifier, not the password, is sent in `ALTER ROLE ... PASSWORD` (computed
  client-side). Server statement logs / pgaudit may still record the verifier.
