import { execFile } from "node:child_process"; import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { Client } from "pg"; import { afterAll, describe, expect, it } from "vitest"; import { databaseTlsConnectionOptions } from "../src/database/transport.js"; const run = promisify(execFile); /** * Real TLS proof for the production transport policy, exercised through the pinned `pg` client * against a disposable, TLS-enabled PostgreSQL container. * * Every certificate, key, and CA used here is generated at test runtime into an isolated temporary * directory and deleted in `afterAll` — no private-key material is committed to this repository. * The container, its name, and its published loopback port are likewise disposable and removed in * `afterAll` even when an assertion fails. */ const containerName = `ekklesia-database-tls-${process.pid}`; let certificateDirectory: string | undefined; let containerStarted = false; let boundPort: number | undefined; class TlsHarnessError extends Error { constructor(message: string) { super(message); this.name = "TlsHarnessError"; this.stack = `${this.name}: ${this.message}`; } } async function openssl(args: readonly string[], cwd: string): Promise { try { await run("openssl", [...args], { cwd }); } catch { // Never surface openssl's own stderr: it can echo paths from the harness environment. throw new TlsHarnessError("The disposable TLS material could not be generated."); } } /** Generates a private CA, a server certificate signed by it whose only SAN is `DNS:localhost`, * and an unrelated second CA. The deliberately narrow SAN is what makes the hostname-mismatch * assertion below meaningful: reaching the very same server through `127.0.0.1` must fail. */ async function generateCertificates(directory: string): Promise { await openssl( [ "req", "-new", "-x509", "-days", "1", "-nodes", "-out", "ca.crt", "-keyout", "ca.key", "-subj", "/CN=Ekklesia Disposable Test CA", ], directory, ); await openssl( [ "req", "-new", "-nodes", "-out", "server.csr", "-keyout", "server.key", "-subj", "/CN=localhost", ], directory, ); await writeFile(path.join(directory, "san.cnf"), "subjectAltName=DNS:localhost\n"); await openssl( [ "x509", "-req", "-in", "server.csr", "-CA", "ca.crt", "-CAkey", "ca.key", "-CAcreateserial", "-out", "server.crt", "-days", "1", "-extfile", "san.cnf", ], directory, ); await openssl( [ "req", "-new", "-x509", "-days", "1", "-nodes", "-out", "other-ca.crt", "-keyout", "other-ca.key", "-subj", "/CN=Unrelated Test CA", ], directory, ); } async function docker(args: readonly string[]): Promise { const { stdout } = await run("docker", [...args]); return stdout.trim(); } async function startTlsPostgres(directory: string): Promise { // The certificate/key are copied *inside* the container and re-owned before PostgreSQL starts: // PostgreSQL refuses a key file that is not owned by the database user or root, and a bind- // mounted host file keeps the host's ownership. await docker([ "run", "-d", "--name", containerName, "-e", "POSTGRES_DB=ekklesia_tls", "-e", "POSTGRES_USER=ekklesia_tls", "-e", "POSTGRES_PASSWORD=ekklesia_tls", "-v", `${directory}:/certs-src:ro`, "-p", "127.0.0.1:0:5432", "--entrypoint", "/bin/sh", "postgres:18.4-alpine3.24", "-c", "mkdir -p /tls && cp /certs-src/server.crt /certs-src/server.key /tls/ && " + "chown postgres:postgres /tls/server.* && chmod 600 /tls/server.key && " + "exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/tls/server.crt " + "-c ssl_key_file=/tls/server.key", ]); containerStarted = true; const published = await docker(["port", containerName, "5432"]); const match = /^127\.0\.0\.1:(\d+)$/u.exec(published.split("\n")[0]?.trim() ?? ""); if (!match) { throw new TlsHarnessError( "The disposable TLS PostgreSQL port is not bound safely to loopback.", ); } return Number(match[1]); } /** Bounded readiness polling — never an arbitrary sleep. Resolves once the server accepts a TLS * connection, or fails after the deadline. */ async function waitForTlsReadiness(port: number, ca: string): Promise { const deadline = Date.now() + 60_000; let lastError: unknown; while (Date.now() < deadline) { const client = new Client({ connectionTimeoutMillis: 3_000, database: "ekklesia_tls", host: "localhost", password: "ekklesia_tls", port, ssl: { ca, rejectUnauthorized: true }, user: "ekklesia_tls", }); try { await client.connect(); await client.end(); return; } catch (error) { lastError = error; try { await client.end(); } catch { // The failed client is already unusable; nothing to clean up beyond this. } await new Promise((resolve) => setTimeout(resolve, 250)); } } throw new TlsHarnessError( `The disposable TLS PostgreSQL did not become ready: ${String(lastError)}`, ); } async function connectWith( host: string, port: number, ssl: ReturnType, ): Promise<{ encrypted: boolean }> { const client = new Client({ connectionTimeoutMillis: 5_000, database: "ekklesia_tls", host, password: "ekklesia_tls", port, ...(ssl === false ? {} : { ssl }), user: "ekklesia_tls", }); try { await client.connect(); const result = await client.query<{ encrypted: boolean }>( "SELECT ssl AS encrypted FROM pg_stat_ssl WHERE pid = pg_backend_pid()", ); return { encrypted: result.rows[0]?.encrypted === true }; } finally { try { await client.end(); } catch { // Closing an already-failed client is not itself a test failure. } } } afterAll(async () => { if (containerStarted) { await docker(["rm", "-f", containerName]).catch(() => undefined); } if (certificateDirectory) { // Removes the generated CA, server certificate, and every private key. await rm(certificateDirectory, { force: true, recursive: true }).catch(() => undefined); } }); describe.sequential("production PostgreSQL TLS policy against a real TLS endpoint", () => { it("starts a disposable TLS-enabled PostgreSQL with runtime-generated certificates", async () => { certificateDirectory = await mkdtemp(path.join(tmpdir(), "ekklesia-tls-")); await generateCertificates(certificateDirectory); boundPort = await startTlsPostgres(certificateDirectory); const ca = await readFile(path.join(certificateDirectory, "ca.crt"), "utf8"); await waitForTlsReadiness(boundPort, ca); expect(boundPort).toBeGreaterThan(0); }); it("connects successfully, and encrypted, when the certificate is trusted and its identity matches the host", async () => { const ca = await readFile(path.join(certificateDirectory as string, "ca.crt"), "utf8"); const ssl = databaseTlsConnectionOptions( `postgresql://ekklesia_tls@localhost:${boundPort}/ekklesia_tls`, { certificateAuthority: ca, mode: "verify-full" }, ); const { encrypted } = await connectWith("localhost", boundPort as number, ssl); expect(encrypted).toBe(true); }); it("refuses a certificate that does not chain to the configured CA", async () => { const otherCa = await readFile( path.join(certificateDirectory as string, "other-ca.crt"), "utf8", ); const ssl = databaseTlsConnectionOptions( `postgresql://ekklesia_tls@localhost:${boundPort}/ekklesia_tls`, { certificateAuthority: otherCa, mode: "verify-full" }, ); await expect(connectWith("localhost", boundPort as number, ssl)).rejects.toMatchObject({ code: "UNABLE_TO_VERIFY_LEAF_SIGNATURE", }); }); it("refuses a trusted certificate whose identity does not match the host being connected to", async () => { // The server certificate's only SAN is `DNS:localhost`, so reaching the identical server via // its IP address is a genuine hostname mismatch. This is the case the pinned driver does *not* // catch on its own: `pg` sets `servername` only for non-IP hosts, and Node performs no identity // check when it is unset, so `rejectUnauthorized: true` alone would accept this connection. const ca = await readFile(path.join(certificateDirectory as string, "ca.crt"), "utf8"); const ssl = databaseTlsConnectionOptions( `postgresql://ekklesia_tls@127.0.0.1:${boundPort}/ekklesia_tls`, { certificateAuthority: ca, mode: "verify-full" }, ); await expect(connectWith("127.0.0.1", boundPort as number, ssl)).rejects.toMatchObject({ code: "ERR_TLS_CERT_ALTNAME_INVALID", }); }); it("proves the gap the policy closes: chain-only verification would accept that same mismatch", async () => { const ca = await readFile(path.join(certificateDirectory as string, "ca.crt"), "utf8"); // Exactly what `ssl: { ca, rejectUnauthorized: true }` alone does — no pinned // `checkServerIdentity`. It connects, which is why the policy supplies one. const { encrypted } = await connectWith("127.0.0.1", boundPort as number, { ca, rejectUnauthorized: true, }); expect(encrypted).toBe(true); }); it("cannot satisfy verify-full against a plaintext-only PostgreSQL endpoint", async () => { // The disposable plaintext PostgreSQL the rest of the integration suite uses. const plaintextUrl = process.env.EKKLESIA_MIGRATION_TEST_DATABASE_URL; if (typeof plaintextUrl !== "string" || plaintextUrl.trim() === "") { throw new TlsHarnessError("The plaintext integration database is not configured."); } const parsed = new URL(plaintextUrl); const ca = await readFile(path.join(certificateDirectory as string, "ca.crt"), "utf8"); const ssl = databaseTlsConnectionOptions(plaintextUrl, { certificateAuthority: ca, mode: "verify-full", }); const client = new Client({ connectionTimeoutMillis: 5_000, database: parsed.pathname.slice(1), host: parsed.hostname, password: decodeURIComponent(parsed.password), port: Number(parsed.port), ...(ssl === false ? {} : { ssl }), user: decodeURIComponent(parsed.username), }); try { await expect(client.connect()).rejects.toBeTruthy(); } finally { try { await client.end(); } catch { // Already unusable. } } }); });