import tls from "node:tls"; import { describe, expect, it, vi } from "vitest"; import { reportMigrationCommandError } from "../src/cli/migration-command-errors.js"; import { assertNoConnectionStringTlsParameters, assertProductionDatabaseTransport, createDatabaseTransportPolicy, databaseHostFromUrl, DatabaseTransportError, databaseTlsConnectionOptions, describeDatabaseTransport, } from "../src/database/transport.js"; const productionUrl = "postgresql://ekklesia:secret@db.example.test:5432/ekklesia"; describe("createDatabaseTransportPolicy", () => { it("defaults to certificate-verified TLS in production and plaintext in development", () => { expect(createDatabaseTransportPolicy()).toEqual({ mode: "verify-full" }); expect(createDatabaseTransportPolicy({}, { environment: "production" })).toEqual({ mode: "verify-full", }); expect(createDatabaseTransportPolicy({}, { environment: "development" })).toEqual({ mode: "disable", }); }); it("refuses plaintext in production", () => { let captured: unknown; try { createDatabaseTransportPolicy({ mode: "disable" }, { environment: "production" }); } catch (error) { captured = error; } expect(captured).toBeInstanceOf(DatabaseTransportError); expect(captured).toMatchObject({ code: "DATABASE_TLS_REQUIRED_IN_PRODUCTION" }); }); it("rejects every loose, aliased, or coercible mode spelling in both environments", () => { for (const mode of [ "VERIFY-FULL", "Verify-Full", " verify-full", "verify-full ", "require", // encryption-only: deliberately unsupported "verify-ca", // no hostname verification: deliberately unsupported "prefer", "no-verify", "allow", "true", true, false, 1, 0, "", null, ]) { for (const environment of ["production", "development"] as const) { let captured: unknown; try { createDatabaseTransportPolicy({ mode }, { environment }); } catch (error) { captured = error; } expect(captured, `expected ${JSON.stringify(mode)} to be rejected`).toMatchObject({ code: "DATABASE_TLS_MODE_INVALID", }); } } }); it("accepts an optional private CA and rejects an empty one", () => { expect( createDatabaseTransportPolicy({ certificateAuthority: "-----BEGIN CERTIFICATE-----" }) .certificateAuthority, ).toBe("-----BEGIN CERTIFICATE-----"); for (const certificateAuthority of ["", " ", 42]) { let captured: unknown; try { createDatabaseTransportPolicy({ certificateAuthority }); } catch (error) { captured = error; } expect(captured).toBeInstanceOf(DatabaseTransportError); } }); it("never carries the offending mode or CA material in the thrown error", () => { let captured: unknown; try { createDatabaseTransportPolicy({ certificateAuthority: "SUPER-SECRET-CA", mode: "sslmode=x" }); } catch (error) { captured = error; } const publicText = `${String(captured)}\n${ captured instanceof Error ? (captured.stack ?? "") : "" }\n${JSON.stringify(captured)}`; expect(publicText).not.toContain("SUPER-SECRET-CA"); expect(publicText).not.toContain("sslmode=x"); }); }); describe("assertNoConnectionStringTlsParameters", () => { it("rejects every TLS parameter the pinned connection-string parser recognizes", () => { for (const parameter of [ "ssl=true", "sslmode=disable", "sslmode=require", "sslmode=verify-full", "sslcert=/tmp/c.crt", "sslkey=/tmp/c.key", "sslrootcert=/tmp/ca.crt", "sslpassword=x", "sslnegotiation=direct", "uselibpqcompat=true", "SSLMODE=disable", // case-insensitive ]) { let captured: unknown; try { assertNoConnectionStringTlsParameters(`${productionUrl}?${parameter}`); } catch (error) { captured = error; } expect(captured, `expected ${parameter} to be rejected`).toMatchObject({ code: "DATABASE_TLS_CONNECTION_STRING_CONFLICT", }); } }); it("allows an unrelated parameter", () => { expect(() => assertNoConnectionStringTlsParameters(`${productionUrl}?application_name=ekklesia`), ).not.toThrow(); }); it("rejects a non-PostgreSQL or malformed URL", () => { for (const url of ["", "not-a-url", "mysql://db.example.test/x", "http://db.example.test"]) { let captured: unknown; try { assertNoConnectionStringTlsParameters(url); } catch (error) { captured = error; } expect(captured).toMatchObject({ code: "DATABASE_URL_INVALID" }); } }); }); describe("databaseTlsConnectionOptions", () => { it("produces no TLS options at all when the policy disables TLS", () => { expect( databaseTlsConnectionOptions("postgresql://127.0.0.1:5432/ekklesia", { mode: "disable" }), ).toBe(false); }); it("enables chain verification and pins hostname verification to the configured host", () => { const options = databaseTlsConnectionOptions(productionUrl, { mode: "verify-full" }); expect(options).not.toBe(false); if (options === false) { throw new Error("expected TLS options"); } // There is no configuration path that produces `rejectUnauthorized: false`. expect(options.rejectUnauthorized).toBe(true); expect(typeof options.checkServerIdentity).toBe("function"); expect(options.ca).toBeUndefined(); }); it("checks the certificate against the configured host, not against whatever SNI the driver set", () => { // The pinned driver sets `servername` only for non-IP hosts, and Node skips identity checking // entirely when it is unset — so the policy must pin the host itself. This asserts the // supplied callback ignores the passed servername and uses the configured host. const options = databaseTlsConnectionOptions(productionUrl, { mode: "verify-full" }); if (options === false || !options.checkServerIdentity) { throw new Error("expected a checkServerIdentity callback"); } const spy = vi.spyOn(tls, "checkServerIdentity").mockReturnValue(undefined); try { options.checkServerIdentity("attacker-supplied.example", {} as tls.PeerCertificate); expect(spy).toHaveBeenCalledWith("db.example.test", expect.anything()); } finally { spy.mockRestore(); } }); it("uses the bare address for an IPv6 host so identity checking sees a usable value", () => { expect(databaseHostFromUrl("postgresql://[2001:db8::1]:5432/ekklesia")).toBe("2001:db8::1"); expect(databaseHostFromUrl("postgresql://db.example.test:5432/ekklesia")).toBe( "db.example.test", ); }); it("passes an explicit private CA through unchanged", () => { const certificateAuthority = "-----BEGIN CERTIFICATE-----\nprivate-ca\n-----END CERTIFICATE-----"; const options = databaseTlsConnectionOptions(productionUrl, { certificateAuthority, mode: "verify-full", }); if (options === false) { throw new Error("expected TLS options"); } expect(options.ca).toBe(certificateAuthority); }); it("refuses to build options for a URL carrying its own TLS parameters", () => { let captured: unknown; try { databaseTlsConnectionOptions(`${productionUrl}?sslmode=disable`, { mode: "verify-full" }); } catch (error) { captured = error; } expect(captured).toMatchObject({ code: "DATABASE_TLS_CONNECTION_STRING_CONFLICT" }); }); }); describe("assertProductionDatabaseTransport", () => { it("permits verified TLS in production and any validated policy in development", () => { expect(() => assertProductionDatabaseTransport(productionUrl, { mode: "verify-full" }, "production"), ).not.toThrow(); expect(() => assertProductionDatabaseTransport( "postgresql://127.0.0.1:5432/ekklesia", { mode: "disable" }, "development", ), ).not.toThrow(); }); it("refuses production plaintext, including for a loopback database — there is no production exception", () => { for (const url of [ productionUrl, "postgresql://127.0.0.1:5432/ekklesia", "postgresql://localhost:5432/ekklesia", "postgresql://[::1]:5432/ekklesia", ]) { let captured: unknown; try { assertProductionDatabaseTransport(url, { mode: "disable" }, "production"); } catch (error) { captured = error; } expect(captured, `expected production plaintext to ${url} to be refused`).toMatchObject({ code: "DATABASE_TLS_REQUIRED_IN_PRODUCTION", }); } }); }); describe("migration CLI transport reporting", () => { it("reports the stable transport code instead of a generic 'failed unexpectedly', and leaks nothing", () => { const captured: string[] = []; const errorSpy = vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { captured.push(args.map(String).join(" ")); }); try { for (const url of [ `${productionUrl}?sslmode=disable`, "postgresql://ekklesia:hunter2@db.example.test:5432/ekklesia?ssl=true", ]) { try { databaseTlsConnectionOptions(url, { mode: "verify-full" }); } catch (error) { reportMigrationCommandError(error); } } try { createDatabaseTransportPolicy({ mode: "disable" }, { environment: "production" }); } catch (error) { reportMigrationCommandError(error); } } finally { errorSpy.mockRestore(); } const output = captured.join("\n"); expect(output).toContain("[DATABASE_TLS_CONNECTION_STRING_CONFLICT]"); expect(output).toContain("[DATABASE_TLS_REQUIRED_IN_PRODUCTION]"); expect(output).not.toContain("failed unexpectedly"); // The connection string, its credentials, and its host never reach operator output. for (const secret of ["hunter2", "db.example.test", "secret", "sslmode=disable"]) { expect(output).not.toContain(secret); } }); }); describe("describeDatabaseTransport", () => { it("describes the effective mode without revealing any connection detail", () => { expect(describeDatabaseTransport({ mode: "verify-full" })).toBe( "TLS required with certificate and hostname verification.", ); expect( describeDatabaseTransport({ certificateAuthority: "SECRET-CA", mode: "verify-full" }), ).toBe( "TLS required with certificate and hostname verification (explicit private CA supplied).", ); expect( describeDatabaseTransport({ certificateAuthority: "SECRET-CA", mode: "verify-full" }), ).not.toContain("SECRET-CA"); expect(describeDatabaseTransport({ mode: "disable" })).toBe( "TLS disabled (development/test plaintext).", ); }); });