Run as a least-privilege database role
The SupaCloud server needs two things from PostgreSQL: a role that can change the
schema when migrations run, and a role that reads and writes rows while it serves
requests. They should be different roles. A server that connects as a superuser
gives any SQL injection COPY ... TO PROGRAM (a shell in the database container),
every database on the cluster and every row, whatever row security says.
This guide splits the control-plane identity into three roles:
| Role | Login | Holds | Used by |
|---|---|---|---|
supacloud_owner |
no | Owns the supacloud database, the public and auth schemas and every table |
Nobody logs in as it. The migrator assumes it. |
supacloud_migrator |
yes | Membership in supacloud_owner |
SUPACLOUD_MIGRATION_DATABASE_URL: sqlx migrations and the pre-migration auth objects |
supacloud |
yes | SELECT, INSERT, UPDATE, DELETE on the tables, sequence use |
DATABASE_URL: the running server |
None of the three is SUPERUSER, BYPASSRLS or CREATEROLE. The cluster’s
bootstrap superuser stays for administration only, and the server environment does
not hold its password.
What the server enforces
Section titled “What the server enforces”- Boot check. At boot the server reads
rolsuperandrolbypassrlsfor the roleDATABASE_URLconnects as. WithMODE=prodit refuses to boot when either is true, and also when the check cannot run. In dev mode it logs an error and boots. - Metric.
/metricsexportssupacloud_db_runtime_role_privileged:1for a SUPERUSER or BYPASSRLS runtime role,0for a least-privilege one,-1when the check could not run. The shipped ruleSupaCloudDbRuntimeRolePrivilegedpages (severitycritical) on1; see Observability with Prometheus and Grafana. - Ownership. The same check reads whether the runtime role owns the schema it
writes into or a table in it, or can become their owner (the login identity is a
member of the owning role).
/metricsexportssupacloud_db_runtime_role_owner:1for such a role,0for one with DML grants only,-1when the check could not run. Ownership is a warning, never a boot refusal: the server logs a WARN and the shipped ruleSupaCloudDbRuntimeRoleOwnerwarns after 15 minutes on1. The single-role shape below reads1by design. - Migrator URL. Migrations run on
SUPACLOUD_MIGRATION_DATABASE_URLwhen it is set, and onDATABASE_URLotherwise. With one URL for both, that role must own the schema, which is the single-role shape below.
Before you start
Section titled “Before you start”- Upgrade to a release that contains migration
604(control_plane_rls_disabled_for_runtime_role) and boot it once in your current shape. That migration disables the unforced row-level-security switch on the tables that carry the historical, inertauth.uid()policies. The policies stay, but a runtime role that no longer owns the tables would otherwise see zero rows in those tables. - Back up the database (see Run migrations and upgrade).
- You need a superuser session that is not the role the server connects as. With
the bundled Compose Postgres,
POSTGRES_USER(supacloud) is that superuser, so create a separate one first (step 1).
Split the roles
Section titled “Split the roles”-
Create a bootstrap superuser the server never sees. Connected as the current superuser:
CREATE ROLE pgadmin LOGIN SUPERUSER PASSWORD '<a new password>';Keep that password in your password manager or secret store, never in the server
.env. Reconnect aspgadminfor every following step. -
Create the extensions the migrations expect. A non-superuser cannot create every extension (
vectoris not trusted everywhere, andpg_stat_statementsneedsshared_preload_libraries=pg_stat_statements). Create them once aspgadmin; the migrations then find them and skip the step:\c supacloudCREATE EXTENSION IF NOT EXISTS pgcrypto;CREATE EXTENSION IF NOT EXISTS vector; -- when availableCREATE EXTENSION IF NOT EXISTS pg_stat_statements; -- when preloaded -
Create the owner, the migrator and the artifact floor owner.
CREATE ROLE supacloud_owner NOLOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB;CREATE ROLE supacloud_migrator LOGIN PASSWORD '<migrator password>'NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB IN ROLE supacloud_owner;DO $$ BEGINIF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = 'supacloud_artifact_floor_owner') THENCREATE ROLE supacloud_artifact_floor_owner NOLOGIN NOINHERIT NOSUPERUSERNOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION;END IF;IF EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = 'supacloud_artifact_floor_owner'AND (rolcanlogin OR rolinherit OR rolsuper OR rolbypassrls OR rolcreaterole OR rolcreatedb OR rolreplication)) THENRAISE EXCEPTION 'unsafe artifact floor owner';END IF;END $$;GRANT supacloud_artifact_floor_owner TO supacloud_owner WITH INHERIT FALSE, SET TRUE;supacloud_artifact_floor_ownerowns the private artifact floors (step 6). It is a role of its own, never the application owner: the floor qualification refuses an owner that inherits, and the step-5 grant block, which is keyed on the application owner, would otherwise hand the runtime the floor relations. TheDOblock creates it once and refuses a pre-existing role with unsafe attributes instead of changing it.The membership goes to
supacloud_ownerbecause migrations run as that role (theroleoption in step 8): the floor migrations check that the role they run as canSET ROLEto the floor owner and hand objects to it as that role.INHERIT FALSEkeeps the floor relations out of the application owner’s privileges; it reaches them only through an explicitSET ROLE. The runtime role is never a member, not even without inheritance. -
Move the ownership, in the
supaclouddatabase.REASSIGN OWNEDmoves every object the old role owns in this database, plus every database it owns:\c supacloudREASSIGN OWNED BY supacloud TO supacloud_owner;ALTER DATABASE supacloud OWNER TO supacloud_owner;ALTER SCHEMA public OWNER TO supacloud_owner;ALTER SCHEMA auth OWNER TO supacloud_owner; -
Demote the runtime role and grant it data access only.
ALTER ROLE supacloud NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB;GRANT CONNECT ON DATABASE supacloud TO supacloud;GRANT USAGE ON SCHEMA public, auth TO supacloud;DO $$DECLARErelation record;core_floor_configured boolean := false;BEGINIF pg_catalog.to_regprocedure('public.artifact_recovery_floor_configured()') IS NOT NULL THENEXECUTE 'SELECT public.artifact_recovery_floor_configured()' INTO core_floor_configured;END IF;FOR relation INSELECT n.nspname, c.relnameFROM pg_catalog.pg_class cJOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespaceWHERE c.relowner = 'supacloud_owner'::regroleAND n.nspname IN ('public', 'auth')AND c.relkind IN ('r', 'p', 'v', 'm', 'f')AND NOT (core_floor_configuredAND n.nspname = 'public'AND c.relname = 'artifact_staging_authority')LOOPEXECUTE pg_catalog.format('GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.%I TO supacloud',relation.nspname, relation.relname);END LOOP;FOR relation INSELECT n.nspname, c.relnameFROM pg_catalog.pg_class cJOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespaceWHERE c.relowner = 'supacloud_owner'::regroleAND n.nspname IN ('public', 'auth')AND c.relkind = 'S'LOOPEXECUTE pg_catalog.format('GRANT USAGE, SELECT, UPDATE ON SEQUENCE %I.%I TO supacloud',relation.nspname, relation.relname);END LOOP;FOR relation INSELECT DISTINCT d.refobjid::regprocedure AS routineFROM pg_catalog.pg_depend dJOIN pg_catalog.pg_policy pol ON pol.oid = d.objidJOIN pg_catalog.pg_class c ON c.oid = pol.polrelidJOIN pg_catalog.pg_proc p ON p.oid = d.refobjidWHERE d.classid = 'pg_catalog.pg_policy'::regclassAND d.refclassid = 'pg_catalog.pg_proc'::regclassAND c.relowner = 'supacloud_owner'::regroleAND p.proowner = 'supacloud_owner'::regroleLOOPEXECUTE pg_catalog.format('GRANT EXECUTE ON FUNCTION %s TO supacloud', relation.routine);END LOOP;END$$;GRANT EXECUTE ON FUNCTION public.usage_credential_visible_in(uuid, text, uuid) TO supacloud;SELECT public.realtime_capture_orphan_privileges();ALTER DEFAULT PRIVILEGES FOR ROLE supacloud_owner IN SCHEMA public, authGRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO supacloud;ALTER DEFAULT PRIVILEGES FOR ROLE supacloud_owner IN SCHEMA public, authGRANT USAGE, SELECT, UPDATE ON SEQUENCES TO supacloud;ALTER DEFAULT PRIVILEGES FOR ROLE supacloud_ownerREVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;The loop grants on the relations the application owner owns when it runs, and the default privileges cover the tables and sequences that owner creates later. The third loop grants
EXECUTEon every function of the owner that a row-security policy of one of the owner’s tables calls: since migration 873 those functions, and every function the owner creates later, are no longer executable byPUBLIC, so the runtime would otherwise be refused when it reads such a table. The server also callsusage_credential_visible_indirectly, which no policy names, so it is granted by name.realtime_capture_orphan_privileges()grants the capture-orphan resolver to every role that may write capture lifecycles, which after the table loop includes the runtime. Relations owned by another role — the private artifact floor owner — are not touched, which is why the block is keyed on the owner instead ofGRANT ... ON ALL TABLES IN SCHEMA: a schema-wide grant reaches the private floors, and a server with the artifact witness configured then refuses to boot.One application-owned table is skipped once the core artifact floor is configured:
artifact_staging_authority. While the floor is unconfigured the server writes that table directly, so the block grants it like every other table. The Core provisioner then configures the floor and removes the runtime’s direct privileges on it; from then on the server reaches it only through the floor’s exact-row functions.artifact_recovery_floor_configured()is the predicate the server itself routes on, and the block reads it, so a re-run after provisioning grants nothing on that table. Before migration 766 exists the function is absent and the block grants as before. Re-running this block is safe, before and after provisioning.A direct privilege on
artifact_staging_authoritythat reappears on a provisioned floor, for example from a hand grant, is not removed again: the next Core run refuses withthe runtime or PUBLIC holds a direct artifact_staging_authority privilege again …; revoke it before re-running. Revoke the grant and run the provisioners again.If you later change a grant by hand, run
REASSIGN OWNED, or otherwise move a floor object out of shape, re-run this block and then the provisioners in the order core,--report,--mail,--archive-settle. They restore the receipt and privilege shape they can prove and print every privilege they restored; a floor object they do not own is refused with the named check instead of being changed. The Core provisioner also installs the 766 qualification when migration 766 ran without the role setting — the shape this guide produces — and refuses a floor it cannot prove rather than adopting it.The provisioners’ one-run connection is the bootstrap superuser (
pgadmin); aBYPASSRLS-only login is refused before any change.For a rolling switch that moves the report run receipt to the floor owner, put every replica on the new server version first, then run
--report, then set the witness URL. An older replica’s 776 check still requires the application owner and answers the moved receipt with a qualification refusal, so drain old replicas from the report path before the provisioner run.If a provisioner run stops with
a 766 custody table is not empty: <table>, the named custody table holds rows while the floor is unqualified. The unqualified guards prevent the product from writing those rows, so the provisioner cannot prove the custody and refuses instead of adopting it. There is nothing to repair by hand: deleting the row would destroy the custody evidence the refusal names. Treat the run as stopped and clarify the row’s origin before provisioning again.A logical backup must run as a superuser or as a role that can
SET ROLEto the floor owner; a read-only role granted only on the application owner’s tables cannot read the floor tables after provisioning. -
Provision the private artifact floors and their witness.
The private floors (766 core, 775 report, 779 mail archive, 783 archive settlement) and the server-only witness are installed by the operator binary
provision_artifact_floor, not by the migrations. The binary ships at/usr/local/bin/provision_artifact_floorin the server image: run it as a one-shot container from the same image tag as your server, and give only that one-shot the provisioner connection. The witness is a separate login that the server reads the private receipts with; it is never the runtime role and never a member of the floor owner.CREATE ROLE supacloud_witness LOGIN PASSWORD '<witness password>'NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOINHERIT;Run the provisioners from the bootstrap superuser’s connection, in the order core,
--report,--mail,--archive-settle:Terminal window export SUPACLOUD_ARTIFACT_PROVISIONER_DATABASE_URL='postgresql://pgadmin:<password>@<host>/supacloud'provision_artifact_floor supacloud_artifact_floor_owner supacloud supacloud_witnessprovision_artifact_floor --report supacloud_artifact_floor_owner supacloud supacloud_witnessprovision_artifact_floor --mail supacloud_artifact_floor_owner supacloud supacloud_witnessprovision_artifact_floor --archive-settle supacloud_artifact_floor_owner supacloud supacloud_witnessThe first argument is the dedicated floor owner from step 3, never
supacloud_owner. The provisioner connection is a superuser, so the ownership transfers it performs need noCREATEonpublicfor the floor owner.Finally, give the server the witness login as its separate connection:
Terminal window SUPACLOUD_ARTIFACT_WITNESS_DATABASE_URL='postgresql://supacloud_witness:<password>@<host>/supacloud'Set both database URLs from the deployment’s secret store; do not type them into a shell history.
The server proves at boot that the witness login is distinct from the runtime and the floor owner, inherits neither, and connects to the same database and host; it checks the core role and privilege shape and the owner and isolated-store floors that exist at that moment, and refuses to start when any of it is unqualified. The per-floor install receipts are not a boot gate: the admin feature panel reports the witness and each known floor’s installed/matches state by name — a floor is available only when it is installed and matches this binary — and each witness call enforces its own floor at use time. Until the witness is configured, attended mail capture answers a named refusal instead of a generic one.
-
Keep the runtime role out of the tenant databases. When the cluster also hosts the built-in Apps or workflow databases:
REVOKE CONNECT ON DATABASE supacloud_apps FROM PUBLIC, supacloud;REVOKE CONNECT ON DATABASE supacloud_workflows FROM PUBLIC, supacloud;SUPACLOUD_APPS_DATABASE_URLandSUPACLOUD_WORKFLOWS_DATABASE_URLconnect asapp_runtimeandworkflow_runtime, which own those databases and keepCONNECT. -
Point the server at both identities in
.env. The migrator logs in assupacloud_migratorand assumes the owner role through the connectionoptions, so every object a migration creates is owned bysupacloud_owner. The second option names the runtime role for the artifact floor migrations:Terminal window DATABASE_URL=postgresql://supacloud:<runtime password>@postgres:5432/supacloudSUPACLOUD_MIGRATION_DATABASE_URL=postgresql://supacloud_migrator:<migrator password>@postgres:5432/supacloud?options=-c%20role%3Dsupacloud_owner%20-c%20supacloud.artifact_runtime_role%3DsupacloudSet this option only after step 6 provisioned the core floor: migration 834 reads it as the promise of a configured floor and refuses on an unconfigured one. On a configured floor a floor migration (766, 792, 834 and 860 are the ones so far) uses it to hand its new objects to the floor owner and grant the runtime exactly what it needs; 792 and 860 refuse to run on a configured floor without it. The floor owner is the documented
supacloud_artifact_floor_owner, sosupacloud.artifact_floor_owner_rolecan stay unset. Handing an object to the floor owner needsCREATEonpublicfor that owner while the migration runs. Grant it aspgadminbefore every server upgrade that runs migrations, and take it back once the migrations have finished:GRANT CREATE ON SCHEMA public TO supacloud_artifact_floor_owner;-- start the new server version and wait until its migrations finished, then:REVOKE CREATE ON SCHEMA public FROM supacloud_artifact_floor_owner;SELECT pg_catalog.has_schema_privilege('supacloud_artifact_floor_owner', 'public', 'CREATE'); -- fWithout the grant such a migration stops with a permission error and the server does not start; nothing is half applied, because each of these migrations runs in one transaction.
Rotate the runtime password now if the old superuser password was ever in the server environment:
ALTER ROLE supacloud PASSWORD '<new password>';. -
Restart and check. Start the server with
MODE=prod. It boots, the log shows no database-role error, andsupacloud_db_runtime_role_privilegedandsupacloud_db_runtime_role_ownerboth read0.
Verify the posture
Section titled “Verify the posture”Connected as the runtime role, the first statement returns f | f and the other three must fail:
SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user; -- f | fCOPY (SELECT 1) TO PROGRAM 'true'; -- ERROR: permission deniedCREATE ROLE should_not_exist; -- ERROR: permission deniedALTER TABLE workspaces ADD COLUMN x int; -- ERROR: must be ownerTransport encryption
Section titled “Transport encryption”DATABASE_SSL_MODE defaults to require. Keep it there whenever the connection to
PostgreSQL crosses a network you do not control. disable is reasonable only on a
private container network or an encrypted overlay (for example WireGuard), where the
database has no published port. Never expose the PostgreSQL port publicly, and do not
put agent containers on the network that carries the database host (see
SUPACLOUD_AGENT_NETWORK_DB_GUARD in the
environment variable reference).
Related
Section titled “Related”- Run migrations and upgrade
- Environment variables:
DATABASE_URL,SUPACLOUD_MIGRATION_DATABASE_URL,DATABASE_SSL_MODE - Secret provisioning: both database URLs are secrets and can come from OpenBao