Appearance
0005. Per-module database roles
Status: accepted. Applies to crates/kernel (bus, registry, migration 0003), crates/events (migration 0002, PgBus, relay), crates/jobs, every module's migrations, crates/test-kit and deploy/postgres.
Context
kernel.grant_runtime gave the single orbit_runtime role full DML on every module's tables, so any module's handler could read or write payroll.*. Contract rule 2.3 ("modules own their data") was enforced only by review. The same role could insert any catalogue event into the outbox and mark any subscriber's delivery as processed. Events reaching a disabled module were dropped, a subscriber had no way to fail an event at once, and a down migration could not see whether a table under FORCE row-level security held any row (issue #10).
Decision
- One NOLOGIN role per module,
orbit_mod_<id>.orbit migrate(Registry::migrate) creates every compiled module's role before any module migration runs, throughorbit_roles.ensure_module_role(module). - A role admin, not the owner, creates roles. The superuser's
deploy/postgres/init/02-module-roles.sqlcreates a NOLOGINorbit_role_adminwithCREATEROLEandADMIN OPTIONonorbit_runtime(INHERIT FALSE, SET FALSE), and theSECURITY DEFINERfunctionorbit_roles.ensure_module_roleit owns (search path pinned,EXECUTEonly to the database owner, and it refuses any caller that does not own schemakernel). It only creates and wiresorbit_mod_<validated id>. The owner (orbit_migrator) has neitherCREATEROLEnor any membership inorbit_runtime. The function lives in its own schemaorbit_roles, notkernel: the superuser script runs before the owner's first migration createskernel, and only a superuser can create a function owned byorbit_role_admin. It refuses a pre-existingorbit_mod_<id>unlessorbit_role_adminholds ADMIN on it (it made it), it is a member of nothing butorbit_runtime, and it has none of LOGIN, SUPERUSER, BYPASSRLS, CREATEROLE, CREATEDB or REPLICATION. - Module roles inherit the platform, not each other. Each module role is a member of
orbit_runtime, so it has every platform grant (tenants, enablement, audit insert, memberships, outbox insert,events.processed,jobs.enqueue,pii.tenant_keys).orbit_runtimeis the shared group the planner calledorbit_module_base: platform crates keep granting to it, and nothing has to be granted twice. - Module tables are granted to their module's role only, with the privileges listed:
kernel.grant_module(table, module, ARRAY['SELECT', 'INSERT', ...]). It revokes the table fromorbit_runtime, soorbit_runtime(and a login using it directly) reaches no module table. Append-only tables get no UPDATE or DELETE (SELECT ... FOR UPDATEneeds UPDATE). The table must be in the module's own schema (named as the module), never a platform schema (kernel, events, jobs, pii, audit, authz, doors, mcp, auth, apalis, public); its sequences get USAGE. Every table in the repository uses it;kernel.grant_runtimeremains only for older down migrations. - The runtime login switches per transaction. It is a member of each module role
WITH INHERIT FALSE, SET TRUE. On everyorbit migratethe function grants that to every login that inheritsorbit_runtimeand removes the module roles from everyone else: a login taken out oforbit_runtimeloses them at the next migrate, and a module role granted outside the function (another grantor, or with INHERIT) makes migrate fail until a superuser revokes it. The bus sets the tenant, checks the gate and enablement as the login, then runsSET LOCAL ROLE "orbit_mod_<id>"; the tenant is set withSET LOCAL app.tenant_id = '<uuid>'. Subscribers and jobs do the same (orbit_kernel::module_tx). Built-inkernelcommands run as the login itself. - No
set_configfor runtime code. The superuser script revokesEXECUTEonpg_catalog.set_configfromPUBLICand grants it to the database owner only (itsSECURITY DEFINERfunctions scope transactions). A single injected statement as a module role can no longer switch tenant or role and switch back inside one statement (e.g. in a CTE), which the tripwire could not see. - Tripwire. Before commit the bus,
PgBusand the job runner check that both the tenant and the role are unchanged (orbit_kernel::still_scoped_as); a handler that ranRESET ROLEor switched to another module's role is rolled back (BusError::TenantChanged, a failed delivery or job). Released pool connections get their role reset. - The database enforces event ownership. A
BEFORE INSERTtrigger onevents.outboxrefuses an event whose catalogue module is not the module of the current role (kernel.current_module()), and onevents.processeda subscriber name other than the current module. The table owner and superusers are not checked.orbit_events::emitkeeps its own check for a clear error. - Events reaching a disabled module are held, not dropped, but only for a module the tenant enabled before (a
kernel.tenant_modulesrow withenabled = false). For a module the tenant never turned on nothing is held, so a first enable starts from that moment and never replays a history it did not subscribe to.PgBusrecords held events inevents.skipped(relay role). The relay asksevents.replay_tenants()for tenants with skipped events whose module is enabled again and, before that tenant's pending events, replays them in outbox order, reading only rows of modules enabled again (a disabled module's backlog never fills the batch). A subscriber with skipped events left gets no later event until they are replayed, so its order holds. Replays are ordinary deliveries (retries, dead letters,events.processed). - Permanent failures. A subscriber returns
orbit_events::Permanentfor an error retrying cannot fix; it is dead-lettered on the first attempt. - No redacted values in payloads.
emitandorbit_jobs::enqueuerefuse a payload with a string value exactly equal toorbit_kernel::REDACTED([redacted], what aPiivalue serialises to;orbit_kernel::has_redacted). Free text that merely mentions it passes. - Down-migration guard.
kernel.table_has_rows(table)(owner only) lifts FORCE row-level security for oneEXISTSand restores it, so a module with history can refuse a destructive down migration (call it in a statement of its own):DO $$ BEGIN IF kernel.table_has_rows('payroll.runs') THEN RAISE EXCEPTION '...'; END IF; END $$;
Consequences
- This is defence against bugs, not against malicious in-process code. The handler runs on the same login that holds every module role, so code that wants to can
RESET ROLEorSET ROLE orbit_mod_payrolland act before the tripwire runs, or switch back before commit. The roles stop accidental cross-module SQL and wrong grants; separating hostile code needs separate logins or processes per module, which is out of scope (plugins run in Extism, not on this login). orbit migratechecks first, before any migration: PostgreSQL 16 or later, thenorbit_role_admin(NOLOGIN, CREATEROLE, ADMIN onorbit_runtime), thenorbit_roles.ensure_module_roleowned by it and callable by this login. Each failure points todeploy/README.md. An existing database is upgraded by stoppingwebandworker, running02-module-roles.sqlas the superuser, thenorbit migrate.- The superuser script is one transaction, and
orbit migraterefuses whileorbit_runtimemay still executeset_config, unless the operator setsORBIT_ALLOW_SET_CONFIG=1(a managed provider that cannot revoke it; single-statement switch protection is then lost). Backups and maintenance tools (pg_dump,pg_restore,vacuumdb,reindexdb) callset_config, so they run as the superuser or the database owner. - The
set_configrevoke is per database and needs the superuser script; the tripwire and triggers still do not stop code that runs several statements (SET ROLE ...; ...; SET ROLE back). - Roles are cluster-wide: several Orbit databases on one cluster share
orbit_mod_<id>(grants stay per database). - Skipped events are held for 90 days (
orbit_events::SKIPPED_RETENTION): a running relay callsevents.prune_skipped(owner-defined, worker-callable, at least one day) hourly, in the relay rather than a scheduled job so it needs no tenant and no extra role. A module re-enabled after longer must reconcile from its own data. jobs.enqueuerefuses a job whose name's module is not the caller's module role (read from therolesetting, whichSECURITY DEFINERleaves unchanged), so a module can enqueue only its own jobs. Code running as no module role cannot enqueue at all.- Adding a runtime login to
orbit_runtimeneeds a laterorbit migrate(orbit_roles.ensure_module_roleruns for every module on every migrate). Retiring a login means revokingorbit_runtimeand runningorbit migrate(or revoking itsorbit_mod_*memberships by hand); revokingorbit_runtimealone leaves it able to switch to every module role until then.
Amendment (issue #27): kernel events, subscriber emits, memberships
- Kernel events. The built-in module emits
kernel.module.enabledfromkernel.module.enable, running as the login (no module role). The outbox trigger accepts akernel.*event only whenkernel.current_module()is NULL, so a module role still cannot emit one (events migration 0004). The kernel writes the outbox row itself (it does not depend onorbit-events) and skips it on a database without the events schema. - Subscribers emit.
EventCtx::emitwrites the subscriber's own module's events in the delivery transaction, as the module role; the trigger checks it like any emit. - Dead letters. The runtime role may read
events.failures'tenant_id,subscriber,event_id,attemptsanddead_at(column grant), neverlast_error. - Memberships.
orbit_runtime(so every module role) losesSELECTonauthz.memberships; the kernel's helpers and the policy engine read through tenant-scopedSECURITY DEFINERfunctions (authz.membership_of,person_role,count_people,people_page).authz.remove_personandrestore_personrefuse a caller whoserolesetting is a module role (current_useris the definer inside them) or another tenant. A removal stands untilkernel.member.restore: the doors refuse every token of the person meanwhile, and after a restore only one issued over a minute later.
Note (payroll setup review): column UPDATE for re-encryption only
payroll.assignment_lines is append-only, but its role holds UPDATE (amount): an orbit_pii::Reencrypt job rewrites the ciphertext under a new key version, and SELECT ... FOR UPDATE needs an UPDATE privilege. No handler updates the column; the grant exists for re-encryption alone.
Amendment (issue #31): outbox reads, dead letters, re-encryption grants
- Outbox.
orbit_runtime, and so every module role, losesSELECTonevents.outbox(events migration 0005): a module read every event of its tenant, other modules' payloads included. Emitting needs only the column-limitedINSERTit keeps (noRETURNING, noON CONFLICT). Only the relay's login (orbit_worker) reads the outbox, for delivery and replay. The platform reads listed above are therefore: tenants, enablement, audit insert, memberships (through functions), outbox insert,events.processed,jobs.enqueue,pii.tenant_keys. - Dead letters.
kernel.dead_letter.listreads event names throughevents.dead_letters(limit), a tenant-scopedSECURITY DEFINERfunction with a pinnedsearch_paththat returns no payload or error text. It refuses any caller whoserolesetting is notnone(the kernel runs as the login with no role set), so a module role that switches toorbit_runtimeis refused too.EXECUTEis revoked fromPUBLIC. - Re-encryption grants.
attendance.checkinsstays append-only, but its role holdsUPDATE (location)(attendance migration 0005) for theReencryptjob, as in the payroll note below.