fix: enforce production transport policy

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]>
This commit is contained in:
ekklesia
2026-07-26 17:03:52 -05:00
co-authored by Claude Opus 5
parent 7a0f624fc3
commit 6b6b77c105
34 changed files with 2035 additions and 52 deletions
+331
View File
@@ -0,0 +1,331 @@
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.
}
}
});
});
+303
View File
@@ -0,0 +1,303 @@
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).",
);
});
});
+2
View File
@@ -87,6 +87,8 @@ Data definitions
0 migrations · checksums valid
PostgreSQL
✓ Database TLS verified
TLS required with certificate and hostname verification.
○ Connection check skipped
DATABASE_URL is not configured.
○ Migration plan skipped
+59 -1
View File
@@ -206,6 +206,7 @@ describe("Ekklesia Doctor diagnostics", () => {
"modules.permissions",
"schemas.discovery",
"migrations.discovery",
"database.transport",
"postgresql.connection",
"postgresql.plan",
"identity.configuration",
@@ -255,9 +256,15 @@ describe("Ekklesia Doctor diagnostics", () => {
dependencies({ createMigrationDatabase, planMigrations }),
);
// Doctor's own read-only connection carries the same validated transport policy every other
// executable uses — it defaults to certificate-verified TLS, exactly like production.
expect(createMigrationDatabase).toHaveBeenCalledWith(
"postgresql://not-rendered.invalid/ekklesia",
{ connectionTimeoutMs: 10_000, operationTimeoutMs: 10_000 },
{
connectionTimeoutMs: 10_000,
operationTimeoutMs: 10_000,
transport: { mode: "verify-full" },
},
);
expect(planMigrations).toHaveBeenCalledOnce();
expect(check(report, "postgresql.connection")).toMatchObject({
@@ -702,6 +709,57 @@ describe("Ekklesia Doctor diagnostics", () => {
expect(report.result).toBe("not-ready");
});
it("passes database transport by default, reporting verified TLS without revealing any connection detail", async () => {
const report = await diagnoseEkklesia(
{ ...options("postgresql://admin:[email protected]:5432/ekklesia") },
dependencies(),
);
const transport = check(report, "database.transport");
expect(transport.status).toBe("pass");
expect(transport.summary).toBe("Database TLS verified");
const rendered = JSON.stringify(transport);
expect(rendered).not.toContain("hunter2");
expect(rendered).not.toContain("db.internal.example");
expect(rendered).not.toContain("postgresql://");
});
it("blocks readiness when a production deployment would reach PostgreSQL without verified TLS", async () => {
for (const [label, extra] of [
["explicit production plaintext", { databaseTransport: { mode: "disable" } }],
[
"connection-string downgrade",
{ databaseUrl: "postgresql://db.example.test/ekklesia?sslmode=disable" },
],
["malformed mode", { databaseTransport: { mode: "require" } }],
] as const) {
const report = await diagnoseEkklesia(
{ ...options("postgresql://db.example.test/ekklesia"), ...extra },
dependencies(),
);
const transport = check(report, "database.transport");
expect(transport.status, `expected ${label} to block readiness`).toBe("failure");
expect(transport.summary).toBe("Database transport unsafe");
expect(report.result).toBe("not-ready");
expect(doctorExitCode(report)).toBe(1);
}
});
it("passes development plaintext only when development is explicitly selected", async () => {
const report = await diagnoseEkklesia(
{
...options("postgresql://127.0.0.1:5432/ekklesia"),
databaseEnvironment: "development",
},
dependencies(),
);
const transport = check(report, "database.transport");
expect(transport.status).toBe("pass");
expect(transport.summary).toContain("disabled");
});
it("passes client-address configuration with direct mode when nothing is configured", async () => {
const report = await diagnoseEkklesia(options(), dependencies());
+120
View File
@@ -179,6 +179,126 @@ describe("Core identity configuration", () => {
expect(config.baseUrl).toBe("http://localhost:3000");
});
it("requires the base URL to be exactly one canonical origin, rejecting every non-origin component", () => {
for (const baseUrl of [
"https://id.example.test/", // a bare trailing slash is a path; `URL.origin` is slashless
"https://id.example.test/auth", // Better Auth is never mounted beneath a configurable path
"https://id.example.test?a=1",
"https://id.example.test#fragment",
"https://user:[email protected]",
"https://:[email protected]",
" https://id.example.test ",
"https://ID.EXAMPLE.TEST", // non-canonical hostname case
"https://id.example.test:443", // redundant default port
"http://id.example.test:80",
"ftp://id.example.test",
"id.example.test",
]) {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), baseUrl }, { environment: "production" });
} catch (error) {
captured = error;
}
expect(captured, `expected ${JSON.stringify(baseUrl)} to be rejected`).toMatchObject({
code: "BASE_URL_INVALID",
});
}
});
it("stores the base URL and trusted origins as one identical canonical origin representation", () => {
const config = createIdentityConfig(
{
...validInput(),
baseUrl: "https://id.example.test",
trustedOrigins: ["https://id.example.test", "https://dashboard.example.test:8443"],
},
{ environment: "production" },
);
expect(config.baseUrl).toBe("https://id.example.test");
expect(config.trustedOrigins).toEqual([
"https://id.example.test",
"https://dashboard.example.test:8443",
]);
});
it("rejects every loopback and unspecified-host spelling in production, for the base URL and trusted origins alike", () => {
// Canonical spellings the WHATWG parser preserves — these must be rejected as production
// policy failures, by the identical classifier on both fields.
const canonicalLoopback = [
"https://127.0.0.1",
"https://127.0.0.2", // the full 127.0.0.0/8 block, not just .1
"https://127.255.255.254",
"https://[::1]", // IPv6 loopback, compressed
"https://[::ffff:7f00:1]", // IPv4-mapped loopback, hexadecimal notation
"https://localhost",
"https://app.localhost", // RFC 6761 reserved namespace
"https://0.0.0.0",
"https://[::]", // IPv6 unspecified
"https://[::ffff:0:0]", // IPv4-mapped unspecified
];
for (const value of canonicalLoopback) {
let baseCaptured: unknown;
try {
createIdentityConfig({ ...validInput(), baseUrl: value }, { environment: "production" });
} catch (error) {
baseCaptured = error;
}
expect(baseCaptured, `expected base URL ${value} to be rejected`).toMatchObject({
code: "BASE_URL_LOOPBACK_IN_PRODUCTION",
});
let originCaptured: unknown;
try {
createIdentityConfig(
{ ...validInput(), trustedOrigins: [value] },
{ environment: "production" },
);
} catch (error) {
originCaptured = error;
}
expect(originCaptured, `expected trusted origin ${value} to be rejected`).toMatchObject({
code: "TRUSTED_ORIGIN_LOOPBACK_IN_PRODUCTION",
});
}
});
it("rejects non-canonical loopback spellings structurally, never as a misleading production-policy failure", () => {
// WHATWG canonicalization folds some of these into `127.0.0.1`; others simply are not the
// canonical origin text. Either way the honest answer is "this is not a canonical origin".
for (const baseUrl of [
"https://127.1",
"https://2130706433",
"https://0x7f000001",
"https://[0:0:0:0:0:0:0:1]", // expanded IPv6 loopback
"https://[::ffff:127.0.0.1]", // mixed IPv4-mapped notation
"https://LOCALHOST",
]) {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), baseUrl }, { environment: "production" });
} catch (error) {
captured = error;
}
expect(captured, `expected ${baseUrl} to be structurally rejected`).toMatchObject({
code: "BASE_URL_INVALID",
});
}
});
it("still accepts canonical loopback development origins", () => {
const config = createIdentityConfig(
{
...validInput(),
baseUrl: "http://localhost:3000",
trustedOrigins: ["http://localhost:3000", "http://127.0.0.1:5173"],
},
{ environment: "development" },
);
expect(config.baseUrl).toBe("http://localhost:3000");
expect(config.trustedOrigins).toEqual(["http://localhost:3000", "http://127.0.0.1:5173"]);
});
it("defaults publicSignupEnabled to false when entirely omitted", () => {
const config = createIdentityConfig(validInput(), { environment: "production" });
expect(config.publicSignupEnabled).toBe(false);