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
+27 -1
View File
@@ -1,3 +1,9 @@
import {
assertProductionDatabaseTransport,
type DatabaseTransportPolicy,
type DatabaseTransportPolicyInput,
createDatabaseTransportPolicy,
} from "@ekklesia/core/database";
import {
type CreateIdentityConfigOptions,
createIdentityConfig,
@@ -44,6 +50,8 @@ const defaultPort = 3000;
export interface ApiRuntimeConfig {
readonly clientAddress: ClientAddressConfig;
readonly databaseUrl: string;
/** The one validated PostgreSQL transport policy this runtime's single pool uses. */
readonly databaseTransport: DatabaseTransportPolicy;
readonly host: string;
readonly identity: IdentityConfig;
readonly port: number;
@@ -54,6 +62,9 @@ export interface ApiRuntimeConfigInput {
* trust unless explicitly configured. See `./client-address.js`. */
readonly clientAddress?: ClientAddressConfigInput;
readonly databaseUrl?: unknown;
/** Optional. Defaults to certificate-verified TLS in production and plaintext in development;
* production can never select plaintext. See `@ekklesia/core/database`'s transport policy. */
readonly databaseTransport?: DatabaseTransportPolicyInput;
readonly host?: unknown;
readonly identity: IdentityConfigInput;
readonly port?: unknown;
@@ -122,6 +133,21 @@ export function createApiRuntimeConfig(
options.environment === undefined ? {} : { environment: options.environment },
);
const clientAddress = createClientAddressConfig(input.clientAddress);
const environment = options.environment ?? "production";
const databaseTransport = createDatabaseTransportPolicy(input.databaseTransport, {
environment,
});
// Fails here — before `startApi` constructs a pool, Better Auth, the module runtime, or a
// listener — if a production deployment would connect without certificate-verified TLS, or if
// the URL carries TLS parameters that could override the policy.
assertProductionDatabaseTransport(databaseUrl, databaseTransport, environment);
return Object.freeze({ clientAddress, databaseUrl, host, identity, port });
return Object.freeze({
clientAddress,
databaseTransport,
databaseUrl,
host,
identity,
port,
});
}
+12
View File
@@ -260,6 +260,10 @@ export async function startApi(
const databaseHandle = createApiDatabase(config.databaseUrl, {
connectionTimeoutMs,
operationTimeoutMs,
// The one validated transport policy reaches this runtime's single physical pool here; the
// identity, authorization, and module Drizzle views are all typed views over that same pool,
// so TLS never introduces a second connection.
transport: config.databaseTransport,
});
let services: ModuleRuntimeServices;
@@ -425,6 +429,14 @@ function readConfigFromEnvironment(): {
environment: process.env.NODE_ENV === "development" ? "development" : "production",
input: {
...(clientAddress === undefined ? {} : { clientAddress }),
databaseTransport: {
...(process.env.EKKLESIA_DATABASE_CA === undefined
? {}
: { certificateAuthority: process.env.EKKLESIA_DATABASE_CA }),
...(process.env.EKKLESIA_DATABASE_TLS_MODE === undefined
? {}
: { mode: process.env.EKKLESIA_DATABASE_TLS_MODE }),
},
databaseUrl: process.env.DATABASE_URL,
host: process.env.EKKLESIA_API_HOST,
identity: {
+18 -9
View File
@@ -347,14 +347,20 @@ async function startConfiguredApi(
options: StartConfiguredApiOptions = {},
): Promise<RunningApi> {
const publicSignupEnabled = options.publicSignupEnabled ?? true;
// Production configuration refuses to enable public signup at all until durable abuse controls
// exist (`PUBLIC_SIGNUP_UNSUPPORTED_IN_PRODUCTION`, `core/src/identity/config.ts`), so a scenario
// that creates accounts over HTTP must validate its configuration as development — the explicit,
// intended way to opt in. This changes only Ekklesia's own config-validation strictness:
// `environment` never reaches Better Auth, and this harness keeps the identical https,
// non-loopback base URL and trusted origins either way, so the production-equivalent origin/CSRF
// behavior ADR 0012 established is exercised exactly the same in both cases.
const environment = publicSignupEnabled ? "development" : "production";
// This harness explicitly selects development configuration, for two independent reasons that
// both apply to every scenario in this suite:
//
// 1. It connects to the disposable *plaintext* loopback PostgreSQL. Production configuration
// requires certificate-verified TLS with no exception, so a plaintext test database can
// only be used by a deployment that has explicitly declared itself non-production.
// 2. Scenarios that create accounts over HTTP need public signup, which production refuses to
// enable at all until durable abuse controls exist.
//
// This changes only Ekklesia's own configuration-validation strictness — `environment` never
// reaches Better Auth — and the harness keeps the identical https, non-loopback base URL and
// trusted origins regardless, so the production-equivalent origin/CSRF behavior ADR 0012
// established is exercised exactly the same either way.
const environment = "development" as const;
const config = createApiRuntimeConfig(
{
...(options.clientAddress === undefined ? {} : { clientAddress: options.clientAddress }),
@@ -2255,7 +2261,10 @@ describe.sequential("live API — Node header/request timeouts and client errors
},
port: 0,
},
{ environment: "production" },
// Development configuration, for the same reason `startConfiguredApi` documents: this suite
// connects to the disposable plaintext loopback PostgreSQL, which production configuration
// never permits. Nothing about the transport-level timeout behavior under test depends on it.
{ environment: "development" },
);
// Deliberately tiny, test-only timeouts — production composition (server.ts's `main`) never
// sets this override — so a real timeout is observed deterministically in well under a second
+131
View File
@@ -22,6 +22,8 @@ describe("API runtime configuration", () => {
expect(config).toEqual({
clientAddress: { mode: "direct" },
// Production defaults to certificate-verified TLS with no configuration at all.
databaseTransport: { mode: "verify-full" },
databaseUrl: validInput().databaseUrl,
host: "127.0.0.1",
identity: {
@@ -185,6 +187,135 @@ describe("API runtime configuration", () => {
});
});
describe("PostgreSQL transport policy", () => {
it("defaults to certificate-verified TLS in production and plaintext in development", () => {
expect(createApiRuntimeConfig(validInput()).databaseTransport).toEqual({
mode: "verify-full",
});
expect(
createApiRuntimeConfig(
{
...validInput(),
identity: {
baseUrl: "http://localhost:3000",
secret: validSecret,
trustedOrigins: ["http://localhost:3000"],
},
},
{ environment: "development" },
).databaseTransport,
).toEqual({ mode: "disable" });
});
it("refuses a production configuration that disables TLS", () => {
let captured: unknown;
try {
createApiRuntimeConfig(
{ ...validInput(), databaseTransport: { mode: "disable" } },
{ environment: "production" },
);
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "DATABASE_TLS_REQUIRED_IN_PRODUCTION" });
});
it("rejects a malformed or loosely spelled TLS mode in every environment, without coercion", () => {
for (const mode of [
"VERIFY-FULL",
" verify-full ",
"require",
"verify-ca",
"prefer",
"no-verify",
"true",
true,
1,
"",
]) {
for (const environment of ["production", "development"] as const) {
let captured: unknown;
try {
createApiRuntimeConfig(
{
...validInput(),
databaseTransport: { mode },
...(environment === "development"
? {
identity: {
baseUrl: "http://localhost:3000",
secret: validSecret,
trustedOrigins: ["http://localhost:3000"],
},
}
: {}),
},
{ environment },
);
} catch (error) {
captured = error;
}
expect(captured, `expected mode ${JSON.stringify(mode)} to be rejected`).toMatchObject({
code: "DATABASE_TLS_MODE_INVALID",
});
}
}
});
it("rejects a database URL carrying its own TLS parameters, which the pinned driver would let override the policy", () => {
for (const parameter of [
"sslmode=disable",
"sslmode=require",
"sslmode=verify-full",
"ssl=true",
"sslrootcert=/tmp/ca.crt",
"sslcert=/tmp/c.crt",
"sslkey=/tmp/c.key",
"uselibpqcompat=true",
]) {
let captured: unknown;
try {
createApiRuntimeConfig(
{
...validInput(),
databaseUrl: `postgresql://ekklesia:[email protected]:5432/ekklesia?${parameter}`,
},
{ environment: "production" },
);
} catch (error) {
captured = error;
}
expect(captured, `expected ${parameter} to be rejected`).toMatchObject({
code: "DATABASE_TLS_CONNECTION_STRING_CONFLICT",
});
}
});
it("never leaks the database URL, credentials, host, or CA material through a transport error", () => {
let captured: unknown;
try {
createApiRuntimeConfig(
{
...validInput(),
databaseTransport: { certificateAuthority: "-----BEGIN CERTIFICATE-----SECRET" },
databaseUrl:
"postgresql://admin:[email protected]:5432/ekklesia?sslmode=disable",
},
{ environment: "production" },
);
} catch (error) {
captured = error;
}
const publicText = `${String(captured)}\n${
captured instanceof Error ? (captured.stack ?? "") : ""
}\n${JSON.stringify(captured)}`;
expect(publicText).not.toContain("hunter2");
expect(publicText).not.toContain("db.internal.example");
expect(publicText).not.toContain("SECRET");
expect(publicText).not.toContain("sslmode");
});
});
it("never leaks the database URL, secret, or trusted origins through a thrown error", () => {
const hostileUrl = "postgresql://admin:[email protected]:5432/ekklesia";
let captured: unknown;
+53
View File
@@ -460,6 +460,59 @@ describe("Ekklesia API shutdown lifecycle", () => {
expect(poolEnd).not.toHaveBeenCalled();
});
it("refuses an unsafe production database transport before any pool, Better Auth instance, module runtime, or server exists", async () => {
const poolEnd = vi.fn().mockResolvedValue(undefined);
poolConstructor.mockImplementation(function fakePool() {
return { end: poolEnd, on: vi.fn() };
});
betterAuthMock.mockReturnValue({ api: { getSession: vi.fn() }, handler: vi.fn() });
mockSuccessfulServe();
// Both an explicit production plaintext selection and a URL that would silently downgrade the
// policy are rejected in `createApiRuntimeConfig` — the same boundary the executable entry
// point calls before `startApi` — so no runtime resource is ever constructed to leak.
for (const [label, input] of [
[
"explicit production plaintext",
{
databaseTransport: { mode: "disable" },
databaseUrl: "postgresql://ekklesia:[email protected]:5432/ekklesia",
},
],
[
"connection-string TLS downgrade",
{
databaseUrl:
"postgresql://ekklesia:[email protected]:5432/ekklesia?sslmode=disable",
},
],
] as const) {
let captured: unknown;
try {
createApiRuntimeConfig(
{
host: "127.0.0.1",
identity: {
baseUrl: "https://identity.example.test",
secret: "correct-horse-battery-staple-0123456789",
trustedOrigins: ["https://identity.example.test"],
},
port: 0,
...input,
},
{ environment: "production" },
);
} catch (error) {
captured = error;
}
expect(captured, `expected ${label} to be rejected`).toBeInstanceOf(Error);
expect(poolConstructor).not.toHaveBeenCalled();
expect(betterAuthMock).not.toHaveBeenCalled();
expect(serveMock).not.toHaveBeenCalled();
expect(poolEnd).not.toHaveBeenCalled();
}
});
it("closes an already-created database pool when the server fails to bind its listen address", async () => {
const poolEnd = vi.fn().mockResolvedValue(undefined);
poolConstructor.mockImplementation(function fakePool() {