Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 2 additions & 16 deletions app/api/cron/build-snapshots/route.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 } });
Expand Down
9 changes: 6 additions & 3 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion instrumentation-node.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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);
Expand Down
3 changes: 2 additions & 1 deletion lib/cron-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -44,7 +45,7 @@ export function checkCronAuth(
*/
export async function verifyCronRequest(req: NextRequest): Promise<NextResponse | null> {
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":
Expand Down
34 changes: 34 additions & 0 deletions lib/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[should-fix] Number(raw) accepts 0x1F90 (8080) and 1e3 (1000), but the standalone server listens on parseInt(process.env.PORT, 10) || 3000 (3000 and 1). Accept /^\d+$/ only, and add both values to the "throws" test.

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;
}
7 changes: 2 additions & 5 deletions lib/platform-operator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { platformOperatorIds } from "@/lib/env";
import { getUserId } from "@/lib/tenant";

/**
Expand All @@ -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 }),
};
Expand Down
4 changes: 3 additions & 1 deletion lib/session-lookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] Double blank line after the import.

/** What the middleware needs from a session. */
export type LookedUpSession = {
Expand All @@ -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<LookedUpSession | null> {
Expand Down
14 changes: 14 additions & 0 deletions lib/snapshot-publish.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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 };
Expand Down
7 changes: 4 additions & 3 deletions lib/tenant.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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");
}
}
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/cron-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
46 changes: 45 additions & 1 deletion tests/unit/env.test.ts
Original file line number Diff line number Diff line change
@@ -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", () => {
Expand Down Expand Up @@ -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}"`);
}
});
});
15 changes: 15 additions & 0 deletions tests/unit/instrumentation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/platform-operator.test.ts
Original file line number Diff line number Diff line change
@@ -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);
}
});
});
11 changes: 11 additions & 0 deletions tests/unit/session-lookup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
26 changes: 25 additions & 1 deletion tests/unit/snapshot-publish.test.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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");
});
});
Loading
Loading