diff --git a/app/api/cron/build-snapshots/route.ts b/app/api/cron/build-snapshots/route.ts index f85fc68..ccf53f9 100644 --- a/app/api/cron/build-snapshots/route.ts +++ b/app/api/cron/build-snapshots/route.ts @@ -1,22 +1,8 @@ import { NextRequest, NextResponse } from "next/server"; import { verifyCronRequest } from "@/lib/cron-auth"; import { prisma } from "@/lib/prisma"; -import { DEFAULT_SNAPSHOT_PARAMS, publishCommonSetSnapshot, type SnapshotParams } from "@/lib/snapshot-publish"; +import { publishCommonSetSnapshot, snapshotParamsFromEnv } from "@/lib/snapshot-publish"; import { loadSnapshotSigner } from "@/lib/snapshot-manifest"; -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: 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 }), - }; -} /** * GET /api/cron/build-snapshots @@ -36,7 +22,7 @@ export async function GET(req: NextRequest) { if (!signer) { return NextResponse.json({ error: "Snapshot signing is not configured" }, { status: 503 }); } - const params = paramsFromEnv(); + const params = snapshotParamsFromEnv(process.env); const now = new Date(); const tenants = await prisma.tenant.findMany({ select: { id: true } }); diff --git a/docs/configuration.md b/docs/configuration.md index 8fcb07f..4a0406d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3,8 +3,11 @@ 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 (`AUTH_TRUSTED_ORIGINS` is the exception, see below): a missing secret shows as a refused request -(`500`, `503`), never as a silent default. +read through `lib/env.ts`. A missing secret shows as a refused request (`500`, `503`), never as a +silent default, and the server starts without it. A value that is set but wrong is another matter: +`AUTH_TRUSTED_ORIGINS`, `PORT` and the `SNAPSHOT_*` numbers are checked at start, and a bad one +logs `Invalid configuration, exiting` and exits with status 1. The other numbers (`LAKE_*`, +`PREVALENCE_*`) are read by the job that uses them and fail that job. The development values below are public. Replace every secret before the stack leaves one machine ([Deployment](deployment.md#before-the-stack-leaves-one-machine)); generate one with @@ -22,7 +25,7 @@ machine ([Deployment](deployment.md#before-the-stack-leaves-one-machine)); gener | `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` | +| `PORT`, `HOSTNAME` | No | Where the Next.js server listens (default `3000`, and a `PORT` that is not an integer from 1 to 65535 stops the server at start; in the images `HOSTNAME` is `0.0.0.0`). The middleware calls the session route on `127.0.0.1:$PORT`. | `3000`, `0.0.0.0` | | `NEXT_MANUAL_SIG_HANDLE` | In production | `true` hands `SIGINT`/`SIGTERM` to the server's own handler, which writes pending decoy alarms (at most 5 seconds) before exiting. The production image sets it; the server logs a warning at start when it is missing. | set in the `runner` image | `docker-compose.yml` also sets `NEXTAUTH_SECRET`, which nothing reads. diff --git a/instrumentation-node.ts b/instrumentation-node.ts index faea453..8339d9d 100644 --- a/instrumentation-node.ts +++ b/instrumentation-node.ts @@ -1,4 +1,5 @@ -import { authTrustedOrigins, type Environment } from "@/lib/env"; +import { authTrustedOrigins, listenPort, type Environment } from "@/lib/env"; +import { snapshotParamsFromEnv } from "@/lib/snapshot-publish"; import { prisma } from "@/lib/prisma"; import { checkDecoyTable, checkShutdownOwnership, installDecoyShutdownFlush } from "@/lib/decoy"; @@ -21,6 +22,8 @@ export function startDecoyWatch(): void { export function assertStartupConfig(env: Environment, exit: (code: number) => never = process.exit): void { try { authTrustedOrigins(env); + listenPort(env); + snapshotParamsFromEnv(env); } catch (error) { console.error(`Invalid configuration, exiting: ${error instanceof Error ? error.message : String(error)}`); exit(1); diff --git a/lib/cron-auth.ts b/lib/cron-auth.ts index 62182fe..f9cd970 100644 --- a/lib/cron-auth.ts +++ b/lib/cron-auth.ts @@ -2,6 +2,7 @@ import { timingSafeEqual } from "node:crypto"; import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { scheduleDecoyReport } from "@/lib/decoy"; +import { cronSecret } from "@/lib/env"; export type CronAuthResult = "ok" | "unconfigured" | "unauthorized"; @@ -44,7 +45,7 @@ export function checkCronAuth( */ export async function verifyCronRequest(req: NextRequest): Promise { const authorization = req.headers.get("Authorization"); - switch (checkCronAuth(authorization, process.env.CRON_SECRET)) { + switch (checkCronAuth(authorization, cronSecret(process.env))) { case "ok": return null; case "unconfigured": diff --git a/lib/env.ts b/lib/env.ts index 1ed8bb6..d31bd0e 100644 --- a/lib/env.ts +++ b/lib/env.ts @@ -69,3 +69,37 @@ function parseOrigin(entry: string): string { if (!isBareHttpOrigin(url)) throw invalidOriginError(); return url.origin; } + +/** + * The secret nginx adds to every request as `X-Proxy-Secret` (`NGINX_PROXY_SECRET`). `undefined` + * when unset or empty: the caller refuses every request then, it never treats "no secret" as a match. + * The value is not trimmed: it is compared byte for byte with the header. + */ +export function proxySecret(env: Environment): string | undefined { + return env.NGINX_PROXY_SECRET || undefined; +} + +/** The bearer token of the `/api/cron/*` routes (`CRON_SECRET`). `undefined` when unset or empty: every job call is refused then. */ +export function cronSecret(env: Environment): string | undefined { + return env.CRON_SECRET || undefined; +} + +/** + * The `auth_user.id` values allowed to act before a tenant exists (`PLATFORM_OPERATOR_USER_IDS`, + * comma-separated, entries trimmed, empty entries dropped). Unset or empty is an empty list: nobody is allowed. + */ +export function platformOperatorIds(env: Environment): string[] { + return (env.PLATFORM_OPERATOR_USER_IDS ?? "") + .split(",") + .map((id) => id.trim()) + .filter((id) => id.length > 0); +} + +/** The port the Next.js server listens on (`PORT`, 3000 when unset or empty). A value that is not 1-65535 throws. */ +export function listenPort(env: Environment): number { + const raw = env.PORT; + if (raw === undefined || raw === "") return 3000; + const n = Number(raw); + if (!Number.isInteger(n) || n < 1 || n > 65535) throw new Error(`PORT must be an integer from 1 to 65535, got "${raw}"`); + return n; +} diff --git a/lib/platform-operator.ts b/lib/platform-operator.ts index 6ee1a89..0106806 100644 --- a/lib/platform-operator.ts +++ b/lib/platform-operator.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from "next/server"; +import { platformOperatorIds } from "@/lib/env"; import { getUserId } from "@/lib/tenant"; /** @@ -18,11 +19,7 @@ export async function requirePlatformOperator( req: NextRequest ): Promise<{ userId: string } | { response: NextResponse }> { const userId = getUserId(req); - const allowed = (process.env.PLATFORM_OPERATOR_USER_IDS ?? "") - .split(",") - .map((id) => id.trim()) - .filter((id) => id.length > 0); - if (!allowed.includes(userId)) { + if (!platformOperatorIds(process.env).includes(userId)) { return { response: NextResponse.json({ error: "Platform operator access required" }, { status: 403 }), }; diff --git a/lib/session-lookup.ts b/lib/session-lookup.ts index 48557e0..5645ad8 100644 --- a/lib/session-lookup.ts +++ b/lib/session-lookup.ts @@ -9,6 +9,8 @@ * Fails closed: a missing cookie, a refusal, a network error, a timeout or an answer of an * unexpected shape is "no session", which the middleware turns into a redirect to `/login`. */ +import { listenPort } from "@/lib/env"; + /** What the middleware needs from a session. */ export type LookedUpSession = { @@ -24,7 +26,7 @@ const LOOKUP_TIMEOUT_MS = 5_000; * `X-Forwarded-Host`: those are the client's, and the request carries the session cookie. */ function selfOrigin(): string { - return `http://127.0.0.1:${process.env.PORT ?? "3000"}`; + return `http://127.0.0.1:${listenPort(process.env)}`; } export async function lookupSession(headers: Headers): Promise { diff --git a/lib/snapshot-publish.ts b/lib/snapshot-publish.ts index db1a680..b9b3dc6 100644 --- a/lib/snapshot-publish.ts +++ b/lib/snapshot-publish.ts @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import type { PrismaClient } from "@prisma/client"; import { buildCommonSetSnapshot, SnapshotTooLargeError } from "@/lib/common-set-snapshot"; +import { positiveNumberFromEnv, type Environment } from "@/lib/env"; import { countReportingHosts, getCommonHashes } from "@/lib/prevalence"; import { signSnapshotManifest, @@ -36,6 +37,19 @@ export const DEFAULT_SNAPSHOT_PARAMS: SnapshotParams = { minEntryFraction: 0.5, }; +/** The defaults, each overridden by its `SNAPSHOT_*` variable. A value that is set but wrong throws. */ +export function snapshotParamsFromEnv(env: Environment): SnapshotParams { + const d = DEFAULT_SNAPSHOT_PARAMS; + return { + minHosts: positiveNumberFromEnv(env, "SNAPSHOT_MIN_HOSTS", d.minHosts, { integer: true }), + minHostsCovered: positiveNumberFromEnv(env, "SNAPSHOT_MIN_HOSTS_COVERED", d.minHostsCovered, { integer: true }), + falsePositiveRate: positiveNumberFromEnv(env, "SNAPSHOT_FALSE_POSITIVE_RATE", d.falsePositiveRate), + maxBytes: positiveNumberFromEnv(env, "SNAPSHOT_MAX_BYTES", d.maxBytes, { integer: true }), + maxEntries: positiveNumberFromEnv(env, "SNAPSHOT_MAX_ENTRIES", d.maxEntries, { integer: true }), + minEntryFraction: positiveNumberFromEnv(env, "SNAPSHOT_MIN_ENTRY_FRACTION", d.minEntryFraction), + }; +} + export type PublishOutcome = | { status: "published"; builtAt: number; hostsCovered: number; entryCount: number; size: number } | { status: "skipped"; reason: string }; diff --git a/lib/tenant.ts b/lib/tenant.ts index 43ee67c..9fbc5a9 100644 --- a/lib/tenant.ts +++ b/lib/tenant.ts @@ -1,4 +1,5 @@ import { NextRequest } from "next/server"; +import { proxySecret } from "@/lib/env"; /** * Headers the middleware derives from the session. Route handlers trust them @@ -95,8 +96,8 @@ export function getUserId(req: NextRequest): string { * @throws Error if proxy authentication fails */ export function verifyProxyAuth(req: NextRequest): void { - const proxySecret = req.headers.get("X-Proxy-Secret"); - const expectedSecret = process.env.NGINX_PROXY_SECRET; + const presentedSecret = req.headers.get("X-Proxy-Secret"); + const expectedSecret = proxySecret(process.env); if (!expectedSecret) { throw new Error( @@ -105,7 +106,7 @@ export function verifyProxyAuth(req: NextRequest): void { } // Constant-time comparison to prevent timing attacks - if (!proxySecret || !timingSafeEqual(proxySecret, expectedSecret)) { + if (!presentedSecret || !timingSafeEqual(presentedSecret, expectedSecret)) { throw new Error("Invalid proxy authentication - request did not come from nginx"); } } diff --git a/tests/unit/cron-auth.test.ts b/tests/unit/cron-auth.test.ts index d9da911..b1c438d 100644 --- a/tests/unit/cron-auth.test.ts +++ b/tests/unit/cron-auth.test.ts @@ -41,6 +41,16 @@ describe("verifyCronRequest", () => { expect((await verifyCronRequest(request("Bearer nope")))?.status).toBe(401); }); + it("returns 500 when CRON_SECRET is empty, even for 'Bearer '", async () => { + const saved = process.env.CRON_SECRET; + process.env.CRON_SECRET = ""; + try { + expect((await verifyCronRequest(request("Bearer ")))?.status).toBe(500); + } finally { + process.env.CRON_SECRET = saved; + } + }); + it("returns 500 and rejects 'Bearer undefined' when CRON_SECRET is unset", async () => { const saved = process.env.CRON_SECRET; delete process.env.CRON_SECRET; diff --git a/tests/unit/env.test.ts b/tests/unit/env.test.ts index f3a962a..5d853de 100644 --- a/tests/unit/env.test.ts +++ b/tests/unit/env.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { authTrustedOrigins, positiveIntFromEnv, positiveNumberFromEnv } from "@/lib/env"; +import { authTrustedOrigins, cronSecret, listenPort, platformOperatorIds, positiveIntFromEnv, positiveNumberFromEnv, proxySecret } from "@/lib/env"; describe("positiveNumberFromEnv", () => { it("returns the fallback when the variable is unset or empty", () => { @@ -69,3 +69,47 @@ describe("authTrustedOrigins", () => { } }); }); + +describe("proxySecret and cronSecret", () => { + it("return the value as set, untrimmed", () => { + expect(proxySecret({ NGINX_PROXY_SECRET: " s3 " })).toBe(" s3 "); + expect(cronSecret({ CRON_SECRET: "c1" })).toBe("c1"); + }); + + it("are undefined when unset or empty: the callers refuse, never match", () => { + for (const env of [{}, { NGINX_PROXY_SECRET: "", CRON_SECRET: "" }]) { + expect(proxySecret(env)).toBeUndefined(); + expect(cronSecret(env)).toBeUndefined(); + } + }); +}); + +describe("platformOperatorIds", () => { + it("is empty when unset, empty or only separators: nobody is allowed", () => { + expect(platformOperatorIds({})).toEqual([]); + expect(platformOperatorIds({ PLATFORM_OPERATOR_USER_IDS: "" })).toEqual([]); + expect(platformOperatorIds({ PLATFORM_OPERATOR_USER_IDS: " , ," })).toEqual([]); + }); + + it("lists the ids, trimmed, empty entries dropped", () => { + expect(platformOperatorIds({ PLATFORM_OPERATOR_USER_IDS: "u1, u2 ,,u3" })).toEqual(["u1", "u2", "u3"]); + }); +}); + +describe("listenPort", () => { + it("is 3000 when unset or empty", () => { + expect(listenPort({})).toBe(3000); + expect(listenPort({ PORT: "" })).toBe(3000); + }); + + it("is the port when it is an integer from 1 to 65535", () => { + expect(listenPort({ PORT: "8080" })).toBe(8080); + expect(listenPort({ PORT: "65535" })).toBe(65535); + }); + + it("throws on anything else, naming the value", () => { + for (const bad of ["0", "65536", "-1", "80.5", "http", " "]) { + expect(() => listenPort({ PORT: bad })).toThrow(`PORT must be an integer from 1 to 65535, got "${bad}"`); + } + }); +}); diff --git a/tests/unit/instrumentation.test.ts b/tests/unit/instrumentation.test.ts index 77e6e8b..8131ed5 100644 --- a/tests/unit/instrumentation.test.ts +++ b/tests/unit/instrumentation.test.ts @@ -52,6 +52,21 @@ describe("assertStartupConfig", () => { log.mockRestore(); }, 30_000); + it("exits with status 1 on a bad PORT or SNAPSHOT_* value", async () => { + const { assertStartupConfig } = await import("../../instrumentation-node"); + const log = vi.spyOn(console, "error").mockImplementation(() => {}); + expect(() => assertStartupConfig({ PORT: "http" }, exit)).toThrow("exit 1"); + expect(log).toHaveBeenCalledWith(expect.stringContaining("PORT")); + expect(() => assertStartupConfig({ SNAPSHOT_MAX_BYTES: "1.5" }, exit)).toThrow("exit 1"); + expect(log).toHaveBeenCalledWith(expect.stringContaining("SNAPSHOT_MAX_BYTES")); + log.mockRestore(); + }); + + it("does not require a secret: an unset secret is a closed door, not a startup error", async () => { + const { assertStartupConfig } = await import("../../instrumentation-node"); + expect(() => assertStartupConfig({ PORT: "8080" }, exit)).not.toThrow(); + }); + 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(); diff --git a/tests/unit/platform-operator.test.ts b/tests/unit/platform-operator.test.ts new file mode 100644 index 0000000..69d41c2 --- /dev/null +++ b/tests/unit/platform-operator.test.ts @@ -0,0 +1,28 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; +import { requirePlatformOperator } from "@/lib/platform-operator"; + +const asUser = (id: string) => new NextRequest("http://localhost/x", { headers: { "x-user-id": id } }); + +afterEach(() => vi.unstubAllEnvs()); + +describe("requirePlatformOperator", () => { + it("lets a listed user through, whatever the spacing around the list", async () => { + vi.stubEnv("PLATFORM_OPERATOR_USER_IDS", "u1, u2 ,,u3"); + expect(await requirePlatformOperator(asUser("u2"))).toEqual({ userId: "u2" }); + }); + + it("refuses a user who is not listed with 403", async () => { + vi.stubEnv("PLATFORM_OPERATOR_USER_IDS", "u1"); + const result = await requirePlatformOperator(asUser("u9")); + expect("response" in result && result.response.status).toBe(403); + }); + + it("refuses everyone when the list is unset, empty or only separators", async () => { + for (const value of [undefined, "", " , "]) { + vi.stubEnv("PLATFORM_OPERATOR_USER_IDS", value); + const result = await requirePlatformOperator(asUser("u1")); + expect("response" in result && result.response.status).toBe(403); + } + }); +}); diff --git a/tests/unit/session-lookup.test.ts b/tests/unit/session-lookup.test.ts index eb0f794..8b9c151 100644 --- a/tests/unit/session-lookup.test.ts +++ b/tests/unit/session-lookup.test.ts @@ -38,6 +38,17 @@ describe("lookupSession", () => { expect(url.hostname).toBe("127.0.0.1"); }); + it("uses PORT, and 3000 when it is unset", async () => { + fetchMock.mockResolvedValue(body({}, { id: "u1" })); + vi.stubEnv("PORT", "8080"); + await lookupSession(new Headers({ cookie: "a=b" })); + vi.stubEnv("PORT", ""); + await lookupSession(new Headers({ cookie: "a=b" })); + + expect(new URL(String(fetchMock.mock.calls[0][0])).port).toBe("8080"); + expect(new URL(String(fetchMock.mock.calls[1][0])).port).toBe("3000"); + }); + it("sends nothing and finds nothing for a request without a cookie", async () => { expect(await lookupSession(new Headers())).toBeNull(); expect(fetchMock).not.toHaveBeenCalled(); diff --git a/tests/unit/snapshot-publish.test.ts b/tests/unit/snapshot-publish.test.ts index d3525b0..3ba710b 100644 --- a/tests/unit/snapshot-publish.test.ts +++ b/tests/unit/snapshot-publish.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { DEFAULT_SNAPSHOT_PARAMS, guardFailure } from "@/lib/snapshot-publish"; +import { DEFAULT_SNAPSHOT_PARAMS, guardFailure, snapshotParamsFromEnv } from "@/lib/snapshot-publish"; const params = { ...DEFAULT_SNAPSHOT_PARAMS, minHostsCovered: 5, minEntryFraction: 0.5 }; const at = (s: number) => new Date(s * 1000); @@ -34,3 +34,27 @@ describe("guardFailure (ADR-0033 decision 3)", () => { expect(guardFailure(params, { ...build, entryCount: 0 }, null)).toBeNull(); }); }); + +describe("snapshotParamsFromEnv", () => { + it("is the defaults when nothing is set", () => { + expect(snapshotParamsFromEnv({})).toEqual(DEFAULT_SNAPSHOT_PARAMS); + }); + + it("takes each SNAPSHOT_* variable, fractions only where the parameter is a rate", () => { + expect( + snapshotParamsFromEnv({ + SNAPSHOT_MIN_HOSTS: "3", + SNAPSHOT_MIN_HOSTS_COVERED: "4", + SNAPSHOT_FALSE_POSITIVE_RATE: "0.001", + SNAPSHOT_MAX_BYTES: "1000", + SNAPSHOT_MAX_ENTRIES: "50", + SNAPSHOT_MIN_ENTRY_FRACTION: "0.9", + }) + ).toEqual({ minHosts: 3, minHostsCovered: 4, falsePositiveRate: 0.001, maxBytes: 1000, maxEntries: 50, minEntryFraction: 0.9 }); + }); + + it("throws on a set value that is wrong, a fraction for a count included", () => { + expect(() => snapshotParamsFromEnv({ SNAPSHOT_MIN_HOSTS: "2.5" })).toThrow("SNAPSHOT_MIN_HOSTS must be a positive integer"); + expect(() => snapshotParamsFromEnv({ SNAPSHOT_MAX_BYTES: "0" })).toThrow("SNAPSHOT_MAX_BYTES"); + }); +}); diff --git a/tests/unit/tenant.test.ts b/tests/unit/tenant.test.ts index 89b7b5d..da91238 100644 --- a/tests/unit/tenant.test.ts +++ b/tests/unit/tenant.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from "vitest"; +import { afterEach, describe, it, expect } from "vitest"; import { NextRequest } from "next/server"; import { AuthenticationError, @@ -6,6 +6,7 @@ import { extractEnrollmentId, getTenantId, getUserId, + verifyProxyAuth, } from "@/lib/tenant"; describe("tenant helpers", () => { @@ -113,3 +114,33 @@ describe("tenant helpers", () => { }); }); }); + +describe("verifyProxyAuth", () => { + const req = (secret?: string) => + new NextRequest("http://localhost/x", { headers: secret === undefined ? {} : { "X-Proxy-Secret": secret } }); + const saved = process.env.NGINX_PROXY_SECRET; + afterEach(() => { + if (saved === undefined) delete process.env.NGINX_PROXY_SECRET; + else process.env.NGINX_PROXY_SECRET = saved; + }); + + it("accepts the configured secret", () => { + process.env.NGINX_PROXY_SECRET = "s3"; + expect(() => verifyProxyAuth(req("s3"))).not.toThrow(); + }); + + it("refuses everything when the secret is unset or empty, an empty header included", () => { + for (const value of [undefined, ""]) { + if (value === undefined) delete process.env.NGINX_PROXY_SECRET; + else process.env.NGINX_PROXY_SECRET = value; + expect(() => verifyProxyAuth(req("s3"))).toThrow("NGINX_PROXY_SECRET not configured"); + expect(() => verifyProxyAuth(req(""))).toThrow("NGINX_PROXY_SECRET not configured"); + } + }); + + it("refuses a wrong or missing header", () => { + process.env.NGINX_PROXY_SECRET = "s3"; + expect(() => verifyProxyAuth(req("nope"))).toThrow("Invalid proxy authentication"); + expect(() => verifyProxyAuth(req())).toThrow("Invalid proxy authentication"); + }); +});