From a9fd443b63a929c0719411e4f1d3c149572d835f Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 26 Nov 2026 23:34:22 +0100 Subject: [PATCH] feat(db): present a Postgres client certificate from sslcert and sslkey in TREK_DB_URL A Postgres server that authenticates clients by certificate could not be used: TREK read only sslmode and sslrootcert from TREK_DB_URL, so neither the connection pool nor pg_dump, pg_restore and psql ever offered a client certificate (discussion #3215). TREK_DB_URL now also takes libpq's sslcert and sslkey. Both must be given together and only with a verifying sslmode, and each file must be readable, or the boot refuses with the same kind of message as for sslrootcert. The pool gets them as its TLS cert and key, the tools as PGSSLCERT and PGSSLKEY. The Postgres wiki page shows the URL, how to mount the files with Compose or the chart's extraVolumes, and libpq's rule for the key file's permissions, which the backup tools enforce. --- server/.env.example | 2 +- server/src/db/engine/postgres/pg-process.ts | 7 ++- server/src/db/engine/postgres/ssl.ts | 45 +++++++++++++++---- server/tests/unit/db/engine/engine.test.ts | 35 +++++++++++++++ .../unit/db/engine/postgres/pg-tools.test.ts | 15 +++++++ wiki/Database-Postgres.md | 12 +++++ 6 files changed, 105 insertions(+), 11 deletions(-) diff --git a/server/.env.example b/server/.env.example index df947c9e8..53d2da7e4 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). 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_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). For a server that asks for a client certificate, sslcert= and sslkey= name the certificate and its key file, both together and only with a verifying sslmode. 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 ebd751623..53c038370 100644 --- a/server/src/db/engine/postgres/pg-process.ts +++ b/server/src/db/engine/postgres/pg-process.ts @@ -63,7 +63,8 @@ export function resolvePgTool(tool: PgTool, binDir: string | undefined): string * read. An sslmode that asks for SSL verifies the server's certificate, as the * app's own pool does (`postgres-engine.ts`): against the URL's sslrootcert, * else the system's trusted CAs (`system`, which `run` accepts only from a - * client that understands it). + * client that understands it), and presents the URL's client certificate + * (sslcert and sslkey) when it names one. */ export function pgConnectionEnv(url: string): Record { const parsed = new URL(url); @@ -81,6 +82,10 @@ export function pgConnectionEnv(url: string): Record { else if (sslmode) { env.PGSSLMODE = 'verify-full'; env.PGSSLROOTCERT = parsed.searchParams.get('sslrootcert') ?? 'system'; + const clientCert = parsed.searchParams.get('sslcert'); + const clientKey = parsed.searchParams.get('sslkey'); + if (clientCert) env.PGSSLCERT = clientCert; + if (clientKey) env.PGSSLKEY = clientKey; } return env; } diff --git a/server/src/db/engine/postgres/ssl.ts b/server/src/db/engine/postgres/ssl.ts index 5b96a0c50..13cda53b8 100644 --- a/server/src/db/engine/postgres/ssl.ts +++ b/server/src/db/engine/postgres/ssl.ts @@ -4,10 +4,23 @@ import { readFileSync } from 'node:fs'; const VERIFYING_MODES = new Set(['require', 'verify-ca', 'verify-full']); /** The `ssl` option of a `pg` pool, as `sslOptionFor` builds it. */ -type PgSslOption = false | { rejectUnauthorized: true; ca?: string }; +type PgSslOption = false | VerifiedSsl; + +/** SSL that verifies the server, with the CA and the client certificate the URL names. */ +type VerifiedSsl = { rejectUnauthorized: true; ca?: string; cert?: string; key?: string }; + +/** The contents of the file a URL parameter names, or the refusal that names the parameter. */ +function readNamedFile(param: string, file: string): string { + try { + return readFileSync(file, 'utf8'); + } catch (error) { + throw new Error(`TREK_DB_URL names ${param} ${file}, which cannot be read.`, { cause: error }); + } +} /** - * The `ssl` option for the pool, from the URL's `sslmode` and `sslrootcert`. + * The `ssl` option for the pool, from the URL's `sslmode`, `sslrootcert`, + * `sslcert` and `sslkey`. * * MikroORM builds the pool from the URL's host, port, user, password and * database alone and drops the rest of the query, so an `sslmode` in @@ -17,26 +30,40 @@ type PgSslOption = false | { rejectUnauthorized: true; ca?: string }; * default (no SSL). A mode that would connect without verifying (`prefer`, * `allow`, `no-verify`) or that is misspelt refuses, rather than quietly * connecting with less than was asked. `sslrootcert` names the CA file a host - * that signs its own certificates needs (Supabase's, say). + * that signs its own certificates needs (Supabase's, say). `sslcert` and + * `sslkey` name the client certificate and its key for a server that wants + * one (mutual TLS); they come together or not at all, and only with a + * verifying mode. */ export function sslOptionFor(url: string): PgSslOption | undefined { const params = new URL(url).searchParams; const mode = params.get('sslmode'); const rootCert = params.get('sslrootcert'); + const clientCert = params.get('sslcert'); + const clientKey = params.get('sslkey'); + if ((clientCert === null) !== (clientKey === null)) { + throw new Error('TREK_DB_URL names only one of sslcert and sslkey; a client certificate needs both.'); + } + const hasClientCert = clientCert !== null && clientKey !== null; if (mode === null) { if (rootCert !== null) throw new Error('TREK_DB_URL names an sslrootcert without sslmode=verify-full.'); + if (hasClientCert) throw new Error('TREK_DB_URL names an sslcert and sslkey without sslmode=verify-full.'); return undefined; } - if (mode === 'disable') return false; + if (mode === 'disable') { + if (hasClientCert) throw new Error('TREK_DB_URL names an sslcert and sslkey with sslmode=disable.'); + return false; + } if (!VERIFYING_MODES.has(mode)) { throw new Error( `TREK_DB_URL has sslmode "${mode}"; use disable, require, verify-ca or verify-full (all but disable verify the server).`, ); } - if (rootCert === null) return { rejectUnauthorized: true }; - try { - return { rejectUnauthorized: true, ca: readFileSync(rootCert, 'utf8') }; - } catch (error) { - throw new Error(`TREK_DB_URL names sslrootcert ${rootCert}, which cannot be read.`, { cause: error }); + const option: VerifiedSsl = { rejectUnauthorized: true }; + if (rootCert !== null) option.ca = readNamedFile('sslrootcert', rootCert); + if (hasClientCert) { + option.cert = readNamedFile('sslcert', clientCert); + option.key = readNamedFile('sslkey', clientKey); } + return option; } diff --git a/server/tests/unit/db/engine/engine.test.ts b/server/tests/unit/db/engine/engine.test.ts index 22191e0ab..f3207ac4c 100644 --- a/server/tests/unit/db/engine/engine.test.ts +++ b/server/tests/unit/db/engine/engine.test.ts @@ -96,6 +96,41 @@ describe('sslOptionFor', () => { rmSync(dir, { recursive: true, force: true }); } }); + + it('ENGINE-014: presents the client certificate in sslcert and sslkey (mutual TLS), both or neither, only when verifying', () => { + const dir = mkdtempSync(path.join(tmpdir(), 'trek-mtls-')); + try { + const cert = path.join(dir, 'client.crt'); + const key = path.join(dir, 'client.key'); + writeFileSync(cert, '-----BEGIN CERTIFICATE-----\nclient\n-----END CERTIFICATE-----\n'); + writeFileSync(key, '-----BEGIN PRIVATE KEY-----\nclient\n-----END PRIVATE KEY-----\n'); + const pair = `sslcert=${encodeURIComponent(cert)}&sslkey=${encodeURIComponent(key)}`; + expect(sslOptionFor(`${PG_URL}?sslmode=verify-full&${pair}`)).toEqual({ + rejectUnauthorized: true, + cert: readFileSync(cert, 'utf8'), + key: readFileSync(key, 'utf8'), + }); + expect(() => sslOptionFor(`${PG_URL}?sslmode=verify-full&sslcert=${encodeURIComponent(cert)}`)).toThrow( + /only one of sslcert and sslkey/, + ); + expect(() => sslOptionFor(`${PG_URL}?sslmode=verify-full&sslkey=${encodeURIComponent(key)}`)).toThrow( + /only one of sslcert and sslkey/, + ); + expect(() => sslOptionFor(`${PG_URL}?sslmode=disable&${pair}`)).toThrow( + /sslcert and sslkey with sslmode=disable/, + ); + expect(() => sslOptionFor(`${PG_URL}?${pair}`)).toThrow(/sslcert and sslkey without sslmode/); + const missing = encodeURIComponent(path.join(dir, 'no.key')); + expect(() => + sslOptionFor(`${PG_URL}?sslmode=require&sslcert=${encodeURIComponent(cert)}&sslkey=${missing}`), + ).toThrow(/sslkey .* cannot be read/); + expect(() => + sslOptionFor(`${PG_URL}?sslmode=require&sslcert=${missing}&sslkey=${encodeURIComponent(key)}`), + ).toThrow(/sslcert .* cannot be read/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); }); describe('redactUrl', () => { 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 549343cec..4733bced5 100644 --- a/server/tests/unit/db/engine/postgres/pg-tools.test.ts +++ b/server/tests/unit/db/engine/postgres/pg-tools.test.ts @@ -97,6 +97,21 @@ describe('pg-tools', () => { }); }); + it('PGTOOLS-023: the client certificate in sslcert and sslkey reaches the tools as PGSSLCERT and PGSSLKEY', () => { + const env = pgConnectionEnv( + 'postgres://u@h/d?sslmode=verify-full&sslrootcert=%2Fcerts%2Fca.crt&sslcert=%2Fcerts%2Fclient.crt&sslkey=%2Fcerts%2Fclient.key', + ); + expect(env).toMatchObject({ + PGSSLMODE: 'verify-full', + PGSSLROOTCERT: '/certs/ca.crt', + PGSSLCERT: '/certs/client.crt', + PGSSLKEY: '/certs/client.key', + }); + const plain = pgConnectionEnv('postgres://u@h/d?sslmode=require'); + expect(plain.PGSSLCERT).toBeUndefined(); + expect(plain.PGSSLKEY).toBeUndefined(); + }); + it('PGTOOLS-004: pg_dump writes a private custom-format dump beside the target and renames it into place', async () => { installFakeTool(bin, 'psql', { snippets: [answersSchema()] }); const log = installFakeTool(bin, 'pg_dump', { snippets: [writesFile('dump')] }); diff --git a/wiki/Database-Postgres.md b/wiki/Database-Postgres.md index 3acb690b0..b30deb386 100644 --- a/wiki/Database-Postgres.md +++ b/wiki/Database-Postgres.md @@ -47,6 +47,18 @@ Without `sslmode`, the connection pool uses no SSL. The client tools use the lib `sslrootcert=` names the file holding the certificate authority that signs the server's certificate. It is needed when the server uses a certificate from a private CA, and it is valid only together with one of the verifying modes. The file must be readable inside the container, so mount it into the container and point the URL at the path inside the container. Without `sslrootcert`, the system's trusted certificate authorities are used. The client tools read the system's authorities only from version 16 on, so with an older client (outside the Docker image) set `sslrootcert`; TREK refuses a backup or restore with such a client otherwise and says so. +#### Client certificates + +A server that asks for a client certificate (mutual TLS) gets one from `sslcert=` and `sslkey=`, which name the certificate and its private key, with the libpq parameter names: + +``` +postgres://trek@db/trek?sslmode=verify-full&sslrootcert=/certs/ca.crt&sslcert=/certs/client.crt&sslkey=/certs/client.key +``` + +Both must be given together, and only with one of the verifying modes; TREK refuses to start otherwise, and also when a file cannot be read. The connection pool and the backup and restore tools present the same certificate. Mount the files into the container like the CA file: with Docker Compose a read-only volume such as `./certs:/certs:ro`, on Kubernetes a Secret through the chart's `extraVolumes` and `extraVolumeMounts` (see [Install: Helm](Install-Helm#further-volumes)). + +The key file must satisfy libpq's rule, or `pg_dump`, `pg_restore` and `psql` refuse it and backups fail: mode `0600` when it is owned by the user TREK runs as, or owned by root with mode `0640` at most. A Kubernetes Secret mounted as a volume therefore needs `defaultMode: 0640` together with an `fsGroup` in the pod's security context, so the key is readable through its group without being readable by everyone. + ### Where the client tools are found TREK runs the tools by their absolute path. It does not search `PATH`. When `TREK_DB_PG_BIN_DIR` is unset, TREK looks in these directories, in order, and uses the first one that holds the tool: