diff --git a/.env.example b/.env.example index 918baca..baa1182 100644 --- a/.env.example +++ b/.env.example @@ -5,6 +5,8 @@ DATABASE_URL="postgresql://synthaea:synthaea_dev@localhost:5432/synthaea" NEXTAUTH_URL="http://localhost:3000" NEXTAUTH_SECRET="dev_secret_change_in_production" BETTER_AUTH_SECRET="dev_secret_change_in_production" +# Origins trusted on a request with a session cookie; unset = http://localhost:3000,http://localhost:8443 +# AUTH_TRUSTED_ORIGINS="https://console.example.com" # Cron CRON_SECRET="dev_cron_secret" diff --git a/app/api/cron/build-snapshots/route.ts b/app/api/cron/build-snapshots/route.ts index bca0070..f85fc68 100644 --- a/app/api/cron/build-snapshots/route.ts +++ b/app/api/cron/build-snapshots/route.ts @@ -3,28 +3,18 @@ import { verifyCronRequest } from "@/lib/cron-auth"; import { prisma } from "@/lib/prisma"; import { DEFAULT_SNAPSHOT_PARAMS, publishCommonSetSnapshot, type SnapshotParams } from "@/lib/snapshot-publish"; import { loadSnapshotSigner } from "@/lib/snapshot-manifest"; - -/** A positive number from the environment, or `fallback` when unset; a value that is set but wrong throws. */ -function numberFromEnv(name: string, fallback: number, integer: boolean): number { - const raw = process.env[name]; - if (raw === undefined || raw === "") return fallback; - const n = Number(raw); - if (!Number.isFinite(n) || n <= 0 || (integer && !Number.isInteger(n))) { - throw new Error(`${name} must be a positive ${integer ? "integer" : "number"}, got "${raw}"`); - } - return n; -} +import { positiveNumberFromEnv } from "@/lib/env"; /** Provisional starting points, set from the environment until slice 6 calibrates them. */ function paramsFromEnv(): SnapshotParams { const d = DEFAULT_SNAPSHOT_PARAMS; return { - minHosts: numberFromEnv("SNAPSHOT_MIN_HOSTS", d.minHosts, true), - minHostsCovered: numberFromEnv("SNAPSHOT_MIN_HOSTS_COVERED", d.minHostsCovered, true), - falsePositiveRate: numberFromEnv("SNAPSHOT_FALSE_POSITIVE_RATE", d.falsePositiveRate, false), - maxBytes: numberFromEnv("SNAPSHOT_MAX_BYTES", d.maxBytes, true), - maxEntries: numberFromEnv("SNAPSHOT_MAX_ENTRIES", d.maxEntries, true), - minEntryFraction: numberFromEnv("SNAPSHOT_MIN_ENTRY_FRACTION", d.minEntryFraction, false), + minHosts: positiveNumberFromEnv(process.env, "SNAPSHOT_MIN_HOSTS", d.minHosts, { integer: true }), + minHostsCovered: positiveNumberFromEnv(process.env, "SNAPSHOT_MIN_HOSTS_COVERED", d.minHostsCovered, { integer: true }), + falsePositiveRate: positiveNumberFromEnv(process.env, "SNAPSHOT_FALSE_POSITIVE_RATE", d.falsePositiveRate, { integer: false }), + maxBytes: positiveNumberFromEnv(process.env, "SNAPSHOT_MAX_BYTES", d.maxBytes, { integer: true }), + maxEntries: positiveNumberFromEnv(process.env, "SNAPSHOT_MAX_ENTRIES", d.maxEntries, { integer: true }), + minEntryFraction: positiveNumberFromEnv(process.env, "SNAPSHOT_MIN_ENTRY_FRACTION", d.minEntryFraction, { integer: false }), }; } diff --git a/app/api/cron/prune-prevalence/route.ts b/app/api/cron/prune-prevalence/route.ts index baa139d..352a211 100644 --- a/app/api/cron/prune-prevalence/route.ts +++ b/app/api/cron/prune-prevalence/route.ts @@ -1,7 +1,7 @@ import { NextRequest, NextResponse } from "next/server"; import { verifyCronRequest } from "@/lib/cron-auth"; import { prisma } from "@/lib/prisma"; -import { positiveIntFromEnv } from "@/lib/env-int"; +import { positiveIntFromEnv } from "@/lib/env"; import { pruneIngestStats } from "@/lib/ingest-stats"; import { DEFAULT_MAX_ROWS_PER_TENANT, diff --git a/app/api/cron/write-lake/route.ts b/app/api/cron/write-lake/route.ts index 87c6971..2e2a186 100644 --- a/app/api/cron/write-lake/route.ts +++ b/app/api/cron/write-lake/route.ts @@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server"; import { verifyCronRequest } from "@/lib/cron-auth"; import { prisma } from "@/lib/prisma"; import { lakeStoreFromEnv } from "@/lib/lake-env"; -import { positiveIntFromEnv } from "@/lib/env-int"; +import { positiveIntFromEnv } from "@/lib/env"; import { DEFAULT_MAX_BATCHES, drainLakeQueue } from "@/lib/lake-writer"; /** diff --git a/docs/configuration.md b/docs/configuration.md index 4ca39ec..8fcb07f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3,7 +3,7 @@ The server is configured only through environment variables. There is no configuration file; [`.env.example`](../.env.example) lists the core variables for a run outside Docker, and [`docker-compose.yml`](../docker-compose.yml) sets them for the development stack. Variables are -read when they are used, not validated at start-up: a missing secret shows as a refused request +read when they are used, not validated at start-up (`AUTH_TRUSTED_ORIGINS` is the exception, see below): a missing secret shows as a refused request (`500`, `503`), never as a silent default. The development values below are public. Replace every secret before the stack leaves one @@ -19,6 +19,7 @@ machine ([Deployment](deployment.md#before-the-stack-leaves-one-machine)); gener | `NGINX_PROXY_SECRET` | Yes | Shared secret nginx adds to every request as `X-Proxy-Secret`. Agent endpoints refuse a request without it, and refuse everything while it is unset. Set the same value on the application and the proxy. | `dev_nginx_secret_change_in_production` | | `CRON_SECRET` | For scheduled jobs | Bearer token of the `/api/cron/*` routes. Unset, every job call is refused. | `dev_cron_secret` | | `PLATFORM_OPERATOR_USER_IDS` | To create tenants | Comma-separated `auth_user.id` values allowed to call `POST /api/admin/tenants`. Unset, nobody can. | unset | +| `AUTH_TRUSTED_ORIGINS` | In production | Comma-separated `http(s)://host[:port]` origins better-auth trusts on a request that carries a session cookie, for example `https://console.example.com`. Unset, it is `http://localhost:3000,http://localhost:8443`; set, it replaces those two (localhost is not added back by this variable). better-auth also trusts the origin of its own base URL and `BETTER_AUTH_TRUSTED_ORIGINS`, see [security model](security-model.md#console-users). An entry that is not an origin, or a value with no entry (`,`), makes the server log `Invalid configuration, exiting` and exit with status 1 at start (Next 14.2 would otherwise keep listening and answer every request with 500). | unset | | `NEXTAUTH_URL` | No | Public base URL of the console. Used only as the fallback for `NOTIFY_CONSOLE_URL`. | `http://localhost:3000` | | `NODE_ENV` | No | `development` logs every Prisma query; the production image sets `production`. | `development` | | `PORT`, `HOSTNAME` | No | Where the Next.js server listens (default `3000` and, in the images, `0.0.0.0`). The middleware calls the session route on `127.0.0.1:$PORT`. | `3000`, `0.0.0.0` | diff --git a/docs/deployment.md b/docs/deployment.md index 17fdad8..4eaad8d 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -128,6 +128,7 @@ stack: - Replace every secret with a random value: `BETTER_AUTH_SECRET`, `CRON_SECRET`, `NGINX_PROXY_SECRET` (the same value on `server` and `proxy`) and the PostgreSQL password in both `POSTGRES_PASSWORD` and `DATABASE_URL`. +- Set `AUTH_TRUSTED_ORIGINS` to the console's public origin (for example `https://console.example.com`). Unset, the console trusts only `localhost`, and a sign-in from the real address is refused. In `docker-compose.yml` the `server` service lists its variables in an explicit `environment:` map: add `AUTH_TRUSTED_ORIGINS` there, because setting it in `.env` alone does not reach the container. - Never publish the application port. The proxy secret is what keeps a client from talking to the application directly with forged certificate headers, and it only works if the application is unreachable except through the proxy. diff --git a/docs/security-model.md b/docs/security-model.md index 455a64c..71d82fb 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -60,7 +60,7 @@ its `agents` row exists. Users sign in with email and password through [better-auth](https://www.better-auth.com) ([`lib/auth.ts`](../lib/auth.ts)), mounted at `/api/auth/*`. Sessions are cookies signed with `BETTER_AUTH_SECRET`. better-auth refuses a request that carries a session cookie without an -`Origin` it trusts; the trusted origins are set in `lib/auth.ts`. +`Origin` it trusts; the trusted origins are `AUTH_TRUSTED_ORIGINS` (`lib/env.ts`), the two localhost origins of a development console when unset. The effective list, in better-auth 1.7, is the origin of its base URL (`BETTER_AUTH_URL`, otherwise the request's own origin), plus the `trustedOrigins` option (`AUTH_TRUSTED_ORIGINS` or its default), plus `BETTER_AUTH_TRUSTED_ORIGINS` split on commas. `AUTH_TRUSTED_ORIGINS` is validated when the server starts (`instrumentation-node.ts`, which exits with status 1 on a bad value) and again when `lib/auth.ts` is imported; `BETTER_AUTH_TRUSTED_ORIGINS` is still honoured and is not validated by `lib/env.ts`, so leave it unset unless you need it. Tenancy uses better-auth's organization plugin. An organization and its tenant share one id, and a session's `activeOrganizationId` is the tenant the user acts in. Users cannot create diff --git a/instrumentation-node.ts b/instrumentation-node.ts index 4016225..faea453 100644 --- a/instrumentation-node.ts +++ b/instrumentation-node.ts @@ -1,3 +1,4 @@ +import { authTrustedOrigins, type Environment } from "@/lib/env"; import { prisma } from "@/lib/prisma"; import { checkDecoyTable, checkShutdownOwnership, installDecoyShutdownFlush } from "@/lib/decoy"; @@ -10,3 +11,18 @@ export function startDecoyWatch(): void { installDecoyShutdownFlush(process); void checkDecoyTable(prisma); } + +/** + * Configuration that must be right for the server to be useful, checked at start. A throw from + * Next's `register()` hook is wrapped and logged as "Failed to prepare server" while the process + * keeps listening and answers every request with 500 (Next 14.2), so a bad value logs the cause + * and exits with status 1, which a container orchestrator notices. + */ +export function assertStartupConfig(env: Environment, exit: (code: number) => never = process.exit): void { + try { + authTrustedOrigins(env); + } catch (error) { + console.error(`Invalid configuration, exiting: ${error instanceof Error ? error.message : String(error)}`); + exit(1); + } +} diff --git a/instrumentation.ts b/instrumentation.ts index 30de7e8..6eea6fe 100644 --- a/instrumentation.ts +++ b/instrumentation.ts @@ -4,10 +4,16 @@ * Node-only code lives in `instrumentation-node.ts`, loaded only under a condition webpack * can see through (`NEXT_RUNTIME === "nodejs"`). An early `return` is not enough: the import * after it would still be resolved for the Edge bundle and fail the whole build. + * + * An exception from `register()` does not stop a Next 14.2 server: it only makes every request + * fail with 500. A configuration error therefore exits the process in `instrumentation-node.ts` + * (`process.exit` stays out of this file, which is also compiled for Edge). */ export async function register(): Promise { if (process.env.NEXT_RUNTIME === "nodejs") { - const { startDecoyWatch } = await import("./instrumentation-node"); + const { assertStartupConfig, startDecoyWatch } = await import("./instrumentation-node"); + // Validate first: the pure check, before any side effect is installed. + assertStartupConfig(process.env); startDecoyWatch(); } } diff --git a/lib/auth.ts b/lib/auth.ts index 25c1389..3dd1c2c 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -2,6 +2,7 @@ import { betterAuth } from "better-auth"; import { prismaAdapter } from "better-auth/adapters/prisma"; import { organization } from "better-auth/plugins"; import { prisma } from "@/lib/prisma"; +import { authTrustedOrigins } from "@/lib/env"; export const auth = betterAuth({ // The Prisma client the rest of the server uses; the auth tables are Prisma models @@ -23,10 +24,8 @@ export const auth = betterAuth({ disableOrganizationDeletion: true, }), ], - trustedOrigins: [ - "http://localhost:3000", - "http://localhost:8443", - ], + // `AUTH_TRUSTED_ORIGINS` sets them; unset, the two localhost origins of a development console. + trustedOrigins: authTrustedOrigins(process.env), }); export type Session = typeof auth.$Infer.Session; diff --git a/lib/env-int.ts b/lib/env-int.ts deleted file mode 100644 index 5fd3d4b..0000000 --- a/lib/env-int.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * A positive integer from the environment, or `fallback` when unset. A value that is set but wrong - * throws: a typo must not silently mean "keep the default". - */ -export function positiveIntFromEnv(env: Record, name: string, fallback: number): number { - const raw = env[name]; - if (raw === undefined || raw === "") return fallback; - const n = Number(raw); - if (!Number.isInteger(n) || n <= 0) throw new Error(`${name} must be a positive integer, got "${raw}"`); - return n; -} diff --git a/lib/env.ts b/lib/env.ts new file mode 100644 index 0000000..1ed8bb6 --- /dev/null +++ b/lib/env.ts @@ -0,0 +1,71 @@ +/** + * Configuration read from the environment, in one place. Each reader takes the environment as an + * argument (`process.env` at the call site) so a test can pass its own. A value that is set but wrong + * throws: a typo must not silently mean "keep the default". + */ + +/** What the readers below take: `process.env`, or a test's own object. */ +export type Environment = Record; + +/** + * A positive number from the environment, or `fallback` when unset or empty. With `integer`, a + * fraction is refused too. + */ +export function positiveNumberFromEnv( + env: Environment, + name: string, + fallback: number, + { integer = false }: { integer?: boolean } = {} +): number { + const raw = env[name]; + if (raw === undefined || raw === "") return fallback; + const n = Number(raw); + if (!Number.isFinite(n) || n <= 0 || (integer && !Number.isInteger(n))) { + throw new Error(`${name} must be a positive ${integer ? "integer" : "number"}, got "${raw}"`); + } + return n; +} + +/** A positive integer from the environment, or `fallback` when unset or empty. */ +export function positiveIntFromEnv(env: Environment, name: string, fallback: number): number { + return positiveNumberFromEnv(env, name, fallback, { integer: true }); +} + +/** The origins better-auth trusted before they were configurable (a development console and the nginx port). */ +const DEFAULT_TRUSTED_ORIGINS = ["http://localhost:3000", "http://localhost:8443"]; + +/** + * The origins better-auth accepts on a request that carries a session cookie (`lib/auth.ts`). + * `AUTH_TRUSTED_ORIGINS` is a comma-separated list of `http(s)://host[:port]` origins. Unset, empty or + * blank it is the two localhost origins, as before; set, it is the listed origins instead of those two. + * An entry that is not an origin (no scheme, a path, a query, credentials) throws, and so does a value + * with no entry at all (`","`). better-auth adds its own origins on top (see docs/security-model.md). + */ +export function authTrustedOrigins(env: Environment): string[] { + const raw = env.AUTH_TRUSTED_ORIGINS; + if (raw === undefined || raw.trim() === "") return [...DEFAULT_TRUSTED_ORIGINS]; + const entries = raw.split(",").map((e) => e.trim()).filter((e) => e !== ""); + if (entries.length === 0) throw new Error(`AUTH_TRUSTED_ORIGINS lists no origin, got "${raw}"`); + return Array.from(new Set(entries.map(parseOrigin))); +} + +/** True for `http(s)://host[:port]` and nothing more: no credentials, path, query or fragment. */ +function isBareHttpOrigin(url: URL): boolean { + const httpScheme = url.protocol === "http:" || url.protocol === "https:"; + const noCredentials = url.username === "" && url.password === ""; + const noPath = url.pathname === "/" || url.pathname === ""; + return httpScheme && noCredentials && noPath && url.search === "" && url.hash === ""; +} + +function parseOrigin(entry: string): string { + const invalidOriginError = (cause?: unknown) => + new Error(`AUTH_TRUSTED_ORIGINS must list http(s)://host[:port] origins, got "${entry}"`, { cause }); + let url: URL; + try { + url = new URL(entry); + } catch (error) { + throw invalidOriginError(error); + } + if (!isBareHttpOrigin(url)) throw invalidOriginError(); + return url.origin; +} diff --git a/lib/lake-backlog-case.ts b/lib/lake-backlog-case.ts index 20d55bc..e6c5d83 100644 --- a/lib/lake-backlog-case.ts +++ b/lib/lake-backlog-case.ts @@ -1,5 +1,5 @@ import type { PrismaClient } from "@prisma/client"; -import { positiveIntFromEnv } from "@/lib/env-int"; +import { positiveIntFromEnv } from "@/lib/env"; import { ACTIVE_CASE_STATUSES } from "@/lib/hunt-search"; import type { LakeBacklog } from "@/lib/lake-backlog"; diff --git a/tests/unit/auth-trusted-origins.test.ts b/tests/unit/auth-trusted-origins.test.ts new file mode 100644 index 0000000..e3ba754 --- /dev/null +++ b/tests/unit/auth-trusted-origins.test.ts @@ -0,0 +1,67 @@ +import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; + +// `lib/auth.ts` reads the environment once, when it is imported: each case sets it, resets the module +// registry and imports the module again. +async function loadAuth(origins: string | undefined) { + vi.stubEnv("AUTH_TRUSTED_ORIGINS", origins); + vi.resetModules(); + return (await import("@/lib/auth")).auth; +} + +// better-auth skips its origin check when it sees a test environment (read once, when it is imported). +// The tests that exercise the check import it as it runs in production; `afterEach` puts the +// environment back. +async function loadAuthWithOriginCheck(origins: string) { + vi.stubEnv("NODE_ENV", "production"); + vi.stubEnv("TEST", undefined); + return loadAuth(origins); +} + +// The first import of better-auth transforms the whole package (vitest.config.ts inlines it), which +// takes several seconds on a slow runner. Pay it here, not inside the first test's 5 s budget. +beforeAll(async () => { + await import("@/lib/auth"); +}, 60_000); + +afterEach(() => { + vi.unstubAllEnvs(); + delete process.env.AUTH_TRUSTED_ORIGINS; + vi.resetModules(); +}); + +// A request that carries a session cookie, which is what better-auth's origin check applies to. +function signOutFrom(origin: string) { + return new Request("http://localhost:3000/api/auth/sign-out", { + method: "POST", + headers: { origin, cookie: "better-auth.session_token=not-a-real-session", "content-type": "application/json" }, + body: "{}", + }); +} + +describe("lib/auth trusted origins", () => { + it("keeps the two localhost origins when AUTH_TRUSTED_ORIGINS is unset", async () => { + const auth = await loadAuth(undefined); + expect(auth.options.trustedOrigins).toEqual(["http://localhost:3000", "http://localhost:8443"]); + }); + + it("trusts the configured production origin and no localhost", async () => { + const auth = await loadAuth("https://console.example.com"); + expect(auth.options.trustedOrigins).toEqual(["https://console.example.com"]); + }); + + it("fails at import on a value that is not an origin", async () => { + await expect(loadAuth("console.example.com")).rejects.toThrow(/AUTH_TRUSTED_ORIGINS/); + }); + + it("refuses a cookie-bearing request from a foreign Origin", async () => { + const auth = await loadAuthWithOriginCheck("https://console.example.com"); + const response = await auth.handler(signOutFrom("https://evil.example.com")); + expect(response.status).toBe(403); + }); + + it("accepts a cookie-bearing request from a configured Origin", async () => { + const auth = await loadAuthWithOriginCheck("https://console.example.com"); + const response = await auth.handler(signOutFrom("https://console.example.com")); + expect(response.status).toBe(200); + }); +}); diff --git a/tests/unit/env.test.ts b/tests/unit/env.test.ts new file mode 100644 index 0000000..f3a962a --- /dev/null +++ b/tests/unit/env.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import { authTrustedOrigins, positiveIntFromEnv, positiveNumberFromEnv } from "@/lib/env"; + +describe("positiveNumberFromEnv", () => { + it("returns the fallback when the variable is unset or empty", () => { + expect(positiveNumberFromEnv({}, "X", 7)).toBe(7); + expect(positiveNumberFromEnv({ X: "" }, "X", 7)).toBe(7); + }); + + it("returns a positive number, a fraction included unless an integer is asked for", () => { + expect(positiveNumberFromEnv({ X: "3" }, "X", 7)).toBe(3); + expect(positiveNumberFromEnv({ X: "0.25" }, "X", 7)).toBe(0.25); + }); + + it("throws on a set value that is not a positive number, naming the variable and the value", () => { + for (const bad of ["abc", "0", "-1", "Infinity", "NaN", "1e999"]) { + expect(() => positiveNumberFromEnv({ X: bad }, "X", 7)).toThrow(`X must be a positive number, got "${bad}"`); + } + }); + + it("refuses a fraction when an integer is asked for", () => { + expect(positiveNumberFromEnv({ X: "4" }, "X", 7, { integer: true })).toBe(4); + expect(() => positiveNumberFromEnv({ X: "2.5" }, "X", 7, { integer: true })).toThrow('X must be a positive integer, got "2.5"'); + expect(() => positiveNumberFromEnv({ X: "0" }, "X", 7, { integer: true })).toThrow('X must be a positive integer, got "0"'); + }); +}); + +describe("positiveIntFromEnv", () => { + it("keeps its answers: the fallback when unset, a positive integer, an error otherwise", () => { + expect(positiveIntFromEnv({}, "N", 200)).toBe(200); + expect(positiveIntFromEnv({ N: "" }, "N", 200)).toBe(200); + expect(positiveIntFromEnv({ N: "50" }, "N", 200)).toBe(50); + for (const bad of ["1.5", "0", "-3", "ten", "Infinity"]) { + expect(() => positiveIntFromEnv({ N: bad }, "N", 200)).toThrow(`N must be a positive integer, got "${bad}"`); + } + }); +}); + +describe("authTrustedOrigins", () => { + const LOCAL = ["http://localhost:3000", "http://localhost:8443"]; + + it("is the two localhost origins when AUTH_TRUSTED_ORIGINS is unset, empty or blank (today's value)", () => { + expect(authTrustedOrigins({})).toEqual(LOCAL); + expect(authTrustedOrigins({ AUTH_TRUSTED_ORIGINS: "" })).toEqual(LOCAL); + expect(authTrustedOrigins({ AUTH_TRUSTED_ORIGINS: " " })).toEqual(LOCAL); + }); + + it("is exactly the listed origins when set: localhost is not added back", () => { + expect(authTrustedOrigins({ AUTH_TRUSTED_ORIGINS: "https://console.example.com" })).toEqual(["https://console.example.com"]); + expect(authTrustedOrigins({ AUTH_TRUSTED_ORIGINS: "https://a.example.com, https://b.example.com:8443 ,," })).toEqual([ + "https://a.example.com", + "https://b.example.com:8443", + ]); + }); + + it("normalizes a trailing slash and the default port, and drops a duplicate", () => { + expect(authTrustedOrigins({ AUTH_TRUSTED_ORIGINS: "https://a.example.com/,https://a.example.com:443" })).toEqual(["https://a.example.com"]); + }); + + it("throws on an entry that is not an http(s) origin, so a typo never means the default", () => { + for (const bad of ["console.example.com", "ftp://a.example.com", "https://a.example.com/console", "https://a.example.com?x=1", "https://user@a.example.com", "*"]) { + expect(() => authTrustedOrigins({ AUTH_TRUSTED_ORIGINS: `https://ok.example.com,${bad}` })).toThrow(/AUTH_TRUSTED_ORIGINS/); + } + }); + + it("throws on a non-blank value with no entry, which would otherwise trust no origin silently", () => { + for (const bad of [",", " , ", ",,"]) { + expect(() => authTrustedOrigins({ AUTH_TRUSTED_ORIGINS: bad })).toThrow(/lists no origin/); + } + }); +}); diff --git a/tests/unit/instrumentation.test.ts b/tests/unit/instrumentation.test.ts index fc01fe5..77e6e8b 100644 --- a/tests/unit/instrumentation.test.ts +++ b/tests/unit/instrumentation.test.ts @@ -1,6 +1,6 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; /** * Next compiles `instrumentation.ts` for the Node AND the Edge runtime. The Edge one cannot @@ -38,3 +38,30 @@ describe("the production image", () => { expect(dockerfile.indexOf("NEXT_MANUAL_SIG_HANDLE")).toBeLessThan(dockerfile.lastIndexOf("CMD")); }); }); + +describe("assertStartupConfig", () => { + const exit = (code: number): never => { + throw new Error(`exit ${code}`); + }; + + it("exits with status 1 and logs the cause on a bad AUTH_TRUSTED_ORIGINS", async () => { + const { assertStartupConfig } = await import("../../instrumentation-node"); + const log = vi.spyOn(console, "error").mockImplementation(() => {}); + expect(() => assertStartupConfig({ AUTH_TRUSTED_ORIGINS: "console.example.com" }, exit)).toThrow("exit 1"); + expect(log).toHaveBeenCalledWith(expect.stringContaining("AUTH_TRUSTED_ORIGINS")); + log.mockRestore(); + }, 30_000); + + it("does nothing on a valid or unset value", async () => { + const { assertStartupConfig } = await import("../../instrumentation-node"); + expect(() => assertStartupConfig({ AUTH_TRUSTED_ORIGINS: "https://console.example.com" }, exit)).not.toThrow(); + expect(() => assertStartupConfig({}, exit)).not.toThrow(); + }); +}); + +describe("instrumentation.ts boot order", () => { + it("validates the configuration before the decoy side effects start", () => { + expect(entry.indexOf("assertStartupConfig(")).toBeGreaterThan(-1); + expect(entry.indexOf("assertStartupConfig(")).toBeLessThan(entry.indexOf("startDecoyWatch()")); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts index f1afe76..114c218 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -9,6 +9,10 @@ export default defineConfig({ include: ["tests/**/*.test.ts"], // Integration files share one Postgres database and each clears it between tests. fileParallelism: false, + // better-auth reads NODE_ENV once, when it is imported, and skips its origin check under "test". + // Inlined, it goes through vi.resetModules, so tests/unit/auth-trusted-origins.test.ts can import + // it as production does. + server: { deps: { inline: [/better-auth/] } }, coverage: { provider: "v8", reporter: ["text", "json", "html"],