Skip to content

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, through orbit_roles.ensure_module_role(module).
  • A role admin, not the owner, creates roles. The superuser's deploy/postgres/init/02-module-roles.sql creates a NOLOGIN orbit_role_admin with CREATEROLE and ADMIN OPTION on orbit_runtime (INHERIT FALSE, SET FALSE), and the SECURITY DEFINER function orbit_roles.ensure_module_role it owns (search path pinned, EXECUTE only to the database owner, and it refuses any caller that does not own schema kernel). It only creates and wires orbit_mod_<validated id>. The owner (orbit_migrator) has neither CREATEROLE nor any membership in orbit_runtime. The function lives in its own schema orbit_roles, not kernel: the superuser script runs before the owner's first migration creates kernel, and only a superuser can create a function owned by orbit_role_admin. It refuses a pre-existing orbit_mod_<id> unless orbit_role_admin holds ADMIN on it (it made it), it is a member of nothing but orbit_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_runtime is the shared group the planner called orbit_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 from orbit_runtime, so orbit_runtime (and a login using it directly) reaches no module table. Append-only tables get no UPDATE or DELETE (SELECT ... FOR UPDATE needs 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_runtime remains 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 every orbit migrate the function grants that to every login that inherits orbit_runtime and removes the module roles from everyone else: a login taken out of orbit_runtime loses 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 runs SET LOCAL ROLE "orbit_mod_<id>"; the tenant is set with SET LOCAL app.tenant_id = '<uuid>'. Subscribers and jobs do the same (orbit_kernel::module_tx). Built-in kernel commands run as the login itself.
  • No set_config for runtime code. The superuser script revokes EXECUTE on pg_catalog.set_config from PUBLIC and grants it to the database owner only (its SECURITY DEFINER functions 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, PgBus and the job runner check that both the tenant and the role are unchanged (orbit_kernel::still_scoped_as); a handler that ran RESET ROLE or 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 INSERT trigger on events.outbox refuses an event whose catalogue module is not the module of the current role (kernel.current_module()), and on events.processed a subscriber name other than the current module. The table owner and superusers are not checked. orbit_events::emit keeps 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_modules row with enabled = 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. PgBus records held events in events.skipped (relay role). The relay asks events.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::Permanent for an error retrying cannot fix; it is dead-lettered on the first attempt.
  • No redacted values in payloads. emit and orbit_jobs::enqueue refuse a payload with a string value exactly equal to orbit_kernel::REDACTED ([redacted], what a Pii value 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 one EXISTS and 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 ROLE or SET ROLE orbit_mod_payroll and 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 migrate checks first, before any migration: PostgreSQL 16 or later, then orbit_role_admin (NOLOGIN, CREATEROLE, ADMIN on orbit_runtime), then orbit_roles.ensure_module_role owned by it and callable by this login. Each failure points to deploy/README.md. An existing database is upgraded by stopping web and worker, running 02-module-roles.sql as the superuser, then orbit migrate.
  • The superuser script is one transaction, and orbit migrate refuses while orbit_runtime may still execute set_config, unless the operator sets ORBIT_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) call set_config, so they run as the superuser or the database owner.
  • The set_config revoke 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 calls events.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.enqueue refuses a job whose name's module is not the caller's module role (read from the role setting, which SECURITY DEFINER leaves 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_runtime needs a later orbit migrate (orbit_roles.ensure_module_role runs for every module on every migrate). Retiring a login means revoking orbit_runtime and running orbit migrate (or revoking its orbit_mod_* memberships by hand); revoking orbit_runtime alone 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.enabled from kernel.module.enable, running as the login (no module role). The outbox trigger accepts a kernel.* event only when kernel.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 on orbit-events) and skips it on a database without the events schema.
  • Subscribers emit. EventCtx::emit writes 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, attempts and dead_at (column grant), never last_error.
  • Memberships. orbit_runtime (so every module role) loses SELECT on authz.memberships; the kernel's helpers and the policy engine read through tenant-scoped SECURITY DEFINER functions (authz.membership_of, person_role, count_people, people_page). authz.remove_person and restore_person refuse a caller whose role setting is a module role (current_user is the definer inside them) or another tenant. A removal stands until kernel.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, loses SELECT on events.outbox (events migration 0005): a module read every event of its tenant, other modules' payloads included. Emitting needs only the column-limited INSERT it keeps (no RETURNING, no ON 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.list reads event names through events.dead_letters(limit), a tenant-scoped SECURITY DEFINER function with a pinned search_path that returns no payload or error text. It refuses any caller whose role setting is not none (the kernel runs as the login with no role set), so a module role that switches to orbit_runtime is refused too. EXECUTE is revoked from PUBLIC.
  • Re-encryption grants. attendance.checkins stays append-only, but its role holds UPDATE (location) (attendance migration 0005) for the Reencrypt job, as in the payroll note below.

Orbit by SkySync Tech. Licensed under AGPL-3.0.