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.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(db): refuse the column notation without parentheses and aclitem in plugin SQL
Maurice636fc7d0a650
diff --git a/plugin-sdk/README.md b/plugin-sdk/README.mdindex 633a32f6c..e7c7ce130 100644--- a/plugin-sdk/README.md+++ b/plugin-sdk/README.md@@ -219,18 +219,21 @@ What changes on Postgres:aggregates and window functions (`count`, `sum`, `string_agg`, `row_number`, `lag`, ...),UUIDs (`gen_random_uuid`), ranges, geometry, network addresses and full text search(`to_tsvector`, `ts_rank`, ...). Any other function of Postgres's catalog is refused- however you spell the call (`f(...)`, `"f"(...)`, the column notation `(x).f`): the ones- that read the catalogs or the server rather than their arguments (`obj_description`,- `col_description`, `format_type`, `version`, `current_database`, `inet_server_addr`,- `txid_current`, ...), and so is every new function a later Postgres adds until TREK has+ however you spell the call (`f(...)`, `"f"(...)`, the column notation `(x).f`, `t.f`,+ `$1.f`): the ones that read the catalogs or the server rather than their arguments+ (`obj_description`, `col_description`, `format_type`, `version`, `current_database`,+ `inet_server_addr`, `txid_current`, ...), and so is every new function a later Postgres adds until TREK hasdecided about it. The keywords `current_user`, `session_user`, `current_role`, `user`,`system_user`, `current_catalog` and `current_schema` are refused too. `coalesce`,`nullif`, `greatest`, `least`, `CASE` and `CAST` are syntax and always work. The complete- list is `PLUGIN_FUNCTIONS` in TREK's- [`plugin-sql-functions.ts`](https://github.com/liketrek/TREK/blob/main/server/src/db/engine/postgres/plugin-sql-functions.ts).+ list is TREK's+ [`plugin-functions.txt`](https://github.com/liketrek/TREK/blob/main/server/assets/postgres/plugin-functions.txt).A table or type of yours may still share a refused function's name where it cannot be acall (`INSERT INTO version (...)`, `CREATE TABLE version (...)`, `REFERENCES version (id)`);- as the table of `CREATE INDEX ... ON` it cannot, so name it differently.+ as the table of `CREATE INDEX ... ON` it cannot, so name it differently. Postgres reads+ `t.f` as the call `f(t)` when `t` has no column `f`, so a column named like a refused+ function cannot follow a table's name and a dot either (`name`, `version`, `money`, `oid`,+ `xid` and `xml` can); write it without the table's name, or name it differently.- **You change your own objects only.** Right before an `ALTER`, `DROP`, `REFRESH`,`TRUNCATE` or `CREATE INDEX ... ON` runs, Postgres resolves the object it names (and thetables a `CREATE`/`ALTER TABLE` ties to with `REFERENCES`, `INHERITS`, `PARTITION OF`,diff --git a/server/CLAUDE.md b/server/CLAUDE.mdindex 13f6fb156..72b483652 100644--- a/server/CLAUDE.md+++ b/server/CLAUDE.md@@ -79,7 +79,7 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c- **Realtime**: `/ws` is a Nest gateway in `src/nest/realtime/`. Inject `RealtimeService`; tests hand in a `FakeRealtimeService` (`tests/helpers/fake-realtime.ts`) or spy on the container's instance instead of mocking the transport module. Trip mutations forward `X-Socket-Id` so the originating client doesn't echo its own change.- **MCP**: `src/nest-mcp/` is the decorator/registry layer (`@McpController`/`@Tool`/`@Resource`/`@Prompt`; see its `README.md`); tools live in `<domain>.mcp.ts` files beside each module; the HTTP transport is `src/nest/mcp-transport/`; `src/mcp/` holds process-wide state only (scopes, session manager, boot policy). Every tool invocation writes an audit row through the registry's `onInvoke` seam. The demo-mode write block is the registry's `toolGate` (`trekDemoToolGate`): every tool not annotated read-only refuses a demo account there (except the write tools in `DEMO_UNGATED_WRITE_TOOLS`, which never had a demo check), so a tool never checks demo mode itself (ESLint refuses it in `*.mcp.ts`). MCP tools are adapters over the same services and permission checks as REST — a change on one side lands on the other in the same change.- **Scheduling**: `src/nest/scheduling/` (`CronRegistrarService`) is the one way to schedule a cron. Jobs are `*.job.ts` providers in their owning domain. The registrar refuses to schedule under `NODE_ENV=test` (an integration test pins it). **Never use a `@Cron` decorator**: it bypasses that gate. Every tick first takes the job's row in `scheduler_leases` (`SchedulerLeasesRepository.acquire`, one conditional upsert that decides the race), renews it while it runs and keeps it for a short settle window afterwards, so two processes on one database never run the same tick; a job needs nothing of its own for this. Claims on individual rows (the reminder jobs' `claimReminder`) stay where they are: the lease decides who runs a tick, the claim what a tick may send.-- **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 is kept inside that schema in layers that `src/db/engine/postgres/plugin-sql-guard.ts`'s header names, the ones after the guard enforced by the database: no plugin SQL at all while TREK's role is privileged in the sense of `PRIVILEGED_ROLE_SQL` (`src/db/engine/postgres/plugin-data-checks.ts`, read once per pool connection, and the boot log says why); the guard, which refuses what it would read differently from the Postgres lexer, other schemas, the catalogs, temporary objects, `SELECT ... INTO`, the `reg*` types, the functions that look an object up by name, and every function of `pg_catalog` outside the allowlist in `src/db/engine/postgres/plugin-sql-functions.ts` (its catalog list, `assets/postgres/catalog-functions.txt`, is held to `pg_proc` by PGPLUG-021); the objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX changes, resolved by Postgres (`to_regclass`/`to_regtype`) right before the statement and refused outside the plugin's schema, so an unqualified `int4` is `pg_catalog`'s and refused even on a superuser connection; 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; `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; and a quota over every relation of the schema with its TOAST table plus a cap on its catalog objects (`PLUGIN_SCHEMA_MAX_OBJECTS`). A plugin argument holding NUL is refused there, since Postgres text cannot hold it, while the plugin's SQLite file binds it exactly; 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.+- **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 is kept inside that schema in layers that `src/db/engine/postgres/plugin-sql-guard.ts`'s header names, the ones after the guard enforced by the database: no plugin SQL at all while TREK's role is privileged in the sense of `PRIVILEGED_ROLE_SQL` (`src/db/engine/postgres/plugin-data-checks.ts`, read once per pool connection, and the boot log says why); the guard, which refuses what it would read differently from the Postgres lexer, other schemas, the catalogs, temporary objects, `SELECT ... INTO`, the `reg*` types, the functions that look an object up by name, and every function of `pg_catalog` outside the allowlist `assets/postgres/plugin-functions.txt`, read by `src/db/engine/postgres/plugin-sql-functions.ts` (its catalog list, `assets/postgres/catalog-functions.txt`, is held to `pg_proc` by PGPLUG-021); the objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX changes, resolved by Postgres (`to_regclass`/`to_regtype`) right before the statement and refused outside the plugin's schema, so an unqualified `int4` is `pg_catalog`'s and refused even on a superuser connection; 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; `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; and a quota over every relation of the schema with its TOAST table plus a cap on its catalog objects (`PLUGIN_SCHEMA_MAX_OBJECTS`). A plugin argument holding NUL is refused there, since Postgres text cannot hold it, while the plugin's SQLite file binds it exactly; 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`, 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, each in three slices) 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 in TREK's own text too, unless `--drop-nul` lets it drop each one and list it in the summary), copies each plugin's `plugin.db` into its schema after checking, before anything is written, that every plugin value comes back from the Postgres store with its type and bytes, 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, built from the SQLite values rather than the converted ones, 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.diff --git a/server/assets/postgres/plugin-functions.txt b/server/assets/postgres/plugin-functions.txtnew file mode 100644index 000000000..3eb3ab44d--- /dev/null+++ b/server/assets/postgres/plugin-functions.txt@@ -0,0 +1,424 @@+# The functions of Postgres's pg_catalog a plugin's own SQL may call, one name per line,+# grouped. Read by src/db/engine/postgres/plugin-sql-functions.ts; every name must be in+# catalog-functions.txt (a unit test checks). A line starting with # is a comment.++# Strings and bytes.+ascii+bit_count+bit_length+btrim+casefold+char_length+character_length+chr+concat+concat_ws+convert+convert_from+convert_to+crc32+crc32c+decode+encode+format+get_bit+get_byte+initcap+is_normalized+left+length+like+lower+lpad+ltrim+md5+normalize+octet_length+overlay+position+quote_ident+quote_literal+quote_nullable+regexp_count+regexp_instr+regexp_like+regexp_match+regexp_matches+regexp_replace+regexp_split_to_array+regexp_split_to_table+regexp_substr+repeat+replace+reverse+right+rpad+rtrim+set_bit+set_byte+sha224+sha256+sha384+sha512+split_part+starts_with+string_to_array+string_to_table+strpos+substr+substring+to_ascii+to_bin+to_hex+to_oct+translate+unistr+upper++# Numbers.+abs+acos+acosd+acosh+asin+asind+asinh+atan+atan2+atan2d+atand+atanh+cbrt+ceil+ceiling+cos+cosd+cosh+cot+cotd+degrees+div+erf+erfc+exp+factorial+floor+gamma+gcd+lcm+lgamma+ln+log+log10+min_scale+mod+pi+pow+power+radians+random+random_normal+round+scale+sign+sin+sind+sinh+sqrt+tan+tand+tanh+trim_scale+trunc+width_bucket++# Dates and times.+age+clock_timestamp+date_add+date_bin+date_part+date_subtract+date_trunc+extract+isfinite+justify_days+justify_hours+justify_interval+make_date+make_interval+make_time+make_timestamp+make_timestamptz+now+overlaps+statement_timestamp+timeofday+timezone+to_char+to_date+to_number+to_timestamp+transaction_timestamp++# Conversions, also the type names written with a modifier (`varchar(20)`, `numeric(10, 2)`).+bit+bool+bpchar+bytea+char+date+float4+float8+int2+int4+int8+interval+numeric+text+time+timestamp+timestamptz+timetz+varbit+varchar++# JSON.+array_to_json+json_agg+json_agg_strict+json_array_elements+json_array_elements_text+json_array_length+json_build_array+json_build_object+json_each+json_each_text+json_extract_path+json_extract_path_text+json_object+json_object_agg+json_object_agg_strict+json_object_agg_unique+json_object_agg_unique_strict+json_object_keys+json_populate_record+json_populate_recordset+json_strip_nulls+json_to_record+json_to_recordset+json_typeof+jsonb_agg+jsonb_agg_strict+jsonb_array_elements+jsonb_array_elements_text+jsonb_array_length+jsonb_build_array+jsonb_build_object+jsonb_each+jsonb_each_text+jsonb_extract_path+jsonb_extract_path_text+jsonb_insert+jsonb_object+jsonb_object_agg+jsonb_object_agg_strict+jsonb_object_agg_unique+jsonb_object_agg_unique_strict+jsonb_object_keys+jsonb_path_exists+jsonb_path_exists_tz+jsonb_path_match+jsonb_path_match_tz+jsonb_path_query+jsonb_path_query_array+jsonb_path_query_array_tz+jsonb_path_query_first+jsonb_path_query_first_tz+jsonb_path_query_tz+jsonb_populate_record+jsonb_populate_record_valid+jsonb_populate_recordset+jsonb_pretty+jsonb_set+jsonb_set_lax+jsonb_strip_nulls+jsonb_to_record+jsonb_to_recordset+jsonb_typeof+row_to_json+to_json+to_jsonb++# Arrays and sets.+array_append+array_cat+array_dims+array_fill+array_length+array_lower+array_ndims+array_position+array_positions+array_prepend+array_remove+array_replace+array_reverse+array_sample+array_shuffle+array_sort+array_to_string+array_upper+cardinality+generate_series+generate_subscripts+trim_array+unnest+num_nonnulls+num_nulls++# Aggregates.+any_value+array_agg+avg+bit_and+bit_or+bit_xor+bool_and+bool_or+corr+count+covar_pop+covar_samp+every+max+min+mode+percentile_cont+percentile_disc+range_agg+range_intersect_agg+regr_avgx+regr_avgy+regr_count+regr_intercept+regr_r2+regr_slope+regr_sxx+regr_sxy+regr_syy+stddev+stddev_pop+stddev_samp+string_agg+sum+var_pop+var_samp+variance++# Window functions.+cume_dist+dense_rank+first_value+lag+last_value+lead+nth_value+ntile+percent_rank+rank+row_number++# UUIDs.+gen_random_uuid+uuid_extract_timestamp+uuid_extract_version+uuidv4+uuidv7++# Ranges and the plugin's own enum types.+datemultirange+daterange+enum_first+enum_last+enum_range+int4multirange+int4range+int8multirange+int8range+isempty+lower_inc+lower_inf+multirange+nummultirange+numrange+range_merge+tsmultirange+tsrange+tstzmultirange+tstzrange+upper_inc+upper_inf++# Geometry.+area+bound_box+box+center+circle+diagonal+diameter+height+isclosed+isopen+line+lseg+npoints+path+pclose+point+polygon+popen+radius+slope+width++# Network addresses.+abbrev+broadcast+cidr+family+host+hostmask+inet_merge+inet_same_family+macaddr+macaddr8+masklen+netmask+network+set_masklen++# Full text search. ts_stat and ts_rewrite run SQL handed to them as text and stay refused.+array_to_tsvector+json_to_tsvector+jsonb_to_tsvector+numnode+phraseto_tsquery+plainto_tsquery+querytree+setweight+strip+to_tsquery+to_tsvector+ts_delete+ts_filter+ts_headline+ts_rank+ts_rank_cd+tsvector_to_array+websearch_to_tsquery++# The TABLESAMPLE methods (`TABLESAMPLE SYSTEM (10)`).+bernoulli+systemdiff --git a/server/src/db/engine/postgres/plugin-sql-functions.ts b/server/src/db/engine/postgres/plugin-sql-functions.tsindex 068cd8e54..bbb5b934d 100644--- a/server/src/db/engine/postgres/plugin-sql-functions.ts+++ b/server/src/db/engine/postgres/plugin-sql-functions.ts@@ -16,14 +16,16 @@ import path from 'node:path';* activity. Listing those one by one would miss the next one Postgres adds.** So the rule is an allowlist: a call to a function of `pg_catalog` is- * refused unless its name is in {@link PLUGIN_FUNCTIONS}, the string, math,+ * refused unless its name is in {@link PLUGIN_FUNCTIONS_FILE}, the string, math,* date and time, JSON, array, range, aggregate, window, UUID and text search* functions a data plugin plausibly needs, each of which works only on its* arguments. A name counts as called when `(` follows it (`version()`,- * `"version" ()`) or when it follows `).`, Postgres's column notation for a- * call (`(16386::oid).obj_description`). A plugin's own table or type may- * still carry such a name where it cannot be a call: after INTO, TABLE, VIEW,- * REFERENCES or IF NOT EXISTS (`INSERT INTO version (...)`).+ * `"version" ()`) or when it follows a dot, Postgres's column notation for+ * a call (`(16386::oid).obj_description`, `u.obj_description` over `FROM+ * unnest(...) u`, `$1.obj_description`), unless it is one of+ * {@link COLUMN_NAMES}. A plugin's own table or type may still carry such a+ * name where it cannot be a call: after INTO, TABLE, VIEW, REFERENCES or IF+ * NOT EXISTS (`INSERT INTO version (...)`).** Which names are functions of `pg_catalog` is read from* `assets/postgres/catalog-functions.txt`: every function name of every@@ -38,417 +40,6 @@ import path from 'node:path';* name starting with `pg_` is refused anywhere by the guard itself.*/-/** The functions of `pg_catalog` a plugin may call. Each must exist in the catalog list (a unit test checks). */-export const PLUGIN_FUNCTIONS: ReadonlySet<string> = new Set([- // Strings and bytes.- 'ascii',- 'bit_count',- 'bit_length',- 'btrim',- 'casefold',- 'char_length',- 'character_length',- 'chr',- 'concat',- 'concat_ws',- 'convert',- 'convert_from',- 'convert_to',- 'crc32',- 'crc32c',- 'decode',- 'encode',- 'format',- 'get_bit',- 'get_byte',- 'initcap',- 'is_normalized',- 'left',- 'length',- 'like',- 'lower',- 'lpad',- 'ltrim',- 'md5',- 'normalize',- 'octet_length',- 'overlay',- 'position',- 'quote_ident',- 'quote_literal',- 'quote_nullable',- 'regexp_count',- 'regexp_instr',- 'regexp_like',- 'regexp_match',- 'regexp_matches',- 'regexp_replace',- 'regexp_split_to_array',- 'regexp_split_to_table',- 'regexp_substr',- 'repeat',- 'replace',- 'reverse',- 'right',- 'rpad',- 'rtrim',- 'set_bit',- 'set_byte',- 'sha224',- 'sha256',- 'sha384',- 'sha512',- 'split_part',- 'starts_with',- 'string_to_array',- 'string_to_table',- 'strpos',- 'substr',- 'substring',- 'to_ascii',- 'to_bin',- 'to_hex',- 'to_oct',- 'translate',- 'unistr',- 'upper',- // Numbers.- 'abs',- 'acos',- 'acosd',- 'acosh',- 'asin',- 'asind',- 'asinh',- 'atan',- 'atan2',- 'atan2d',- 'atand',- 'atanh',- 'cbrt',- 'ceil',- 'ceiling',- 'cos',- 'cosd',- 'cosh',- 'cot',- 'cotd',- 'degrees',- 'div',- 'erf',- 'erfc',- 'exp',- 'factorial',- 'floor',- 'gamma',- 'gcd',- 'lcm',- 'lgamma',- 'ln',- 'log',- 'log10',- 'min_scale',- 'mod',- 'pi',- 'pow',- 'power',- 'radians',- 'random',- 'random_normal',- 'round',- 'scale',- 'sign',- 'sin',- 'sind',- 'sinh',- 'sqrt',- 'tan',- 'tand',- 'tanh',- 'trim_scale',- 'trunc',- 'width_bucket',- // Dates and times.- 'age',- 'clock_timestamp',- 'date_add',- 'date_bin',- 'date_part',- 'date_subtract',- 'date_trunc',- 'extract',- 'isfinite',- 'justify_days',- 'justify_hours',- 'justify_interval',- 'make_date',- 'make_interval',- 'make_time',- 'make_timestamp',- 'make_timestamptz',- 'now',- 'overlaps',- 'statement_timestamp',- 'timeofday',- 'timezone',- 'to_char',- 'to_date',- 'to_number',- 'to_timestamp',- 'transaction_timestamp',- // Conversions, also the type names written with a modifier (`varchar(20)`, `numeric(10, 2)`).- 'bit',- 'bool',- 'bpchar',- 'bytea',- 'char',- 'date',- 'float4',- 'float8',- 'int2',- 'int4',- 'int8',- 'interval',- 'numeric',- 'text',- 'time',- 'timestamp',- 'timestamptz',- 'timetz',- 'varbit',- 'varchar',- // JSON.- 'array_to_json',- 'json_agg',- 'json_agg_strict',- 'json_array_elements',- 'json_array_elements_text',- 'json_array_length',- 'json_build_array',- 'json_build_object',- 'json_each',- 'json_each_text',- 'json_extract_path',- 'json_extract_path_text',- 'json_object',- 'json_object_agg',- 'json_object_agg_strict',- 'json_object_agg_unique',- 'json_object_agg_unique_strict',- 'json_object_keys',- 'json_populate_record',- 'json_populate_recordset',- 'json_strip_nulls',- 'json_to_record',- 'json_to_recordset',- 'json_typeof',- 'jsonb_agg',- 'jsonb_agg_strict',- 'jsonb_array_elements',- 'jsonb_array_elements_text',- 'jsonb_array_length',- 'jsonb_build_array',- 'jsonb_build_object',- 'jsonb_each',- 'jsonb_each_text',- 'jsonb_extract_path',- 'jsonb_extract_path_text',- 'jsonb_insert',- 'jsonb_object',- 'jsonb_object_agg',- 'jsonb_object_agg_strict',- 'jsonb_object_agg_unique',- 'jsonb_object_agg_unique_strict',- 'jsonb_object_keys',- 'jsonb_path_exists',- 'jsonb_path_exists_tz',- 'jsonb_path_match',- 'jsonb_path_match_tz',- 'jsonb_path_query',- 'jsonb_path_query_array',- 'jsonb_path_query_array_tz',- 'jsonb_path_query_first',- 'jsonb_path_query_first_tz',- 'jsonb_path_query_tz',- 'jsonb_populate_record',- 'jsonb_populate_record_valid',- 'jsonb_populate_recordset',- 'jsonb_pretty',- 'jsonb_set',- 'jsonb_set_lax',- 'jsonb_strip_nulls',- 'jsonb_to_record',- 'jsonb_to_recordset',- 'jsonb_typeof',- 'row_to_json',- 'to_json',- 'to_jsonb',- // Arrays and sets.- 'array_append',- 'array_cat',- 'array_dims',- 'array_fill',- 'array_length',- 'array_lower',- 'array_ndims',- 'array_position',- 'array_positions',- 'array_prepend',- 'array_remove',- 'array_replace',- 'array_reverse',- 'array_sample',- 'array_shuffle',- 'array_sort',- 'array_to_string',- 'array_upper',- 'cardinality',- 'generate_series',- 'generate_subscripts',- 'trim_array',- 'unnest',- 'num_nonnulls',- 'num_nulls',- // Aggregates.- 'any_value',- 'array_agg',- 'avg',- 'bit_and',- 'bit_or',- 'bit_xor',- 'bool_and',- 'bool_or',- 'corr',- 'count',- 'covar_pop',- 'covar_samp',- 'every',- 'max',- 'min',- 'mode',- 'percentile_cont',- 'percentile_disc',- 'range_agg',- 'range_intersect_agg',- 'regr_avgx',- 'regr_avgy',- 'regr_count',- 'regr_intercept',- 'regr_r2',- 'regr_slope',- 'regr_sxx',- 'regr_sxy',- 'regr_syy',- 'stddev',- 'stddev_pop',- 'stddev_samp',- 'string_agg',- 'sum',- 'var_pop',- 'var_samp',- 'variance',- // Window functions.- 'cume_dist',- 'dense_rank',- 'first_value',- 'lag',- 'last_value',- 'lead',- 'nth_value',- 'ntile',- 'percent_rank',- 'rank',- 'row_number',- // UUIDs.- 'gen_random_uuid',- 'uuid_extract_timestamp',- 'uuid_extract_version',- 'uuidv4',- 'uuidv7',- // Ranges and the plugin's own enum types.- 'datemultirange',- 'daterange',- 'enum_first',- 'enum_last',- 'enum_range',- 'int4multirange',- 'int4range',- 'int8multirange',- 'int8range',- 'isempty',- 'lower_inc',- 'lower_inf',- 'multirange',- 'nummultirange',- 'numrange',- 'range_merge',- 'tsmultirange',- 'tsrange',- 'tstzmultirange',- 'tstzrange',- 'upper_inc',- 'upper_inf',- // Geometry.- 'area',- 'bound_box',- 'box',- 'center',- 'circle',- 'diagonal',- 'diameter',- 'height',- 'isclosed',- 'isopen',- 'line',- 'lseg',- 'npoints',- 'path',- 'pclose',- 'point',- 'polygon',- 'popen',- 'radius',- 'slope',- 'width',- // Network addresses.- 'abbrev',- 'broadcast',- 'cidr',- 'family',- 'host',- 'hostmask',- 'inet_merge',- 'inet_same_family',- 'macaddr',- 'macaddr8',- 'masklen',- 'netmask',- 'network',- 'set_masklen',- // Full text search. ts_stat and ts_rewrite run SQL handed to them as text and stay refused.- 'array_to_tsvector',- 'json_to_tsvector',- 'jsonb_to_tsvector',- 'numnode',- 'phraseto_tsquery',- 'plainto_tsquery',- 'querytree',- 'setweight',- 'strip',- 'to_tsquery',- 'to_tsvector',- 'ts_delete',- 'ts_filter',- 'ts_headline',- 'ts_rank',- 'ts_rank_cd',- 'tsvector_to_array',- 'websearch_to_tsquery',- // The TABLESAMPLE methods (`TABLESAMPLE SYSTEM (10)`).- 'bernoulli',- 'system',-]);-/*** The SQL keywords that call a catalog function without parentheses and* describe the session or the server: the role names, the database and the@@ -464,6 +55,21 @@ export const SESSION_KEYWORDS: ReadonlySet<string> = new Set(['user',]);+/**+ * The refused names a plugin's table may well have as a column, which may+ * still follow a table, an alias or a parameter and a dot (`t.name`,+ * `n.version`). Postgres reads `x.f` as the column `f` of `x` and, when `x`+ * has no such column, as the call `f(x)`: with a function in FROM that+ * returns a single value (`FROM unnest(...) u`, `FROM generate_series(...)+ * g`) or a parameter (`$1.f`), that value is the argument. None of these+ * reads anything called that way: `version` takes no argument, so the+ * notation never calls it, and `money`, `name`, `oid`, `xid` and `xml` only+ * convert their argument to the type of that name. Every other refused name+ * is refused after a dot too. PGPLUG-021 holds each name here to that on the+ * lane's server.+ */+export const COLUMN_NAMES: ReadonlySet<string> = new Set(['money', 'name', 'oid', 'version', 'xid', 'xml']);+/** The function names of `pg_catalog` on every supported major, one per line, sorted. */export const CATALOG_FUNCTIONS_FILE = path.join(__dirname,@@ -476,21 +82,58 @@ export const CATALOG_FUNCTIONS_FILE = path.join('catalog-functions.txt',);-let catalog: ReadonlySet<string> | undefined;+/**+ * The functions of `pg_catalog` a plugin may call, one per line, grouped under+ * `#` comments. A list of names, not SQL, so it is kept as data beside the+ * catalog list. Each must exist in that list (a unit test checks).+ */+export const PLUGIN_FUNCTIONS_FILE = path.join(+ __dirname,+ '..',+ '..',+ '..',+ '..',+ 'assets',+ 'postgres',+ 'plugin-functions.txt',+);-/** The names in {@link CATALOG_FUNCTIONS_FILE}, read once. */-export function catalogFunctionNames(): ReadonlySet<string> {- catalog ??= new Set(+/** The names in `file`: its lines without blanks and `#` comments. */+function namesIn(file: string): ReadonlySet<string> {+ return new Set(fs- .readFileSync(CATALOG_FUNCTIONS_FILE, 'utf8')+ .readFileSync(file, 'utf8').split('\n').map((line) => line.trim())- .filter((line) => line !== ''),+ .filter((line) => line !== '' && !line.startsWith('#')),);+}++let catalog: ReadonlySet<string> | undefined;+let allowed: ReadonlySet<string> | undefined;++/** The names in {@link CATALOG_FUNCTIONS_FILE}, read once. */+export function catalogFunctionNames(): ReadonlySet<string> {+ catalog ??= namesIn(CATALOG_FUNCTIONS_FILE);return catalog;}+/** The names in {@link PLUGIN_FUNCTIONS_FILE}, read once. */+export function pluginFunctionNames(): ReadonlySet<string> {+ allowed ??= namesIn(PLUGIN_FUNCTIONS_FILE);+ return allowed;+}+/** Whether calling `name` reaches a function of `pg_catalog` a plugin may not call. */export function refusedCatalogCall(name: string): boolean {- return !PLUGIN_FUNCTIONS.has(name) && catalogFunctionNames().has(name);+ return !pluginFunctionNames().has(name) && catalogFunctionNames().has(name);+}++/**+ * Whether `name` after a dot (`x.name`, the column notation) may call a+ * function of `pg_catalog` a plugin may not call: one of+ * {@link refusedCatalogCall} that is not in {@link COLUMN_NAMES}.+ */+export function refusedCatalogField(name: string): boolean {+ return refusedCatalogCall(name) && !COLUMN_NAMES.has(name);}diff --git a/server/src/db/engine/postgres/plugin-sql-guard.ts b/server/src/db/engine/postgres/plugin-sql-guard.tsindex 8742f7953..7765e77ed 100644--- a/server/src/db/engine/postgres/plugin-sql-guard.ts+++ b/server/src/db/engine/postgres/plugin-sql-guard.ts@@ -1,5 +1,5 @@import { PLUGIN_SCHEMA_PREFIX } from './plugin-schema';-import { refusedCatalogCall, SESSION_KEYWORDS } from './plugin-sql-functions';+import { refusedCatalogCall, refusedCatalogField, SESSION_KEYWORDS } from './plugin-sql-functions';/*** What keeps a plugin's own SQL on Postgres inside its own schema.@@ -74,13 +74,15 @@ import { refusedCatalogCall, SESSION_KEYWORDS } from './plugin-sql-functions';* `plugin-sql-functions.ts` (`obj_description`, `format_type`, `version`,* `current_database`, ...: whatever reads the catalogs or the server rather* than its arguments), in either spelling of a call (`f(...)`, or the- * column notation `(x).f`), and the keywords that name the session's roles,- * database or schema (`current_user`, `session_user`, `current_catalog`, ...);+ * column notation `(x).f`, `u.f`, `$1.f`), and the keywords that name the+ * session's roles, database or schema (`current_user`, `session_user`,+ * `current_catalog`, ...);* - the object identifier types that look an object up by name* (`regclass`, `regtype`, `regproc`, `regprocedure`, `regoper`,* `regoperator`, `regconfig`, `regdictionary`, `regnamespace`, `regrole`,* `regcollation`, and their array types `_regclass`, ...), in every* spelling: `'x'::regtype`, `CAST('x' AS regtype)`, `regtype 'x'`, quoted;+ * and `aclitem`, whose input and output name roles;* - a temporary object: CREATE TEMP or TEMPORARY (also after OR REPLACE,* LOCAL or GLOBAL), and SELECT ... INTO TEMP; a temporary table outlives* the call on a pooled connection. Elsewhere `temp` is an ordinary name;@@ -207,6 +209,14 @@ const NAME_LOOKUP_TYPES = ['regcollation',];+/**+ * `aclitem`, a privilege as `grantee=privileges/grantor`, refused in every+ * spelling like the object identifier types: its input looks each role up by+ * name and its output names them, so `'=r'::aclitem` shows the cluster's+ * first superuser and `'x=r/x'::aclitem` tells whether a role exists.+ */+const ROLE_LOOKUP_TYPES = ['aclitem', '_aclitem'];+/** Functions and types refused under any spelling, quoted or not. */const REFUSED_NAMES = new Set(['set_config',@@ -221,6 +231,7 @@ const REFUSED_NAMES = new Set(['lowrite',...NAME_LOOKUP_TYPES,...NAME_LOOKUP_TYPES.map((type) => `_${type}`),+ ...ROLE_LOOKUP_TYPES,// Functions that take a relation, a type or another object by a name in a// string, or reach an index by one to maintain it.'has_any_column_privilege',@@ -556,19 +567,24 @@ const NAME_BEFORE = new Set(['into', 'table', 'view', 'references', 'exists']);/*** Refuses the word at `index` when it calls a function of `pg_catalog` a- * plugin may not call (`plugin-sql-functions.ts`): followed by `(`, unless- * it names an object after one of {@link NAME_BEFORE}, or in Postgres's- * column notation for a call, right after `).` or `].` (`(16386::oid).obj_description`).+ * plugin may not call (`plugin-sql-functions.ts`), unless it names an object+ * after one of {@link NAME_BEFORE}: followed by `(`, or after a dot, in+ * Postgres's column notation for a call (`(16386::oid).obj_description`, and+ * `u.obj_description` or `$1.obj_description`, where `u` is a function in+ * FROM that returns a single value); after a dot, the column names+ * `COLUMN_NAMES` in `plugin-sql-functions.ts` lists still pass.*/function checkCall(tokens: readonly Token[], index: number): void {const token = tokens[index];- if (token.kind !== 'word') return;- const before = tokens[index - 2];- const columnNotation = isPunct(tokens[index - 1], '.') && (isPunct(before, ')') || isPunct(before, ']'));- const called = columnNotation || (isPunct(tokens[index + 1], '(') && !namesObject(tokens, index));- if (called && refusedCatalogCall(token.value)) {+ if (token.kind !== 'word' || namesObject(tokens, index)) return;+ const call = isPunct(tokens[index + 1], '(');+ const field = !call && isPunct(tokens[index - 1], '.');+ if ((call && refusedCatalogCall(token.value)) || (field && refusedCatalogField(token.value))) {throw new PluginSqlRefused(`"${token.value}" is a function of the Postgres catalog that a plugin may not call; ` ++ (field+ ? `after a dot Postgres may read x.${token.value} as ${token.value}(x), so name such a column without its table or rename it; `+ : '') +"the plugin SDK's README lists the functions a plugin may call",);}diff --git a/server/tests/postgres/plugin-data.test.ts b/server/tests/postgres/plugin-data.test.tsindex ad1b8b458..cdb9f70a7 100644--- a/server/tests/postgres/plugin-data.test.ts+++ b/server/tests/postgres/plugin-data.test.ts@@ -24,7 +24,7 @@ import {poolClients,PostgresPluginDataStore,} from '../../src/db/engine/postgres/plugin-data-store';-import { catalogFunctionNames } from '../../src/db/engine/postgres/plugin-sql-functions';+import { catalogFunctionNames, COLUMN_NAMES } from '../../src/db/engine/postgres/plugin-sql-functions';import { TrekPostgreSqlDriver } from '../../src/db/engine/postgres/postgres-driver';import { putTempSchemaLast } from '../../src/db/engine/postgres/session-search-path';import { DATABASE_SETTINGS } from '../../src/nest/database/database-engine.module';@@ -615,6 +615,9 @@ describe('plugin data on Postgres', () => {"select has_table_privilege('public.users', 'select')","select currtid2('public.users', '(0,1)')","select to_regtype('public.users')",+ // aclitem names roles: the cluster's first superuser, whether a role exists.+ "select '=r'::aclitem::text",+ "select cast('x=r/x' as aclitem)",];const stores = [data.open('pg-reg'), superuserStore('pg-reg-su')];await Promise.all(@@ -697,8 +700,8 @@ describe('plugin data on Postgres', () => {expect(unlisted,'These functions of this Postgres are missing from server/assets/postgres/catalog-functions.txt. ' +- 'Add each name there (one per line, keep it sorted), and to PLUGIN_FUNCTIONS in ' +- 'src/db/engine/postgres/plugin-sql-functions.ts only if it works on its arguments alone ' ++ 'Add each name there (one per line, keep it sorted), and to server/assets/postgres/plugin-functions.txt ' ++ 'only if it works on its arguments alone ' +'and reads neither the catalogs nor the server.',).toEqual([]);@@ -712,6 +715,9 @@ describe('plugin data on Postgres', () => {`select obj_description(${oid}, 'pg_class')`,`select col_description(${oid}, 1)`,`select (${oid}::oid).obj_description`,+ `select g.obj_description from generate_series(${oid}, ${oid}) g`,+ `select u.obj_description from unnest(array[${oid}::oid]) u`,+ 'select g.txid_status from generate_series(1, 3) g',`select "obj_description"(${oid})`,"select shobj_description(10, 'pg_authid')",`select format_type(${oid}, null)`,@@ -723,6 +729,14 @@ describe('plugin data on Postgres', () => {'select current_catalog',].map((sql) => expect(store.query(sql), sql).rejects.toThrow(/a plugin may not (call|read)/)),);+ await expect(store.query('select $1.obj_description', [oid])).rejects.toThrow(/a plugin may not call/);+ // The refused names a column may have after a dot read nothing when Postgres calls them that way.+ const calls = await asSuper<{ f: string }>(+ 'select p.oid::regprocedure::text as f from pg_proc p ' ++ `where p.pronamespace = 'pg_catalog'::regnamespace and p.proname in (${[...COLUMN_NAMES].map((n) => `'${n}'`).join(', ')}) ` ++ 'and p.pronargs >= 1 and p.pronargs - p.pronargdefaults <= 1 and format_type(p.prorettype, null) <> p.proname',+ );+ expect(calls, 'a COLUMN_NAMES entry that the column notation calls with one argument').toEqual([]);// A table named like a refused function, and the functions a plugin needs, still work.await store.exec('INSERT INTO version (body) VALUES ($1), ($2)', ['Alpha', 'beta']);expect(@@ -735,6 +749,13 @@ describe('plugin data on Postgres', () => {{ b: 'alpha', n: 5, k: '1', d: true, u: true },{ b: 'beta', n: 4, k: '2', d: true, u: true },]);+ await store.migrate('002', 'ALTER TABLE version ADD COLUMN name text');+ expect(+ await store.query("SELECT v.name, excluded.name AS e FROM version v, (SELECT 'x' AS name) excluded"),+ ).toEqual([+ { name: null, e: 'x' },+ { name: null, e: 'x' },+ ]);await asSuper('comment on table users is null');});});diff --git a/server/tests/unit/db/engine/postgres/plugin-sql-functions.test.ts b/server/tests/unit/db/engine/postgres/plugin-sql-functions.test.tsindex e1d1fed33..3e689f39b 100644--- a/server/tests/unit/db/engine/postgres/plugin-sql-functions.test.ts+++ b/server/tests/unit/db/engine/postgres/plugin-sql-functions.test.ts@@ -9,7 +9,8 @@import {catalogFunctionNames,CATALOG_FUNCTIONS_FILE,- PLUGIN_FUNCTIONS,+ pluginFunctionNames,+ PLUGIN_FUNCTIONS_FILE,} from '../../../../../src/db/engine/postgres/plugin-sql-functions';import { parsePluginSql } from '../../../../../src/db/engine/postgres/plugin-sql-guard';@@ -24,8 +25,19 @@ describe('functions a plugin may call on Postgres', () => {expect(lines.every((line) => /^[A-Za-z0-9_]+$/.test(line))).toBe(true);});+ it('lists the allowed functions one per line without duplicates, comments aside', () => {+ const names = fs+ .readFileSync(PLUGIN_FUNCTIONS_FILE, 'utf8')+ .split(/\r?\n/)+ .filter((line) => line !== '' && !line.startsWith('#'));+ expect(names.length).toBeGreaterThan(300);+ expect(names.every((line) => /^[a-z0-9_]+$/.test(line))).toBe(true);+ expect(new Set(names).size).toBe(names.length);+ expect(pluginFunctionNames()).toEqual(new Set(names));+ });+it('allows only functions the catalog has, so a typo cannot stand in for one', () => {- const missing = [...PLUGIN_FUNCTIONS].filter((name) => !catalogFunctionNames().has(name));+ const missing = [...pluginFunctionNames()].filter((name) => !catalogFunctionNames().has(name));expect(missing).toEqual([]);});@@ -55,6 +67,15 @@ describe('functions a plugin may call on Postgres', () => {'select (16386::oid).obj_description','select (16386::oid)."obj_description"','select (array[16386::oid])[1].obj_description',+ // The column notation after an alias or a parameter: a function in FROM+ // that returns a single value, or the parameter, is the argument.+ 'select u.obj_description from unnest(array[16386::oid]) u',+ 'select g.obj_description from generate_series(1, 20000) g',+ 'select o.obj_description from rows from (unnest(array[16386::oid])) o',+ 'select $1.obj_description',+ 'select g."current_schemas" from unnest(array[true]) g',+ 'select g.txid_status from generate_series(1, 3) g',+ 'select n.x from notes n, unnest(array[1]) g where g.mxid_age > 0','select n.x from notes n where n.body = (select version())','create table t (v text default version())','insert into notes (body) values (current_database())',@@ -93,6 +114,11 @@ describe('functions a plugin may call on Postgres', () => {'CREATE TABLE notes (id bigint, v bigint REFERENCES version (id))','CREATE VIEW version (a) AS SELECT 1','select n.version, n.user_id, "user", "current_user" from notes n',+ // The refused names a table may well have as a column, after a dot.+ 'select n.name, n.money, n.oid, n.xid, n.xml, n.version from notes n',+ 'select (n).name, $1.name from notes n',+ "insert into notes (id, name) values (1, 'a') on conflict (id) do update set name = excluded.name",+ 'select n.body from trek_plugin_notes.notes n join trek_plugin_notes.version v on v.id = n.id','select version from notes','select mine(1, 2)',"select '[1,2)'::span",diff --git a/server/tests/unit/db/engine/postgres/plugin-sql-guard.test.ts b/server/tests/unit/db/engine/postgres/plugin-sql-guard.test.tsindex ad63a8593..56ae4d7cb 100644--- a/server/tests/unit/db/engine/postgres/plugin-sql-guard.test.ts+++ b/server/tests/unit/db/engine/postgres/plugin-sql-guard.test.ts@@ -200,6 +200,12 @@ describe('plugin SQL guard', () => {["select currtid2('public.users', '(0,1)')", /"currtid2" may not be named/],["select gin_clean_pending_list('public.users_idx')", /"gin_clean_pending_list" may not be named/],["select to_regtype('int4')", /"to_regtype" may not be named/],+ // aclitem looks its roles up by name and names them in its output.+ ["select '=r'::aclitem", /"aclitem" may not be named/],+ ["select cast('x=r/x' as aclitem)", /"aclitem" may not be named/],+ [`select array['=r']::"aclitem"[]`, /"aclitem" may not be named/],+ ["select '{=r}'::_aclitem", /"_aclitem" may not be named/],+ ['CREATE TABLE grants (a aclitem)', /"aclitem" may not be named/],// A base type is built from C functions, which only a superuser may do.['CREATE TYPE fake (INPUT = int4in, OUTPUT = int4out, INTERNALLENGTH = 1000)', /composite, enum or range/],// The protocol ends a statement's text at a NUL, in a string as anywhere else.diff --git a/wiki/Database-Postgres.md b/wiki/Database-Postgres.mdindex 7d53c22c8..baeddd1a2 100644--- a/wiki/Database-Postgres.md+++ b/wiki/Database-Postgres.md@@ -200,7 +200,7 @@ A plugin with the `db:own` permission keeps its own database. On SQLite that is- **TREK's role creates the schemas**, so it needs the `CREATE` privilege on the database, which the role that owns the database has.- **No plugin SQL on a privileged role.** While `TREK_DB_URL` connects as a role TREK refuses restores for (a superuser or a member of one, or a role that may reach the server's files or programs; see [A role that is not a superuser](#a-role-that-is-not-a-superuser)), every plugin database call fails with "Plugin databases (db:own) are refused on Postgres ...", and the boot log says so. A plugin's SQL runs as TREK's role, and such a role could change the system catalogs for the whole server. Connect TREK as a role that owns its database and is not a superuser, and restart; TREK reads the role once per pool connection.- **A plugin's SQL stays in its schema**, in layers the database enforces as well as TREK's own check:- - TREK refuses a statement before it runs when it names another schema, the system catalogs, a function that could reach past the schema, or a type that looks an object up by name (`regclass`, `regtype`, `regconfig` and the other `reg*` types, `has_table_privilege` and its siblings). Of PostgreSQL's own functions a plugin may call only those on an allowlist, the ones that work on their arguments alone (string, number, date and time, JSON, array, aggregate, window, UUID, range, geometry, network address and full text search functions). Every other one is refused, so a function that reads the catalogs or the server (`obj_description`, `format_type`, `version()`, `current_database()`, `inet_server_addr()`, ...) cannot reveal the names or comments of TREK's objects, and neither can a function a later PostgreSQL adds; the keywords `current_user`, `session_user` and their siblings are refused too. It also refuses temporary objects (`CREATE TEMP`/`TEMPORARY` and `SELECT ... INTO TEMP`; a column named `temp` is fine), `INTO` anywhere but after the `INSERT` or `MERGE` that is the statement's verb, hexadecimal, octal and binary numbers, and control characters or non-ASCII whitespace outside strings, which Postgres reads differently from the check.+ - TREK refuses a statement before it runs when it names another schema, the system catalogs, a function that could reach past the schema, or a type that looks an object up by name (`regclass`, `regtype`, `regconfig` and the other `reg*` types, `aclitem`, `has_table_privilege` and its siblings). Of PostgreSQL's own functions a plugin may call only those on an allowlist, the ones that work on their arguments alone (string, number, date and time, JSON, array, aggregate, window, UUID, range, geometry, network address and full text search functions). Every other one is refused, so a function that reads the catalogs or the server (`obj_description`, `format_type`, `version()`, `current_database()`, `inet_server_addr()`, ...) cannot reveal the names or comments of TREK's objects, and neither can a function a later PostgreSQL adds; the keywords `current_user`, `session_user` and their siblings are refused too. It also refuses temporary objects (`CREATE TEMP`/`TEMPORARY` and `SELECT ... INTO TEMP`; a column named `temp` is fine), `INTO` anywhere but after the `INSERT` or `MERGE` that is the statement's verb, hexadecimal, octal and binary numbers, and control characters or non-ASCII whitespace outside strings, which Postgres reads differently from the check.- Right before an `ALTER`, `DROP`, `REFRESH`, `TRUNCATE` or `CREATE INDEX ... ON`, Postgres itself resolves the objects the statement changes, and TREK refuses it unless each one lies in the plugin's schema. An unqualified `int4` or `text` is the built-in type and is refused, whatever the role may do.- Each statement is sent on its own over the extended query protocol, which runs one statement and no more.- Every connection of TREK's pool searches the temporary schema last, and a plugin call drops the temporary tables and other session state of the connection it used before handing it back, so a temporary table can never stand in for one of TREK's.