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:
co-authored by
Claude Opus 5
parent
7a0f624fc3
commit
6b6b77c105
+142
-20
@@ -18,12 +18,108 @@ export type IdentityConfigErrorCode =
|
||||
| "TRUSTED_ORIGINS_MISSING";
|
||||
|
||||
const MIN_SECRET_LENGTH = 32;
|
||||
const LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set([
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
"::1",
|
||||
"0.0.0.0",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Hostnames that are never a legitimate public production origin, matched exactly (after WHATWG
|
||||
* URL canonicalization, which already folds `127.1`, `2130706433`, and `0x7f000001` into
|
||||
* `127.0.0.1`, and lowercases every hostname).
|
||||
*
|
||||
* This is a purely *syntactic* classifier. It rejects literal and reserved loopback/unspecified
|
||||
* spellings; it performs no DNS resolution, so it cannot and does not prove that some arbitrary
|
||||
* public name will never resolve to a loopback address later. Network reachability remains the
|
||||
* deployment's own firewall/DNS responsibility.
|
||||
*/
|
||||
const IPV4_LOOPBACK_BLOCK = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/u;
|
||||
const UNSPECIFIED_HOSTNAMES: ReadonlySet<string> = new Set(["0.0.0.0", "[::]"]);
|
||||
const LITERAL_LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set(["localhost"]);
|
||||
|
||||
/** Expands a bracketed IPv6 `URL.hostname` into its 8 canonical 16-bit groups, or `undefined` when
|
||||
* the value is not a bracketed IPv6 literal. Handles `::` zero-compression and the mixed
|
||||
* `::ffff:a.b.c.d` notation the WHATWG parser preserves. */
|
||||
function expandIpv6Hostname(hostname: string): readonly number[] | undefined {
|
||||
if (!hostname.startsWith("[") || !hostname.endsWith("]")) {
|
||||
return undefined;
|
||||
}
|
||||
let body = hostname.slice(1, -1);
|
||||
// Mixed notation: translate a trailing dotted-quad into two hex groups.
|
||||
const dotted = /^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/u.exec(body);
|
||||
if (dotted) {
|
||||
const octets = [dotted[2], dotted[3], dotted[4], dotted[5]].map((part) => Number(part));
|
||||
if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
|
||||
return undefined;
|
||||
}
|
||||
const high = ((octets[0] as number) << 8) | (octets[1] as number);
|
||||
const low = ((octets[2] as number) << 8) | (octets[3] as number);
|
||||
body = `${dotted[1]}${high.toString(16)}:${low.toString(16)}`;
|
||||
}
|
||||
|
||||
const [head, tail, ...extra] = body.split("::");
|
||||
if (extra.length > 0) {
|
||||
return undefined;
|
||||
}
|
||||
const parseGroups = (value: string | undefined): number[] | undefined => {
|
||||
if (value === undefined || value === "") {
|
||||
return [];
|
||||
}
|
||||
const groups: number[] = [];
|
||||
for (const part of value.split(":")) {
|
||||
if (!/^[0-9a-f]{1,4}$/u.test(part)) {
|
||||
return undefined;
|
||||
}
|
||||
groups.push(Number.parseInt(part, 16));
|
||||
}
|
||||
return groups;
|
||||
};
|
||||
const leading = parseGroups(head);
|
||||
const trailing = tail === undefined ? [] : parseGroups(tail);
|
||||
if (!leading || !trailing) {
|
||||
return undefined;
|
||||
}
|
||||
if (tail === undefined) {
|
||||
return leading.length === 8 ? leading : undefined;
|
||||
}
|
||||
const missing = 8 - leading.length - trailing.length;
|
||||
if (missing < 0) {
|
||||
return undefined;
|
||||
}
|
||||
return [...leading, ...Array.from({ length: missing }, () => 0), ...trailing];
|
||||
}
|
||||
|
||||
/** Whether a canonicalized `URL.hostname` is a loopback or unspecified listen address in any
|
||||
* spelling this repository accepts — literal name, reserved `.localhost` namespace, the full IPv4
|
||||
* `127.0.0.0/8` block, IPv6 `::1` compressed or expanded, IPv6 `::` unspecified, and IPv4-mapped
|
||||
* IPv6 forms of both in mixed (`::ffff:127.0.0.1`) and hexadecimal (`::ffff:7f00:1`) notation. */
|
||||
function isLoopbackOrUnspecifiedHostname(hostname: string): boolean {
|
||||
const normalized = hostname.toLowerCase();
|
||||
if (LITERAL_LOOPBACK_HOSTNAMES.has(normalized) || UNSPECIFIED_HOSTNAMES.has(normalized)) {
|
||||
return true;
|
||||
}
|
||||
// RFC 6761 reserves the entire `.localhost` namespace for loopback.
|
||||
if (normalized.endsWith(".localhost")) {
|
||||
return true;
|
||||
}
|
||||
if (IPV4_LOOPBACK_BLOCK.test(normalized)) {
|
||||
return true;
|
||||
}
|
||||
const groups = expandIpv6Hostname(normalized);
|
||||
if (!groups) {
|
||||
return false;
|
||||
}
|
||||
const isAllZero = groups.every((group) => group === 0);
|
||||
// `::` (unspecified) and `::1` (loopback).
|
||||
if (isAllZero || (groups.slice(0, 7).every((group) => group === 0) && groups[7] === 1)) {
|
||||
return true;
|
||||
}
|
||||
// IPv4-mapped IPv6 (`::ffff:a.b.c.d`): classify the embedded IPv4 address.
|
||||
const isMapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff;
|
||||
if (isMapped) {
|
||||
const high = groups[6] as number;
|
||||
const low = groups[7] as number;
|
||||
const embedded = `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
|
||||
return IPV4_LOOPBACK_BLOCK.test(embedded) || embedded === "0.0.0.0";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const errorMessages: Readonly<Record<IdentityConfigErrorCode, string>> = Object.freeze({
|
||||
BASE_URL_INSECURE_IN_PRODUCTION: "The identity base URL must use https in production.",
|
||||
@@ -90,20 +186,38 @@ export interface CreateIdentityConfigOptions {
|
||||
readonly environment?: IdentityEnvironment;
|
||||
}
|
||||
|
||||
function isLoopbackHostname(hostname: string): boolean {
|
||||
return LOOPBACK_HOSTNAMES.has(hostname.toLowerCase());
|
||||
}
|
||||
|
||||
function parseAbsoluteHttpUrl(value: unknown): URL | undefined {
|
||||
/**
|
||||
* Parses one value that must be exactly a canonical absolute `http:`/`https:` **origin** — the
|
||||
* single representation both the identity base URL and every trusted origin use, so no component
|
||||
* of the platform can reinterpret the same deployment differently.
|
||||
*
|
||||
* Canonical means `URL.origin` must equal the configured string byte-for-byte. That one comparison
|
||||
* structurally rejects every non-origin component at once — credentials, any path (including a
|
||||
* bare trailing `/`, since `URL.origin` is slashless), a query, a fragment, surrounding
|
||||
* whitespace, an uppercase hostname, and a redundant default port — because the WHATWG parser
|
||||
* normalizes or preserves each of those in a way that no longer matches `origin`.
|
||||
*
|
||||
* Structural parsing is deliberately separate from environment policy: a caller distinguishes
|
||||
* "this is not an origin" from "this origin is not allowed in production" and reports the
|
||||
* structural code first, so an already-malformed URL is never mislabeled as a production-loopback
|
||||
* failure.
|
||||
*/
|
||||
function parseCanonicalHttpOrigin(value: unknown): URL | undefined {
|
||||
if (typeof value !== "string" || value.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
let url: URL;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "http:" || url.protocol === "https:" ? url : undefined;
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
return undefined;
|
||||
}
|
||||
// `URL.origin` carries no credentials, path, query, or fragment, and is already lowercased with
|
||||
// any default port elided — so requiring exact equality is the whole canonical-origin rule.
|
||||
return url.origin === value ? url : undefined;
|
||||
}
|
||||
|
||||
function validateSecret(secret: unknown): string {
|
||||
@@ -126,7 +240,11 @@ function validateBaseUrl(baseUrl: unknown, environment: IdentityEnvironment): st
|
||||
if (typeof baseUrl !== "string" || baseUrl.length === 0) {
|
||||
throw new IdentityConfigError("BASE_URL_MISSING");
|
||||
}
|
||||
const url = parseAbsoluteHttpUrl(baseUrl);
|
||||
// Structural validity first, in every environment: the base URL is the public origin of the
|
||||
// already-fixed `/api/auth` transport, and Ekklesia does not support mounting Better Auth
|
||||
// beneath a configurable URL path. A credentialed, pathed, queried, fragmented, whitespace-
|
||||
// padded, or otherwise non-canonical spelling is structurally invalid, never a policy failure.
|
||||
const url = parseCanonicalHttpOrigin(baseUrl);
|
||||
if (!url) {
|
||||
throw new IdentityConfigError("BASE_URL_INVALID");
|
||||
}
|
||||
@@ -134,11 +252,13 @@ function validateBaseUrl(baseUrl: unknown, environment: IdentityEnvironment): st
|
||||
if (url.protocol !== "https:") {
|
||||
throw new IdentityConfigError("BASE_URL_INSECURE_IN_PRODUCTION");
|
||||
}
|
||||
if (isLoopbackHostname(url.hostname)) {
|
||||
if (isLoopbackOrUnspecifiedHostname(url.hostname)) {
|
||||
throw new IdentityConfigError("BASE_URL_LOOPBACK_IN_PRODUCTION");
|
||||
}
|
||||
}
|
||||
return baseUrl;
|
||||
// Store the canonical origin — identical to what `validateTrustedOrigin` stores — so CORS,
|
||||
// Better Auth's own origin checks, and this base URL can never disagree about the same origin.
|
||||
return url.origin;
|
||||
}
|
||||
|
||||
function validateTrustedOrigin(origin: unknown, environment: IdentityEnvironment): string {
|
||||
@@ -152,19 +272,21 @@ function validateTrustedOrigin(origin: unknown, environment: IdentityEnvironment
|
||||
if (origin.includes("*") || origin.includes("?")) {
|
||||
throw new IdentityConfigError("TRUSTED_ORIGIN_WILDCARD_UNSUPPORTED");
|
||||
}
|
||||
const url = parseAbsoluteHttpUrl(origin);
|
||||
if (!url || url.origin !== origin) {
|
||||
const url = parseCanonicalHttpOrigin(origin);
|
||||
if (!url) {
|
||||
throw new IdentityConfigError("TRUSTED_ORIGIN_INVALID");
|
||||
}
|
||||
if (environment === "production") {
|
||||
if (url.protocol !== "https:") {
|
||||
throw new IdentityConfigError("TRUSTED_ORIGIN_INSECURE_IN_PRODUCTION");
|
||||
}
|
||||
if (isLoopbackHostname(url.hostname)) {
|
||||
// The identical classifier the base URL uses, so the two can never disagree about whether the
|
||||
// same host is a production-legal origin.
|
||||
if (isLoopbackOrUnspecifiedHostname(url.hostname)) {
|
||||
throw new IdentityConfigError("TRUSTED_ORIGIN_LOOPBACK_IN_PRODUCTION");
|
||||
}
|
||||
}
|
||||
return origin;
|
||||
return url.origin;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { drizzle, type NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
import { Pool, type PoolConfig } from "pg";
|
||||
import {
|
||||
type DatabaseTransportPolicy,
|
||||
databaseTlsConnectionOptions,
|
||||
} from "../database/transport.js";
|
||||
import { identityAdapterSchema } from "./schema.js";
|
||||
|
||||
export type IdentityDrizzleDatabase = NodePgDatabase<typeof identityAdapterSchema>;
|
||||
@@ -28,6 +32,10 @@ export interface IdentityDatabaseOptions {
|
||||
* indefinitely. `connectionTimeoutMs` alone only bounds establishing a connection — it does
|
||||
* nothing once a query is already running on one. */
|
||||
readonly operationTimeoutMs?: number;
|
||||
/** The validated transport policy (`core/src/database/transport.js`). Passed explicitly by
|
||||
* every production executable; omitted by single-domain unit/integration factories that use
|
||||
* the disposable loopback database, which keeps the pre-existing plaintext behavior. */
|
||||
readonly transport?: DatabaseTransportPolicy;
|
||||
}
|
||||
|
||||
export interface IdentityDatabaseHandle {
|
||||
@@ -81,8 +89,13 @@ export function createIdentityDrizzleDatabase(
|
||||
const validatedConnectionString = validateConnectionString(connectionString);
|
||||
const validatedConnectionTimeoutMs = validateTimeout(options.connectionTimeoutMs);
|
||||
const validatedOperationTimeoutMs = validateTimeout(options.operationTimeoutMs);
|
||||
const ssl =
|
||||
options.transport === undefined
|
||||
? undefined
|
||||
: databaseTlsConnectionOptions(validatedConnectionString, options.transport);
|
||||
const poolConfig: PoolConfig = {
|
||||
connectionString: validatedConnectionString,
|
||||
...(ssl === undefined ? {} : { ssl }),
|
||||
...(validatedConnectionTimeoutMs === undefined
|
||||
? {}
|
||||
: { connectionTimeoutMillis: validatedConnectionTimeoutMs }),
|
||||
|
||||
Reference in New Issue
Block a user