From f928f4b1ca3b00814b69d51df753555c1f3c5b4e Mon Sep 17 00:00:00 2001 From: Maurice Date: Tue, 24 Nov 2026 23:15:26 +0100 Subject: [PATCH] fix(postgres): connect over a Unix socket TREK_DB_URL could not name a Unix socket. MikroORM builds the pool from the URL's own host and drops a host parameter, so postgresql://trek@localhost/trek?host=/var/run/postgresql connected to localhost over TCP. A percent-encoded socket path as the host reached the pool, but the client tools got it undecoded in PGHOST, so backups, restores and the safety copy before a migration failed. The server address is now read once, the way libpq reads a connection URL: a host or port parameter takes the place of the URL's own, and a host written into the URL is percent-decoded. The pool and the client tools both get that address. The wiki and .env.example show the socket form. --- server/.env.example | 2 +- server/src/db/engine/postgres/pg-process.ts | 7 +++- .../src/db/engine/postgres/postgres-engine.ts | 5 +++ .../src/db/engine/postgres/server-address.ts | 28 ++++++++++++++ server/tests/unit/db/engine/engine.test.ts | 13 +++++++ .../unit/db/engine/postgres/pg-tools.test.ts | 9 +++++ .../db/engine/postgres/server-address.test.ts | 38 +++++++++++++++++++ wiki/Database-Postgres.md | 2 +- 8 files changed, 100 insertions(+), 4 deletions(-) create mode 100644 server/src/db/engine/postgres/server-address.ts create mode 100644 server/tests/unit/db/engine/postgres/server-address.test.ts diff --git a/server/.env.example b/server/.env.example index 1264bf13f..df947c9e8 100644 --- a/server/.env.example +++ b/server/.env.example @@ -52,7 +52,7 @@ DEMO_MODE=false # Demo mode: resets data hourly # BACKUP_MAX_DECOMPRESSED_MB=5120 # Max size (MB) a restore archive may unpack to, on both restore paths: the zip-bomb guard. Raise it if a large backup is refused with "Backup exceeds the maximum decompressed size". (default: 5120) # BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size). -# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS. +# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). A Unix socket: postgresql://trek@localhost/trek?host=/var/run/postgresql (a host= or port= parameter takes the place of the URL's own, as in libpq). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS. # TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/18/bin # The directory holding pg_dump, pg_restore and psql, which back up and restore a Postgres database. Unset, TREK looks in /usr/lib/postgresql/<18..14>/bin, newest first, then /usr/local/bin and /usr/bin (the Docker image installs the version 18 tools, which work with every supported server; tools older than the server are refused). Unused on SQLite. # TREK_DB_POOL_MAX=10 # Most connections TREK opens to the Postgres database (1 to 100). Unused on SQLite. (default: 10) # TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot. diff --git a/server/src/db/engine/postgres/pg-process.ts b/server/src/db/engine/postgres/pg-process.ts index f3a987fa4..ebd751623 100644 --- a/server/src/db/engine/postgres/pg-process.ts +++ b/server/src/db/engine/postgres/pg-process.ts @@ -1,3 +1,5 @@ +import { pgServerAddress } from './server-address'; + import { execFile, spawn } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; @@ -65,9 +67,10 @@ export function resolvePgTool(tool: PgTool, binDir: string | undefined): string */ export function pgConnectionEnv(url: string): Record { const parsed = new URL(url); + const address = pgServerAddress(url); const env: Record = { - PGHOST: parsed.hostname.replace(/^\[(.*)\]$/, '$1'), - PGPORT: parsed.port || '5432', + PGHOST: address.host, + PGPORT: String(address.port ?? 5432), PGDATABASE: decodeURIComponent(parsed.pathname.replace(/^\//, '')), PGCONNECT_TIMEOUT: CONNECT_TIMEOUT_SECONDS, }; diff --git a/server/src/db/engine/postgres/postgres-engine.ts b/server/src/db/engine/postgres/postgres-engine.ts index 60cdaa15c..e69e01858 100644 --- a/server/src/db/engine/postgres/postgres-engine.ts +++ b/server/src/db/engine/postgres/postgres-engine.ts @@ -5,6 +5,7 @@ import type { DatabaseEngine } from '../engine'; import { redactUrl } from '../redact-url'; import { TrekPostgreSqlDriver } from './postgres-driver'; import { bootstrapPostgresSchema, defaultPostgresBootstrapDeps, type PostgresBootstrapDeps } from './schema-bootstrap'; +import { pgServerAddress } from './server-address'; import { putTempSchemaLast } from './session-search-path'; import { sslOptionFor } from './ssl'; import type { EntityManager } from '@mikro-orm/core'; @@ -84,9 +85,13 @@ export class PostgresEngine implements DatabaseEngine { /** Every new pool connection first puts `pg_temp` last on its `search_path` (`session-search-path.ts`). */ ormOptions() { const ssl = sslOptionFor(this.settings.url); + // MikroORM takes the address from the URL's authority alone; a `host` parameter (a socket directory) would be lost. + const { host, port } = pgServerAddress(this.settings.url); return { driver: TrekPostgreSqlDriver, clientUrl: this.settings.url, + host, + port, pool: { min: 0, max: this.settings.poolMax }, driverOptions: ssl === undefined ? {} : { ssl }, onCreateConnection: (connection: unknown) => putTempSchemaLast(connection as DatabaseConnection), diff --git a/server/src/db/engine/postgres/server-address.ts b/server/src/db/engine/postgres/server-address.ts new file mode 100644 index 000000000..86cb8360b --- /dev/null +++ b/server/src/db/engine/postgres/server-address.ts @@ -0,0 +1,28 @@ +/** Where the Postgres server listens, as TREK_DB_URL names it. */ +interface PgServerAddress { + /** A host name, an IP address, or the directory of a Unix socket (a path starting with `/`); empty when the URL names none. */ + host: string; + port: number | undefined; +} + +/** + * The server address in `url`, read the way libpq reads a connection URL: a + * `host` or `port` query parameter takes the place of the URL's own, so + * `postgresql://trek@localhost/trek?host=/var/run/postgresql` connects through + * the socket in that directory, and a host written into the URL itself is + * percent-decoded (`%2Fvar%2Frun%2Fpostgresql`). The app's pool and the client + * tools both connect to this one address, so a backup reaches the database + * the app runs on. + */ +export function pgServerAddress(url: string): PgServerAddress { + const parsed = new URL(url); + const params = parsed.searchParams; + const host = params.get('host') ?? decodeURIComponent(parsed.hostname.replace(/^\[(.*)\]$/, '$1')); + const rawPort = params.get('port') ?? parsed.port; + if (rawPort === '') return { host, port: undefined }; + const port = Number(rawPort); + if (!/^\d+$/.test(rawPort) || port < 1 || port > 65535) { + throw new Error(`TREK_DB_URL names port "${rawPort}", which is not a port number.`); + } + return { host, port }; +} diff --git a/server/tests/unit/db/engine/engine.test.ts b/server/tests/unit/db/engine/engine.test.ts index d60b68026..22191e0ab 100644 --- a/server/tests/unit/db/engine/engine.test.ts +++ b/server/tests/unit/db/engine/engine.test.ts @@ -28,6 +28,8 @@ describe('resolveEngine', () => { expect(engine.ormOptions()).toEqual({ driver: TrekPostgreSqlDriver, clientUrl: PG_URL, + host: 'db.example', + port: 5432, pool: { min: 0, max: 7 }, driverOptions: {}, // Puts pg_temp last on every new connection's search_path (session-search-path.ts). @@ -35,6 +37,17 @@ describe('resolveEngine', () => { }); }); + it('ENGINE-004: a Unix socket reaches the pool, as a host parameter or as a percent-encoded host', () => { + const viaParam = resolveEngine( + deriveDb({ TREK_DB_URL: 'postgresql://trek:s3cret@localhost/trek?host=/var/run/postgresql' }), + ).ormOptions(); + expect(viaParam).toMatchObject({ host: '/var/run/postgresql', port: undefined }); + const encoded = resolveEngine( + deriveDb({ TREK_DB_URL: 'postgresql://trek:s3cret@%2Fvar%2Frun%2Fpostgresql:5433/trek' }), + ).ormOptions(); + expect(encoded).toMatchObject({ host: '/var/run/postgresql', port: 5433 }); + }); + it('ENGINE-003: describes a Postgres database without its password', () => { const engine = resolveEngine(deriveDb({ TREK_DB_URL: `${PG_URL}?sslmode=require&password=other` })); expect(engine.describe()).toBe('Postgres postgresql://trek:***@db.example:5432/trek'); diff --git a/server/tests/unit/db/engine/postgres/pg-tools.test.ts b/server/tests/unit/db/engine/postgres/pg-tools.test.ts index f9a500111..549343cec 100644 --- a/server/tests/unit/db/engine/postgres/pg-tools.test.ts +++ b/server/tests/unit/db/engine/postgres/pg-tools.test.ts @@ -77,6 +77,15 @@ describe('pg-tools', () => { PGUSER: 'u', PGCONNECT_TIMEOUT: '10', }); + // A Unix socket: the host parameter wins over the URL's host, as in libpq, and an encoded host is decoded. + expect(pgConnectionEnv('postgresql://u@localhost/d?host=/var/run/postgresql&port=5433')).toMatchObject({ + PGHOST: '/var/run/postgresql', + PGPORT: '5433', + }); + expect(pgConnectionEnv('postgresql://u@%2Fvar%2Frun%2Fpostgresql/d')).toMatchObject({ + PGHOST: '/var/run/postgresql', + PGPORT: '5432', + }); }); it('PGTOOLS-003: SSL is verified as the app pool verifies it, against the URL root certificate when it names one', () => { diff --git a/server/tests/unit/db/engine/postgres/server-address.test.ts b/server/tests/unit/db/engine/postgres/server-address.test.ts new file mode 100644 index 000000000..0f16a2245 --- /dev/null +++ b/server/tests/unit/db/engine/postgres/server-address.test.ts @@ -0,0 +1,38 @@ +/** + * Where TREK_DB_URL says the Postgres server listens, read as libpq reads a + * connection URL, so the pool and the client tools reach the same server. + */ +import { pgServerAddress } from '../../../../../src/db/engine/postgres/server-address'; + +import { describe, expect, it } from 'vitest'; + +describe('pgServerAddress', () => { + it('PGADDR-001: a TCP host and port come from the URL itself', () => { + expect(pgServerAddress('postgresql://trek:pw@db.example:6543/trek')).toEqual({ host: 'db.example', port: 6543 }); + expect(pgServerAddress('postgres://trek@[::1]/trek')).toEqual({ host: '::1', port: undefined }); + }); + + it('PGADDR-002: a host or port parameter takes the place of the URL’s own, as in libpq', () => { + expect(pgServerAddress('postgresql://trek@localhost/trek?host=/var/run/postgresql')).toEqual({ + host: '/var/run/postgresql', + port: undefined, + }); + expect(pgServerAddress('postgresql:///trek?host=/run/postgresql&port=5433')).toEqual({ + host: '/run/postgresql', + port: 5433, + }); + }); + + it('PGADDR-003: a socket directory written into the URL is percent-decoded', () => { + expect(pgServerAddress('postgresql://trek@%2Fvar%2Frun%2Fpostgresql/trek')).toEqual({ + host: '/var/run/postgresql', + port: undefined, + }); + }); + + it('PGADDR-004: a port that is no port number is refused', () => { + for (const port of ['0', '65536', 'abc', '54x']) { + expect(() => pgServerAddress(`postgresql://trek@localhost/trek?port=${port}`), port).toThrow(/not a port number/); + } + }); +}); diff --git a/wiki/Database-Postgres.md b/wiki/Database-Postgres.md index 77df3add2..3acb690b0 100644 --- a/wiki/Database-Postgres.md +++ b/wiki/Database-Postgres.md @@ -23,7 +23,7 @@ Postgres does not make TREK scale out. TREK still runs as one process. See [Limi | Variable | What it does | Default | |---|---|---| -| `TREK_DB_URL` | Connection URL, `postgres://user:password@host:5432/database` (or `postgresql://`). Setting it selects Postgres. | unset (SQLite) | +| `TREK_DB_URL` | Connection URL, `postgres://user:password@host:5432/database` (or `postgresql://`). Setting it selects Postgres. For a Unix socket, name its directory in a `host` parameter: `postgresql://user:password@localhost/database?host=/var/run/postgresql`. | unset (SQLite) | | `TREK_DB_POOL_MAX` | Most connections TREK opens to the database, from 1 to 100. The pool sets no minimum, so idle connections can close. | `10` | | `TREK_DB_PG_BIN_DIR` | Directory holding `pg_dump`, `pg_restore` and `psql`. | see below |