Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
24 changes: 7 additions & 17 deletions app/api/cron/build-snapshots/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
};
}

Expand Down
2 changes: 1 addition & 1 deletion app/api/cron/prune-prevalence/route.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
2 changes: 1 addition & 1 deletion app/api/cron/write-lake/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand Down
3 changes: 2 additions & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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` |
Expand Down
1 change: 1 addition & 0 deletions docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/security-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions instrumentation-node.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { authTrustedOrigins, type Environment } from "@/lib/env";
import { prisma } from "@/lib/prisma";
import { checkDecoyTable, checkShutdownOwnership, installDecoyShutdownFlush } from "@/lib/decoy";

Expand All @@ -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);
}
}
8 changes: 7 additions & 1 deletion instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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();
}
}
7 changes: 3 additions & 4 deletions lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
11 changes: 0 additions & 11 deletions lib/env-int.ts

This file was deleted.

71 changes: 71 additions & 0 deletions lib/env.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | undefined>;

/**
* 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;
}
2 changes: 1 addition & 1 deletion lib/lake-backlog-case.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down
67 changes: 67 additions & 0 deletions tests/unit/auth-trusted-origins.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading