Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(db): refuse restores for CREATEROLE members, server file grants and parameter grants

Maurice9808e113e402
diff --git a/server/CLAUDE.md b/server/CLAUDE.md
index a67741c0d..3e0055163 100644
--- a/server/CLAUDE.md
+++ b/server/CLAUDE.md
@@ -82,7 +82,7 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c
- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest**; it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/`: run `gen:plugin-facts` after touching them and commit the output. What a plugin gets back is `protocol/output-contract.ts`: every wire method has an entry, and an entity result (`trips.getById`, `todos.list`, `vacay.mine`, ...) is cut down to its published fields in `rpc-host.ts` on the way out, together with every child row it carries whose field is listed in `PLUGIN_ENTITY_NESTED` (a day's `notes_items`, a reservation's `endpoints`). A new column on any whole-row table behind those entities, child tables included, fails `tests/unit/plugins/output-contract.schema.test.ts` until it is listed as published or withheld (the SDK's `PLUGIN_ENTITY_FIELDS` and `PLUGIN_ENTITY_NESTED` are generated from it); a method left as `readModel` must return a value built field by field from named columns. A plugin's own SQL (`host/plugin-data.service.ts`) is held to a row cap, and `query`, `tx` and an `exec` script to a time budget checked between rows and statements (`migrate` is deliberately not timed). Where that data lives is the engine's: `PLUGIN_DATA` (`src/nest/plugins/host/plugin-data.backend.ts`) binds the SQLite file per plugin, or on Postgres a schema per plugin (`trek_plugin_<id>`, `src/db/engine/postgres/plugin-data-store.ts`) whose SQL `src/db/engine/postgres/plugin-sql-guard.ts` keeps inside that schema before it runs (its header names the three layers: the guard, which refuses what it would read differently from the Postgres lexer; one statement per round trip over the extended query protocol, which the store sends on a pool client it checks out for each call and runs its transaction on directly; and `pg_temp` last on the plugin's and on every pool connection's `search_path`, `session-search-path.ts`, with the store dropping its client's temporary tables and other session state before the client goes back to the pool); the plugin's SQL is never translated, and `db.engine` tells the plugin which dialect to write. Backups and restores carry the plugin schemas the role owns (`pg-tools.ts`). `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.
- **Storage**: `src/nest/storage/` is the upload driver abstraction (local / S3 / mirror behind one interface, with an admin surface and a usage job). Domain services never touch the filesystem or the S3 SDK directly. Where the data lives (`data/`, `uploads/`, backups, logs, key files, the DB file) is resolved in one place, `src/app-config/data-paths.ts`; a provider that reads one injects `DataPathsService`, plain helper modules shared with code outside the container call `resolveDataPaths()` (the list is in `src/app-config/README.md`), and nothing anchors a data path on its own `__dirname` or on `process.cwd()`.
- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and a restore or the demo reset swaps the file only through the database backup port, `DATABASE_BACKUP` (`nest/database/database-backup.interface.ts`; the SQLite implementation is `nest/backup/sqlite-database-backup.ts`: `VACUUM INTO` snapshot, close, atomic file swap, `reopen()`). The port works on `DatabaseLifecycle.file`, the one resolved path (`TREK_DB_FILE` or `data/travel.db`), and a snapshot that fails fails the backup rather than archiving the live file. `MaintenanceRepository` is provided only by `MaintenanceModule`'s factory and injected everywhere else; no consumer constructs it. A provider that has to follow every reopen (the demo reset job saves the first demo baseline after a restore's re-bootstrap seeded the example trips) registers with `DatabaseLifecycle.onReopened()`, which runs after the reopen's schema bootstrap; a listener contains its own failures, since one that throws fails the reopen. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot. It refuses the boot when `schema_version` is not exactly one row holding an integer ≥ 1, or is above the last mapped step (258); a value from 1 to 258 is read as dev's steps of those numbers, so a pre-ORM feature-branch database whose steps differ is not detected (the Tours branch is the one case it cuts back). Recorded `mikro_orm_migrations` names this build does not ship refuse it too (`refuseNewerDatabase`), whether a newer release or a development build wrote them. 4.3.x and earlier have no such check and start on a database 5.x migrated. Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Kysely statements (`this.kysely<...>()`) type against `DB` from `db/kysely/db.ts`, narrowed with `Pick<DB, 'trips' | 'days'>`; those files are generated from the migrated schema by `scripts/generate-db-types.ts`, so a migration that adds or changes a column is followed by `npm run gen:db-types`, never by a hand-written table interface. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
-- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; an empty one (or one TREK migrated that holds no account) is refused too while the data directory's `travel.db` holds accounts, unless `TREK_DB_IGNORE_SQLITE_FILE=true` (`sqliteLeftBehind` in the bootstrap deps), so a forgotten move never boots an empty instance; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 18.0/17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714), streams the script to its work file and stops it past `BACKUP_MAX_DECOMPRESSED_MB`, and refuses a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL` in `server-checks.ts`: a member of any superuser role, its own included, a holder of `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, and before PostgreSQL 16 a role with CREATEROLE, which may grant itself those; the archive's SQL runs as that role, and the boot warns about one). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`, else `/usr/lib/postgresql/<major>/bin` newest first) with the password in their environment, never on the command line, and their stderr reaches an error only summarized, without the lines that quote rows. Supported servers are PostgreSQL 14 to 18 (`src/db/engine/postgres/server-checks.ts`): the boot refuses any other before it writes anything. The image ships the version 18 client from the PGDG apt repository (pinned major, key kept in `scripts/pgdg-apt-key.asc`), because a client handles every server up to its own major and refuses a newer one; a dump or a restore refuses a client older than the server, and `sslrootcert=system` (the default when the URL names an `sslmode` but no CA) only with a client from 16 on. The migration history lives in the current schema beside the tables (the bootstrap qualifies MikroORM's `migrations.tableName` with `current_schema()`), so the backups, which hold that schema, include it. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle, and the legacy upgrade suites, which mock `src/db/database` onto a SQLite file the retired positional runner built and so never name the snapshot). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. An existing SQLite install moves with `npm run db:move-to-postgres` (`src/move-to-postgres.ts`, the move itself in `src/db/engine/postgres/sqlite-move/`): it refuses a file at another migration level, orphaned rows and a target holding any table or plugin schema, creates the schema with the engine's own bootstrap (no seeders), then in one transaction empties the bootstrap's rows, copies every table in foreign key order (a self-reference is set after its rows), converts each value to its Postgres column type and refuses one it cannot hold exactly (a NUL character it drops, as every write does), copies each plugin's `plugin.db` into its schema, moves the sequences past the copied ids (and past `sqlite_sequence`), and compares every table's row count and an order-free checksum over all rows before it commits; a failure drops the schema again. It never writes the SQLite file and never touches uploads. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade before scaling out.
+- **Engines** (`src/db/engine/`): `TREK_DB_URL` (a `postgres://` URL) runs TREK on Postgres instead of the SQLite file; without it nothing changes. `resolveEngine()` picks the engine, and what differs by engine (the ORM options, opening and closing, how a database reaches the schema) is the engine's, behind the `DatabaseEngine` contract that `DatabaseLifecycle` calls; code elsewhere never checks which engine it runs on (`lint:engine-dispatch`). The Postgres driver (`src/db/engine/postgres/postgres-driver.ts`) reads `bigint` as a number. A Postgres database never replays the SQLite migrations: an empty one gets `assets/postgres/baseline.sql` (generated from the entities by `gen:pg-baseline`, with the triggers ported by hand in `POSTGRES_TRIGGERS`) and every migration up to its cut recorded as executed, in one transaction (`src/db/engine/postgres/schema-bootstrap.ts`); one holding tables without TREK's migration history is refused; an empty one (or one TREK migrated that holds no account) is refused too while the data directory's `travel.db` holds accounts, unless `TREK_DB_IGNORE_SQLITE_FILE=true` (`sqliteLeftBehind` in the bootstrap deps), so a forgotten move never boots an empty instance; one TREK migrated runs the newer-database refusal and the pending migrations. The migrations after the cut run on Postgres through the migrator, each with its schema change written once per engine through `engineDdl` (SQL dialect, Migrations, has the routine), and the baseline stays frozen for them. Before pending migrations the boot takes a `pg_dump` copy to `data/pre-migrate-<last migration>-<time>.pgdump` under the same `TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP)` policy as the SQLite file. The backup port's Postgres side (`src/nest/backup/postgres-database-backup.ts`) dumps with `pg_dump`; a restore turns the dump into a script with `pg_restore` and has `psql` clear the current schema and run it in one transaction (a dump only recreates what it holds, so `pg_restore --clean` would leave a later migration's tables behind); the restore refuses a pg_restore or psql older than 18.0/17.6/16.10/15.14/14.19, whose script would lack the `\restrict` line that keeps a psql meta-command smuggled into a dump from running (CVE-2025-8714), streams the script to its work file and stops it past `BACKUP_MAX_DECOMPRESSED_MB`, and refuses a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL` in `server-checks.ts`: a member of any superuser role, its own included, a holder of `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, a role granted EXECUTE on a server file function (`lo_export`, `pg_read_file`, ...), from PostgreSQL 15 on a role granted ALTER SYSTEM or SET on a superuser-only setting, and before PostgreSQL 16 a member of a role with CREATEROLE, its own included, which may grant itself those; the archive's SQL runs as that role, and the boot warns about one). The tools run by absolute path (`src/db/engine/postgres/pg-tools.ts`, `TREK_DB_PG_BIN_DIR`, else `/usr/lib/postgresql/<major>/bin` newest first) with the password in their environment, never on the command line, and their stderr reaches an error only summarized, without the lines that quote rows. Supported servers are PostgreSQL 14 to 18 (`src/db/engine/postgres/server-checks.ts`): the boot refuses any other before it writes anything. The image ships the version 18 client from the PGDG apt repository (pinned major, key kept in `scripts/pgdg-apt-key.asc`), because a client handles every server up to its own major and refuses a newer one; a dump or a restore refuses a client older than the server, and `sslrootcert=system` (the default when the URL names an `sslmode` but no CA) only with a client from 16 on. The migration history lives in the current schema beside the tables (the bootstrap qualifies MikroORM's `migrations.tableName` with `current_schema()`), so the backups, which hold that schema, include it. A restore refuses a SQLite archive or a newer TREK's dump before anything is replaced, and replaces everything in the schema, so TREK wants a database of its own and a role that is not a superuser. `RESTORE_FROM_BACKUP` loads the archive's dump the same way into a database that holds no table yet, and is ignored once it holds one. The Postgres lane (`vitest.pg.config.ts`, `npm run test:pg`, CI job `server-postgres`, once on Postgres 14 and once on 18) runs every suite that boots the app on the real database module, each file on its own copy of one template database migrated by the engine's bootstrap (`tests/postgres/global-setup.ts`), plus `tests/postgres/` (PARITY-PG: the comparator finds nothing between the bootstrapped database and the entities but the differences it lists with their reason; the write lock; case-insensitive search). `TREK_TEST_DB_URL` names a database it may create and drop databases from; without it the lane fails, and with `TREK_TEST_PG_MAJOR` set it refuses a server of another major. Nobody keeps the list: `tests/postgres/lane.ts` takes every test file that reaches `src/bootstrap.ts` or `src/nest/app.module.ts` through its imports (directly or through a helper under `tests/`, so `buildApp()`, `bootTestApp()` and the broadcast-parity harness all count) and does not `vi.mock` `src/db/database`. Its `SQLITE_ONLY` map names the suites that stay on SQLite by design, each with its reason (the two whose faked clock needs SQLite to answer synchronously, the two about the better-sqlite3 handle, and the legacy upgrade suites, which mock `src/db/database` onto a SQLite file the retired positional runner built and so never name the snapshot). A suite that boots the app over the SQLite snapshot mock can never run on Postgres; the ones that still do are listed in `tests/postgres/snapshot-suites-baseline.json`, which only shrinks. `tests/unit/postgres-lane.test.ts` (PGLANE, in the SQLite lane) fails on a new such suite (drop the mock and seed through `tests/helpers/factories` with `app.get(MikroORM)`, as `tests/e2e/packing-mcp.e2e.test.ts` does), on a baseline entry or exclusion that went stale, and on a suite that names `buildApp`/`bootTestApp`/`AppModule` without the discovery seeing it boot. The suites that build a partial module over `createTestOrm(db)`/`createTestMikroOrmModule(db)` bind the ORM to a better-sqlite3 handle and stay on SQLite; the probe is what checks their repositories' SQL on Postgres. An existing SQLite install moves with `npm run db:move-to-postgres` (`src/move-to-postgres.ts`, the move itself in `src/db/engine/postgres/sqlite-move/`): it refuses a file at another migration level, orphaned rows and a target holding any table or plugin schema, creates the schema with the engine's own bootstrap (no seeders), then in one transaction empties the bootstrap's rows, copies every table in foreign key order (a self-reference is set after its rows), converts each value to its Postgres column type and refuses one it cannot hold exactly (a NUL character it drops, as every write does), copies each plugin's `plugin.db` into its schema, moves the sequences past the copied ids (and past `sqlite_sequence`), and compares every table's row count and an order-free checksum over all rows before it commits; a failure drops the schema again. It never writes the SQLite file and never touches uploads. Two processes starting on one Postgres database at once are not coordinated yet: the second fails its boot (the first one's schema transaction wins), so start one instance for a first boot or an upgrade before scaling out.
## Rules for new code
diff --git a/server/src/db/engine/postgres/server-checks.ts b/server/src/db/engine/postgres/server-checks.ts
index c297849c1..b084616dd 100644
--- a/server/src/db/engine/postgres/server-checks.ts
+++ b/server/src/db/engine/postgres/server-checks.ts
@@ -10,6 +10,48 @@ import { REFUSAL } from '../../legacy-baseline';
/** The PostgreSQL majors TREK supports and CI runs: the oldest and the newest. */
const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const;
+/**
+ * The `pg_catalog` functions that read, list or write files on the database
+ * server, or move a large object to or from one. PostgreSQL revokes EXECUTE on
+ * them from PUBLIC (since 11) instead of checking for a superuser, so a grant
+ * of one hands that reach to an ordinary role. The `pg_file_*` ones are
+ * adminpack's, which installs into `pg_catalog` where it exists at all. The
+ * `pg_ls_*dir` functions `pg_monitor` holds only list fixed directories and
+ * are not counted.
+ */
+const SERVER_FILE_FUNCTIONS = [
+ 'lo_import',
+ 'lo_export',
+ 'pg_read_file',
+ 'pg_read_binary_file',
+ 'pg_ls_dir',
+ 'pg_stat_file',
+ 'pg_file_write',
+ 'pg_file_rename',
+ 'pg_file_unlink',
+ 'pg_file_sync',
+];
+
+/**
+ * A privilege on a server setting that an ordinary role does not have:
+ * `ALTER SYSTEM` on any parameter (it rewrites `postgresql.auto.conf`, where
+ * `archive_command` or a preload library runs on the host), or `SET` on one
+ * that only a superuser may set (`lo_compat_privileges` turns off the large
+ * object checks). A grant to PUBLIC counts, and so does one on a parameter
+ * this server does not know yet. `pg_parameter_acl` exists from PostgreSQL 15
+ * on, and a statement naming it does not even parse on 14, so the query runs
+ * through `query_to_xml` and only on 15 or later; it answers an empty string
+ * when no row matches.
+ */
+const PARAMETER_GRANT_SQL =
+ 'select 1 from pg_catalog.pg_parameter_acl a, aclexplode(a.paracl) e' +
+ " where (e.privilege_type = 'ALTER SYSTEM'" +
+ " or coalesce((select s.context from pg_catalog.pg_settings s where s.name = a.parname), 'superuser') <> 'user')" +
+ " and case when e.grantee = 0 then true else pg_has_role(current_user, e.grantee, 'MEMBER') end limit 1";
+
+/** `text` as a SQL string literal. */
+const literal = (text: string) => `'${text.replaceAll("'", "''")}'`;
+
/**
* True when the current role could reach the database host, or make itself
* able to, from SQL. A restored archive is a SQL script run as that role, so
@@ -20,25 +62,42 @@ const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const;
* - membership in `pg_execute_server_program` (`COPY ... PROGRAM`),
* `pg_write_server_files` or `pg_read_server_files` (`COPY` to or from a
* server file), which a superuser holds implicitly;
- * - CREATEROLE before PostgreSQL 16, where it may grant itself any role that
- * is not a superuser, those predefined roles included. From 16 on it needs
- * ADMIN OPTION on a role to grant it, which the checks above already see.
+ * - EXECUTE on one of {@link SERVER_FILE_FUNCTIONS} (`lo_export` writes a
+ * server file and keeps it after its transaction rolled back);
+ * - from PostgreSQL 15 on, a privilege on a server setting an ordinary role
+ * lacks ({@link PARAMETER_GRANT_SQL});
+ * - before PostgreSQL 16, membership in a role with CREATEROLE, its own
+ * included: such a role may grant itself any role that is not a superuser,
+ * those predefined roles included, and a member may `SET ROLE` to it first,
+ * since role attributes are not inherited but the grant checks the role in
+ * effect. From 16 on it needs ADMIN OPTION on a role to grant it, which the
+ * checks above already see.
*
* `MEMBER` is membership whatever its INHERIT and SET options, since a member
- * that can neither may still be one that can grant itself the rest.
+ * that can neither may still be one that can grant itself the rest. The
+ * version-gated parts sit in CASE, whose branches PostgreSQL evaluates only
+ * when taken.
*/
export const PRIVILEGED_ROLE_SQL =
"exists (select 1 from pg_roles r where r.rolsuper and pg_has_role(current_user, r.oid, 'MEMBER'))" +
" or pg_has_role(current_user, 'pg_execute_server_program', 'MEMBER')" +
" or pg_has_role(current_user, 'pg_write_server_files', 'MEMBER')" +
" or pg_has_role(current_user, 'pg_read_server_files', 'MEMBER')" +
- " or (current_setting('server_version_num')::int < 160000" +
- ' and coalesce((select r.rolcreaterole from pg_roles r where r.rolname = current_user), false))';
+ " or exists (select 1 from pg_proc p where p.pronamespace = 'pg_catalog'::regnamespace" +
+ ` and p.proname in (${SERVER_FILE_FUNCTIONS.map(literal).join(', ')})` +
+ " and has_function_privilege(current_user, p.oid, 'EXECUTE'))" +
+ " or (case when current_setting('server_version_num')::int >= 150000" +
+ ` then query_to_xml(${literal(PARAMETER_GRANT_SQL)}, false, true, '')::text <> '' else false end)` +
+ " or (case when current_setting('server_version_num')::int < 160000" +
+ " then exists (select 1 from pg_roles r where r.rolcreaterole and pg_has_role(current_user, r.oid, 'MEMBER'))" +
+ ' else false end)';
/** What {@link PRIVILEGED_ROLE_SQL} refuses, as the boot warning and the restore refusal say it. */
export const PRIVILEGED_ROLE_DESCRIPTION =
'a superuser or a member of a superuser role, a role that may run programs or read or write files on the ' +
- 'database server, or (before PostgreSQL 16) a role with CREATEROLE, which may grant itself those';
+ 'database server (through a predefined role or a granted server file function such as lo_export), a role ' +
+ 'granted ALTER SYSTEM or a superuser-only setting (PostgreSQL 15 and later), or (before PostgreSQL 16) a ' +
+ 'member of a role with CREATEROLE, which may grant itself those';
/** The major version in `server_version_num` (`170011` is 17, `180001` is 18). Throws on anything else. */
export function serverMajor(versionNum: string | number | undefined): number {
diff --git a/server/tests/postgres/server-checks.test.ts b/server/tests/postgres/server-checks.test.ts
index 5dba79ed2..e03fdb5e6 100644
--- a/server/tests/postgres/server-checks.test.ts
+++ b/server/tests/postgres/server-checks.test.ts
@@ -1,5 +1,5 @@
/**
- * PGROLE-001..003 — the check that refuses a restore (and warns at boot) for a
+ * PGROLE-001..006 — the check that refuses a restore (and warns at boot) for a
* role that could reach the database host from SQL
* (src/db/engine/postgres/server-checks.ts), evaluated by the real server as
* each kind of role. Roles belong to the whole server, so this suite creates
@@ -15,7 +15,18 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
const adminUrl = process.env.TREK_TEST_DB_URL as string;
const PREFIX = `trek_test_role_${process.pid}_`;
const role = (name: string) => `${PREFIX}${name}`;
-const ROLES = ['plain', 'super', 'member', 'program', 'reader', 'writer', 'creator', 'granter'];
+
+/**
+ * Drops every role this suite created, whatever it was granted. DROP OWNED
+ * revokes what a role holds in this database and on shared objects, its
+ * function and parameter grants included, which DROP ROLE alone refuses to
+ * leave behind.
+ */
+const DROP_ROLES =
+ 'do $drop$ declare name text; begin' +
+ ` for name in select rolname from pg_roles where left(rolname, ${PREFIX.length}) = '${PREFIX}' loop` +
+ " execute format('drop owned by %I', name); execute format('drop role %I', name);" +
+ ' end loop; end $drop$';
/** The statements run as the admin, one after the other on its one connection. */
function asAdmin(statements: string[]): Promise<unknown[]> {
@@ -38,7 +49,7 @@ async function privileged(name: string): Promise<boolean> {
let major = 0;
beforeAll(async () => {
- await asAdmin(ROLES.map((name) => `drop role if exists ${role(name)}`));
+ await asAdmin([DROP_ROLES]);
await asAdmin([
`create role ${role('plain')} nologin`,
`create role ${role('super')} nologin superuser`,
@@ -52,15 +63,44 @@ beforeAll(async () => {
`grant pg_write_server_files to ${role('writer')}`,
`create role ${role('creator')} nologin createrole`,
`create role ${role('granter')} nologin createrole`,
+ // A login role that holds no CREATEROLE itself but belongs to a group that does.
+ `create role ${role('admins')} nologin createrole`,
+ `create role ${role('in_admins')} nologin in role ${role('admins')}`,
+ // Server file functions, granted one by one as a DBA would for a maintenance tool.
+ `create role ${role('lo_export')} nologin`,
+ `grant execute on function lo_export(oid, text) to ${role('lo_export')}`,
+ `create role ${role('lo_import')} nologin`,
+ `grant execute on function lo_import(text) to ${role('lo_import')}`,
+ `create role ${role('read_file')} nologin`,
+ `grant execute on function pg_read_file(text) to ${role('read_file')}`,
+ `create role ${role('ls_dir')} nologin`,
+ `grant execute on function pg_ls_dir(text) to ${role('ls_dir')}`,
+ // pg_monitor lists fixed directories only, and stays an ordinary role.
+ `create role ${role('monitor')} nologin`,
+ `grant pg_monitor to ${role('monitor')}`,
+ `create role ${role('set_suset')} nologin`,
+ `create role ${role('alter_system')} nologin`,
+ `create role ${role('set_userset')} nologin`,
+ `create role ${role('setters')} nologin`,
+ `create role ${role('in_setters')} nologin in role ${role('setters')}`,
]);
const [rows] = (await asAdmin(["select current_setting('server_version_num')::int / 10000 as major"])) as Array<
Array<{ major: number }>
>;
major = rows[0].major;
+ // Privileges on parameters exist from PostgreSQL 15 on; the statements do not parse before.
+ if (major >= 15) {
+ await asAdmin([
+ `grant set on parameter lo_compat_privileges to ${role('set_suset')}`,
+ `grant alter system on parameter archive_command to ${role('alter_system')}`,
+ `grant set on parameter work_mem to ${role('set_userset')}`,
+ `grant set on parameter log_statement to ${role('setters')}`,
+ ]);
+ }
});
afterAll(async () => {
- await asAdmin(ROLES.map((name) => `drop role if exists ${role(name)}`));
+ await asAdmin([DROP_ROLES]);
});
describe('the privileged-role check', () => {
@@ -106,4 +146,50 @@ describe('the privileged-role check', () => {
if (major < 16) await expect(grant).resolves.toBeUndefined();
else await expect(grant).rejects.toThrow(/permission denied|must have admin option/);
});
+
+ it('PGROLE-004: refuses before PostgreSQL 16 a role that is only a member of a CREATEROLE role, and not from 16 on', async () => {
+ const [states] = (await asAdmin([
+ `select rolcreaterole from pg_roles where rolname = '${role('in_admins')}'`,
+ ])) as Array<Array<{ rolcreaterole: boolean }>>;
+ expect(states[0].rolcreaterole).toBe(false);
+ expect(await privileged('in_admins')).toBe(major < 16);
+ // The reason: the member sets its role to the group and grants itself what reaches the host.
+ const grant = withAdmin(adminUrl, async (run) => {
+ await run(`set role ${role('in_admins')}`);
+ try {
+ await run(`set role ${role('admins')}`);
+ await run(`grant pg_execute_server_program to ${role('in_admins')}`);
+ } finally {
+ await run('reset role');
+ }
+ });
+ if (major < 16) await expect(grant).resolves.toBeUndefined();
+ else await expect(grant).rejects.toThrow(/permission denied|must have admin option/);
+ });
+
+ it('PGROLE-005: refuses a role granted a server file function, and passes pg_monitor', async () => {
+ expect(await privileged('lo_export')).toBe(true);
+ expect(await privileged('lo_import')).toBe(true);
+ expect(await privileged('read_file')).toBe(true);
+ expect(await privileged('ls_dir')).toBe(true);
+ expect(await privileged('monitor')).toBe(false);
+ // The reason, as this server answers it: the grant alone lets the role read the host's file system.
+ const listed = await withAdmin(adminUrl, async (run) => {
+ await run(`set role ${role('ls_dir')}`);
+ try {
+ return await run<{ name: string }>("select pg_ls_dir('.') as name");
+ } finally {
+ await run('reset role');
+ }
+ });
+ expect(listed.map((row) => row.name)).toContain('PG_VERSION');
+ });
+
+ it('PGROLE-006: refuses from PostgreSQL 15 on a role granted ALTER SYSTEM or a superuser-only setting, directly or through a group', async () => {
+ expect(await privileged('set_suset')).toBe(major >= 15);
+ expect(await privileged('alter_system')).toBe(major >= 15);
+ expect(await privileged('in_setters')).toBe(major >= 15);
+ // SET on a setting every role may set anyway gives nothing.
+ expect(await privileged('set_userset')).toBe(false);
+ });
});
diff --git a/wiki/Database-Postgres.md b/wiki/Database-Postgres.md
index 551b48e4f..4f4b4c919 100644
--- a/wiki/Database-Postgres.md
+++ b/wiki/Database-Postgres.md
@@ -14,7 +14,7 @@ Postgres does not make TREK scale out. TREK still runs as one process. See [Limi
- **PostgreSQL 14 to 18.** TREK refuses to start on any other server version, before it writes anything.
- **An empty database dedicated to TREK.** TREK creates its schema in an empty database. It refuses a database that holds tables it did not create, and a restore replaces everything in the schema it loads into. Do not share the database with another application.
-- **A role that is not a superuser,** which owns the database or can create objects in its schema. A backup archive is a SQL script run by this role during a restore, so a role with fewer privileges limits what a crafted archive can do. A restore refuses a role that could reach the database server from SQL (a superuser, a member of a superuser role, a role that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, and on PostgreSQL 14 and 15 a role with CREATEROLE), and TREK warns about such a role when it starts. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
+- **A role that is not a superuser,** which owns the database or can create objects in its schema. A backup archive is a SQL script run by this role during a restore, so a role with fewer privileges limits what a crafted archive can do. A restore refuses a role that could reach the database server from SQL (a superuser, a member of a superuser role, a role that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files` or may run a server file function such as `lo_export` or `pg_read_file`, from PostgreSQL 15 on a role granted ALTER SYSTEM or a superuser-only setting, and on PostgreSQL 14 and 15 a role with CREATEROLE or a member of one), and TREK warns about such a role when it starts. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
- **ICU support in the server.** The schema creates the collation `nocase` with `provider = icu`, so the server must be built with ICU. The official `postgres` images include it.
- **PostgreSQL client tools** (`pg_dump`, `pg_restore`, `psql`) for backups, restores and the copy TREK takes before a migration. The Docker image installs the version 18 client, which works with every supported server. A client works with servers up to its own major version, so a client outside the image must be at least as new as the server; TREK refuses an older one with a message that names both versions. See [Configuration](#configuration).
- **Client tool versions that carry the CVE-2025-8714 fix.** A restore refuses `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19.
@@ -78,7 +78,7 @@ CREATE DATABASE trek OWNER trek;
ALTER SCHEMA public OWNER TO trek;
```
-Then use `postgres://trek:<password>@<host>:5432/trek` as `TREK_DB_URL`. A restore refuses a role that is a superuser or a member of one (`SET ROLE` would make it a superuser), that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, or, on PostgreSQL 14 and 15, that has CREATEROLE (there it may grant itself those roles). A crafted archive could use any of these to run commands on the database server or to read or write its files. TREK also logs a warning about such a role when it starts.
+Then use `postgres://trek:<password>@<host>:5432/trek` as `TREK_DB_URL`. A restore refuses a role that is a superuser or a member of one (`SET ROLE` would make it a superuser), that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, that may run a server file function (`lo_import`, `lo_export`, `pg_read_file`, `pg_read_binary_file`, `pg_ls_dir`, `pg_stat_file` or adminpack's `pg_file_*`), that was granted ALTER SYSTEM on any setting or SET on a superuser-only one (PostgreSQL 15 and later), or, on PostgreSQL 14 and 15, that has CREATEROLE or is a member of a role that has it (there it may grant itself those roles). A crafted archive could use any of these to run commands on the database server or to read or write its files. A member of `pg_monitor` is not refused. TREK also logs a warning about such a role when it starts.
TREK creates its tables in the role's current schema, normally `public`. A role whose `search_path` points at a schema of its own works too: TREK keeps its tables and its migration history there, and backups and restores cover that schema.
@@ -177,7 +177,7 @@ Restoring a backup on Postgres follows these rules:
- **Plugin data is replaced with the archive's.** The same transaction drops every `trek_plugin_*` schema the role owns and loads the ones the dump holds, so a plugin installed after the backup loses its data, as it does on SQLite. Schemas the role does not own, and every other schema of the database, are never touched.
- **TREK checks the archive before it replaces anything.** The archive must hold a Postgres dump, not a SQLite file. The dump must carry TREK's migration history, and it must not come from a newer TREK. TREK refuses the restore with a message saying which check failed.
- **The client tools must be recent enough.** The restore refuses `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19, and tools older than the server.
-- **The role must not be a superuser.** The restore refuses a role that is a superuser or a member of one, holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, or has CREATEROLE on PostgreSQL 14 or 15. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
+- **The role must not be a superuser.** The restore refuses a role that is a superuser or a member of one, holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, may run a server file function, was granted ALTER SYSTEM or a superuser-only setting, or on PostgreSQL 14 or 15 has CREATEROLE or is a member of a role that has it. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
- **The restore needs free space in the data directory.** `pg_restore` writes the dump out as a SQL script next to the unpacked archive before `psql` runs it, and the script is several times larger than the dump. It may grow to `BACKUP_MAX_DECOMPRESSED_MB` (5 GB by default); a larger one is stopped, nothing is replaced, and the work files are removed. Raise the limit for a genuine backup that needs more.
`RESTORE_FROM_BACKUP` works on Postgres too. On the first start, TREK loads the archive's dump into the database when that database holds no tables. An empty migration history with no other table beside it counts as no tables. When the database already has tables, the variable is ignored and TREK logs a warning. See [Backups: Restoring on a new install, before setup](Backups#restoring-on-a-new-install-before-setup).