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]>
304 lines
11 KiB
TypeScript
304 lines
11 KiB
TypeScript
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:[email protected]: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:[email protected]: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).",
|
|
);
|
|
});
|
|
});
|