Every PostgreSQL connection this repository opened was plaintext, in every environment: no connection site set `ssl` at all, so credentials, session tokens, and row data crossed the network in the clear and nothing in configuration, startup, or `pnpm doctor` said so. The public identity URL boundary was also looser than it appeared. `core/src/database/transport.ts` is now the one typed policy. It has exactly two modes: `verify-full` (TLS required, certificate chain verified, and server identity verified against the configured host — the production default) and `disable` (the development/test default, refused outright in production). There is deliberately no encryption-only `require` mode, no chain-only `verify-ca`, and no `rejectUnauthorized: false` escape hatch anywhere in the configuration surface; every loose or aliased spelling is rejected in both environments, so a typo never quietly becomes a weaker mode. Production has no plaintext exception at all, not even for a loopback database — a connection string cannot prove the database is process-local. Verification is certificate *and* hostname. The policy supplies an explicit `checkServerIdentity` pinned to the host parsed from DATABASE_URL, because the pinned driver sets TLS `servername` only for non-IP hosts and Node performs no identity check when it is unset — so `rejectUnauthorized: true` alone accepts a certificate from any host the trusted CA ever signed when connecting by IP. Both halves are proven against a real TLS-enabled PostgreSQL, including that the same connection without the pinned callback succeeds. Every CA, certificate, and key is generated at test runtime and deleted afterwards. A DATABASE_URL may no longer carry its own TLS parameters. The pinned driver merges parsed connection-string values over explicitly passed options, so a `?sslmode=disable` in the URL would silently replace the policy's verified `ssl` object; that now fails with a stable code, reported by both `pnpm doctor` and the migration CLIs rather than as "failed unexpectedly". One shared environment reader keeps `process.env` out of Core's reusable constructors, and every executable that opens a connection resolves the policy identically: the API (validated before any pool, Better Auth instance, module runtime, or listener exists), both migration commands, the bootstrap CLI, and Doctor's own connection. Doctor reports it as a blocking failure, never a warning, naming only the effective mode. Separately, the identity base URL and every trusted origin must now be exactly one canonical origin — the WHATWG origin serialization must equal the supplied string — so a path, trailing slash, credentials, explicit default port, or non-canonical case is rejected rather than normalized into something that no longer matches what a browser sends. Production's loopback rejection now classifies the address instead of comparing against three literals, covering `.localhost`, all of 127.0.0.0/8, 0.0.0.0, `::`, expanded and IPv4-mapped forms. This is a configuration-shape guarantee only: it does not resolve DNS or prove reachability, and TLS protects the connection, not the exposure. Co-Authored-By: Claude Opus 5 <[email protected]>
332 lines
11 KiB
TypeScript
332 lines
11 KiB
TypeScript
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<void> {
|
|
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<void> {
|
|
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<string> {
|
|
const { stdout } = await run("docker", [...args]);
|
|
return stdout.trim();
|
|
}
|
|
|
|
async function startTlsPostgres(directory: string): Promise<number> {
|
|
// 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<void> {
|
|
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<typeof databaseTlsConnectionOptions>,
|
|
): 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://[email protected]:${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.
|
|
}
|
|
}
|
|
});
|
|
});
|