Files
Ekklesia/core/tests/identity-config.test.ts
T
ekklesiaandClaude Opus 5 6b6b77c105 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]>
2026-07-26 17:03:52 -05:00

422 lines
15 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { createIdentityConfig, IdentityConfigError } from "../src/identity/config.js";
const validSecret = "correct-horse-battery-staple-0123456789";
const validBaseUrl = "https://identity.example.test";
const validTrustedOrigins = ["https://identity.example.test", "https://dashboard.example.test"];
function validInput() {
return { baseUrl: validBaseUrl, secret: validSecret, trustedOrigins: validTrustedOrigins };
}
/** The loopback/`http` shape only `{ environment: "development" }` accepts — used by the tests that
* exercise development-only behavior (such as explicitly enabling public signup) so they never
* accidentally pass through production validation. */
function developmentInput() {
return {
baseUrl: "http://localhost:3000",
secret: validSecret,
trustedOrigins: ["http://localhost:3000"],
};
}
describe("Core identity configuration", () => {
it("accepts a valid secret, base URL, and trusted origins", () => {
const config = createIdentityConfig(validInput(), { environment: "production" });
expect(config).toEqual({
baseUrl: validBaseUrl,
publicSignupEnabled: false,
secret: validSecret,
trustedOrigins: validTrustedOrigins,
});
expect(Object.isFrozen(config)).toBe(true);
expect(Object.isFrozen(config.trustedOrigins)).toBe(true);
});
it("rejects a missing secret", () => {
expect(() =>
createIdentityConfig({ ...validInput(), secret: undefined }, { environment: "production" }),
).toThrow(IdentityConfigError);
try {
createIdentityConfig({ ...validInput(), secret: undefined });
} catch (error) {
expect(error).toMatchObject({ code: "SECRET_MISSING" });
}
});
it("rejects a secret shorter than 32 characters", () => {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), secret: "x".repeat(31) });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "SECRET_TOO_SHORT" });
});
it("accepts a secret of exactly 32 characters", () => {
const secret = "aB1cD2eF3gH4iJ5kL6mN7oP8qR9sT0uV";
expect(secret).toHaveLength(32);
const config = createIdentityConfig({ ...validInput(), secret });
expect(config.secret).toBe(secret);
});
it("rejects a degenerate single-character-repeated secret", () => {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), secret: "a".repeat(40) });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "SECRET_LOW_ENTROPY" });
});
it("rejects an invalid base URL", () => {
for (const baseUrl of [undefined, "", "not-a-url", "ftp://example.test", "example.test"]) {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), baseUrl });
} catch (error) {
captured = error;
}
expect(captured).toBeInstanceOf(IdentityConfigError);
}
});
it("rejects missing trusted origins", () => {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), trustedOrigins: undefined });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "TRUSTED_ORIGINS_MISSING" });
});
it("rejects an empty trusted origins array", () => {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), trustedOrigins: [] });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "TRUSTED_ORIGINS_EMPTY" });
});
it("rejects a trusted origin containing a path, query, or fragment", () => {
for (const origin of [
"https://example.test/",
"https://example.test/path",
"https://example.test#fragment",
]) {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), trustedOrigins: [origin] });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "TRUSTED_ORIGIN_INVALID" });
}
});
it("rejects wildcard trusted origins", () => {
for (const origin of ["https://*.example.test", "https://app?.example.test"]) {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), trustedOrigins: [origin] });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "TRUSTED_ORIGIN_WILDCARD_UNSUPPORTED" });
}
});
it("rejects insecure http origins and loopback hosts in production", () => {
let httpError: unknown;
try {
createIdentityConfig(
{ ...validInput(), trustedOrigins: ["http://identity.example.test"] },
{ environment: "production" },
);
} catch (error) {
httpError = error;
}
expect(httpError).toMatchObject({ code: "TRUSTED_ORIGIN_INSECURE_IN_PRODUCTION" });
let loopbackError: unknown;
try {
createIdentityConfig(
{ ...validInput(), baseUrl: "https://localhost", trustedOrigins: ["https://localhost"] },
{ environment: "production" },
);
} catch (error) {
loopbackError = error;
}
expect(loopbackError).toMatchObject({ code: "BASE_URL_LOOPBACK_IN_PRODUCTION" });
});
it("defaults to production validation when environment is not specified", () => {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), baseUrl: "http://identity.example.test" });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "BASE_URL_INSECURE_IN_PRODUCTION" });
});
it("explicitly allows local development origins only when environment is development", () => {
const config = createIdentityConfig(
{
baseUrl: "http://localhost:3000",
secret: validSecret,
trustedOrigins: ["http://localhost:3000"],
},
{ environment: "development" },
);
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);
});
it("accepts an explicit boolean publicSignupEnabled in development", () => {
expect(
createIdentityConfig(
{ ...developmentInput(), publicSignupEnabled: true },
{ environment: "development" },
).publicSignupEnabled,
).toBe(true);
expect(
createIdentityConfig(
{ ...developmentInput(), publicSignupEnabled: false },
{ environment: "development" },
).publicSignupEnabled,
).toBe(false);
});
it('accepts the exact strings "true"/"false" in development (environment variables are always strings)', () => {
expect(
createIdentityConfig(
{ ...developmentInput(), publicSignupEnabled: "true" },
{ environment: "development" },
).publicSignupEnabled,
).toBe(true);
expect(
createIdentityConfig(
{ ...developmentInput(), publicSignupEnabled: "false" },
{ environment: "development" },
).publicSignupEnabled,
).toBe(false);
});
it("accepts an explicitly disabled publicSignupEnabled in production", () => {
for (const publicSignupEnabled of [false, "false"]) {
expect(
createIdentityConfig(
{ ...validInput(), publicSignupEnabled },
{ environment: "production" },
).publicSignupEnabled,
).toBe(false);
}
});
it("refuses to enable public signup in production until durable abuse controls exist", () => {
// Ekklesia has no verified email, invitation requirement, CAPTCHA, or durable shared/edge
// limiter yet, so a production deployment must not be able to open public registration at all
// — not even deliberately. This is a fail-closed configuration error, never a warning.
for (const publicSignupEnabled of [true, "true"]) {
let captured: unknown;
try {
createIdentityConfig(
{ ...validInput(), publicSignupEnabled },
{ environment: "production" },
);
} catch (error) {
captured = error;
}
expect(captured).toBeInstanceOf(IdentityConfigError);
expect(captured).toMatchObject({ code: "PUBLIC_SIGNUP_UNSUPPORTED_IN_PRODUCTION" });
}
});
it("defaults to production validation for public signup when environment is not specified", () => {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), publicSignupEnabled: "true" });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "PUBLIC_SIGNUP_UNSUPPORTED_IN_PRODUCTION" });
});
it("reports a malformed public-signup value as malformed even in production, never as unsupported", () => {
let captured: unknown;
try {
createIdentityConfig(
{ ...validInput(), publicSignupEnabled: "TRUE" },
{ environment: "production" },
);
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "PUBLIC_SIGNUP_ENABLED_INVALID" });
});
it("rejects a misspelled, loosely-truthy, or malformed publicSignupEnabled rather than silently defaulting", () => {
for (const publicSignupEnabled of ["1", "0", "yes", "no", "TRUE", "True", " true", "", 1, 0]) {
let captured: unknown;
try {
createIdentityConfig({ ...validInput(), publicSignupEnabled });
} catch (error) {
captured = error;
}
expect(captured).toMatchObject({ code: "PUBLIC_SIGNUP_ENABLED_INVALID" });
}
});
it("never leaks the secret, base URL, or trusted origins through a thrown error", () => {
const hostileSecret = "s3cr3t-do-not-log-0123456789abcdef";
let captured: unknown;
try {
createIdentityConfig({ baseUrl: "not-a-url", secret: hostileSecret, trustedOrigins: [] });
} catch (error) {
captured = error;
}
expect(captured).toBeInstanceOf(IdentityConfigError);
const publicText = `${String(captured)}\n${
captured instanceof Error ? (captured.stack ?? "") : ""
}\n${JSON.stringify(captured)}`;
expect(publicText).not.toContain(hostileSecret);
expect(publicText).not.toContain(validBaseUrl);
for (const origin of validTrustedOrigins) {
expect(publicText).not.toContain(origin);
}
});
});