diff --git a/.changeset/admin-credential-client-ip.md b/.changeset/admin-credential-client-ip.md new file mode 100644 index 00000000..86734d8f --- /dev/null +++ b/.changeset/admin-credential-client-ip.md @@ -0,0 +1,7 @@ +--- +"@reelsaw/server": minor +--- + +Security fixes. An admin's API key made without instance administration, or an MCP connector signed in through OAuth, can no longer restore or permanently delete other accounts' deleted projects and clips, or download instance-wide diagnostics in an issue report; those now need the admin's browser session or a key with instance administration, the same rule the admin tools already followed. + +Sign-in and sign-up limits now key on the address of the connection itself, so a client can no longer pick a new address for each attempt by sending `X-Forwarded-For`, and visitors no longer share one limit when the instance is reached directly. `TRUST_PROXY` now defaults to `false`. **If Reelsaw runs behind a reverse proxy, set `TRUST_PROXY=true`** (the app warns once in its log when a request carries a forwarding header while it is off), and optionally `TRUSTED_PROXIES` to the proxy's address or range so only it may name the client. The installers write `TRUST_PROXY=false`, which fits the port they publish. diff --git a/.env.example b/.env.example index fbc57002..d0cd18e6 100644 --- a/.env.example +++ b/.env.example @@ -80,12 +80,14 @@ SIGNUP_MODE=open # RESEND_API_KEY= # With an email driver: users must click the verification link before they can sign in. The link works for 24 hours and is single-use; an expired one offers a new send. Runtime setting: admins can change it under Settings → System without a restart. # REQUIRE_EMAIL_VERIFICATION=false -# Take the client address from the reverse proxy's header (see TRUSTED_PROXY_HEADER): the Docker deployment sits behind Caddy, so the default is on. false when the app is exposed directly, or the header is whatever the client sent. The address feeds the sign-up cap and the OAuth client-registration limit. -# TRUST_PROXY=true +# true when a reverse proxy (Caddy, nginx, Cloudflare, a platform's edge) sits in front of the app: the client address then comes from the proxy's header (see TRUSTED_PROXY_HEADER, TRUSTED_PROXY_HOPS, TRUSTED_PROXIES). Default false, for an app exposed directly (what the compose files and installers set up): the address is the connection's own, and any forwarding header a client sends is ignored. The address keys the sign-in and sign-up rate limits, the accounts-per-address cap and the OAuth client-registration limit; behind a proxy with this off, every client shares the proxy's address in them (the app warns once when a request carries the header). +# TRUST_PROXY=false # With x-forwarded-for: how many trusted proxies sit in front of the app, each appending the address it saw. The client is the entry that many places from the right, so entries a client prepends are ignored. 1 for Caddy alone, 2 for Cloudflare in front of Caddy. # TRUSTED_PROXY_HOPS=1 # Header that carries the client address when TRUST_PROXY is on: x-forwarded-for (default; Caddy, nginx, most load balancers), cf-connecting-ip (Cloudflare, with the origin closed to everything else) or x-real-ip (Railway, whose edge sets it to the visitor's address). Only the selected header is read, so a client cannot choose its address by sending a different one. (x-forwarded-for | cf-connecting-ip | x-real-ip) # TRUSTED_PROXY_HEADER=x-forwarded-for +# With TRUST_PROXY: the addresses or CIDR ranges of the proxies allowed to name the client, comma-separated (172.16.0.0/12 for a proxy container on a Docker network, 127.0.0.1,::1 for one on the same host). A request from any other address is keyed on its own address and its header ignored, so a client that reaches the app's port around the proxy cannot choose its address. Empty (default) trusts the header from any connection: only safe when the port is reachable through the proxy alone. +# TRUSTED_PROXIES= # Accounts one network address may create per day (sign-up guard). 0 = unlimited. Runtime setting: admins can change it under Settings → System without a restart. # MAX_SIGNUPS_PER_IP_PER_DAY=0 # Refuse sign-ups from known temporary-address domains. Runtime setting: admins can change it under Settings → System without a restart. @@ -372,7 +374,7 @@ CLEANUP_WORKDIR=true # POSTHOG_KEY= # PostHog ingestion host (https://eu.i.posthog.com for the EU cloud, or a self-hosted instance). # POSTHOG_HOST=https://us.i.posthog.com -# true has the web app send PostHog events to the app's own origin at /api/relay, which the server forwards to POSTHOG_HOST (and /static/* to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For, when TRUST_PROXY is on. Default false: the browser talks to POSTHOG_HOST directly. Only used with POSTHOG_KEY. +# true has the web app send PostHog events to the app's own origin at /api/relay, which the server forwards to POSTHOG_HOST (and /static/* to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For (resolved as for the rate limits: see TRUST_PROXY). Default false: the browser talks to POSTHOG_HOST directly. Only used with POSTHOG_KEY. # POSTHOG_PROXY=false # Capture model calls: none, logs (one structured line per call: prompt, response, tokens, latency) or langfuse (a trace per job, a generation per call tagged with its step's prompt version, and, for accounts with learning on, a score per decision about the output on the project's session: clip.kept, clip.found, clip.untouched, clip.bounds_kept, clip.copy_kept, fix.accepted, fix.found); comma-separate for several. A failed call's log line carries errName, statusCode and the provider's errCode beside the error. # LLM_TRACE=none diff --git a/.github/workflows/stack.yml b/.github/workflows/stack.yml index 2570b691..bf8d2aaf 100644 --- a/.github/workflows/stack.yml +++ b/.github/workflows/stack.yml @@ -61,6 +61,8 @@ jobs: echo "OPENAI_API_KEY=mock" echo "AI_MODEL=openai:mock" echo "TRANSCRIPTION_MODEL=openai:whisper-1" + # the tests play the reverse proxy: abuse-stack and signup-rules-stack name each client in X-Forwarded-For + echo "TRUST_PROXY=true" } > .env # the image compose runs (reelsaw:latest), built with buildx so layers come from a cache: pushes # to main write the `stack` scope (PRs can read main's caches, not each other's), and the diff --git a/README.md b/README.md index fe11e5bf..134c5383 100644 --- a/README.md +++ b/README.md @@ -455,8 +455,8 @@ them), so a single-user box stays as it is: - **Bot protection**: `CAPTCHA_PROVIDER` (Cloudflare Turnstile, reCAPTCHA, hCaptcha) with site and secret keys puts a widget on sign-up, sign-in and password reset. - **Free-tier abuse** (all off unless set; `apps/server/src/abuse.ts`): `MAX_SIGNUPS_PER_IP_PER_DAY` - caps accounts per network address (behind a proxy, `TRUST_PROXY` reads `CF-Connecting-IP`, - `X-Real-IP`, `X-Forwarded-For`); `BLOCK_DISPOSABLE_EMAILS` refuses temporary-address domains; one + caps accounts per network address (the connection's, or behind a proxy with `TRUST_PROXY` the one + in `CF-Connecting-IP`, `X-Real-IP` or `X-Forwarded-For`); `BLOCK_DISPOSABLE_EMAILS` refuses temporary-address domains; one account per real mailbox (`john.doe+x@gmail.com` is `johndoe@gmail.com`); `MAX_REQUESTS_PER_MINUTE` / `_HOUR` cap changes (API mutations, MCP tool calls) per account, with plan and per-user overrides like the other quotas. An hourly pass flags accounts that @@ -477,12 +477,17 @@ them), so a single-user box stays as it is: consent page shows the address the approval returns to, registrations are capped at 20 per network address per day, and each person lists and revokes the apps they allowed under Settings → Account → Connected apps. -- **Client address behind a proxy** (`TRUST_PROXY`, `TRUSTED_PROXY_HEADER`, `TRUSTED_PROXY_HOPS`): - the sign-up cap and the registration limit key on the client address. With the default - `x-forwarded-for` it is the entry `TRUSTED_PROXY_HOPS` places from the right (1 behind Caddy, - 2 behind Cloudflare and Caddy), so addresses a client prepends do not count; the other headers - are read only when selected. On Railway set `TRUSTED_PROXY_HEADER=x-real-ip`: its edge puts the - visitor's address there, and the server warns at boot when it is left on `x-forwarded-for`. +- **Client address** (`TRUST_PROXY`, `TRUSTED_PROXY_HEADER`, `TRUSTED_PROXY_HOPS`, `TRUSTED_PROXIES`): + the sign-in and sign-up rate limits, the sign-up cap and the registration limit key on the + client address. By default it is the connection's own address and forwarding headers are + ignored, which is right for the compose files and installers (the app's port is published + directly). Behind a reverse proxy set `TRUST_PROXY=true`: with the default `x-forwarded-for` + the address is the entry `TRUSTED_PROXY_HOPS` places from the right (1 behind Caddy, 2 behind + Cloudflare and Caddy), so addresses a client prepends do not count; the other headers are read + only when selected. `TRUSTED_PROXIES` (addresses or CIDR ranges) limits whose header is + believed, so a client reaching the port around the proxy is keyed on its own address. On + Railway set `TRUSTED_PROXY_HEADER=x-real-ip`: its edge puts the visitor's address there, and + the server warns at boot when it is left on `x-forwarded-for`. ## Billing (enterprise edition) diff --git a/SECURITY.md b/SECURITY.md index ecf27348..72c1adda 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -51,9 +51,12 @@ should follow the update check (Settings → System) or watch releases. keys stored in Settings. - Leave `ALLOW_PRIVATE_SOURCE_URLS` off unless the instance must read from a NAS. - Put the instance behind an HTTPS reverse proxy and keep `TRUST_PROXY` matched to the - deployment (`false` when the app is exposed directly). Set `TRUSTED_PROXY_HOPS` to the number - of proxies in front of the app (2 for Cloudflare in front of Caddy) so the client address is - the entry from the right that your proxies wrote, not one the client sent; use + deployment: `false` (the default) when the app is exposed directly, so rate limits key on the + connection's address and forwarding headers are ignored; `true` behind a proxy, or every client + shares the proxy's address. Set `TRUSTED_PROXY_HOPS` to the number of proxies in front of the + app (2 for Cloudflare in front of Caddy) so the client address is the entry from the right that + your proxies wrote, not one the client sent, and `TRUSTED_PROXIES` to their addresses or ranges + when the app's port is reachable other than through them; use `TRUSTED_PROXY_HEADER=cf-connecting-ip` only when the origin accepts traffic from Cloudflare alone. - Create API keys without "Allow instance administration" unless the agent must change instance settings. OAuth connectors never get admin tools. Connected apps can be revoked under diff --git a/apps/server/scripts/docs-meta.ts b/apps/server/scripts/docs-meta.ts index f1332b3d..afd18ccb 100644 --- a/apps/server/scripts/docs-meta.ts +++ b/apps/server/scripts/docs-meta.ts @@ -79,12 +79,16 @@ export const DOCS: Record = { ], TRUST_PROXY: [ "accounts", - "Take the client address from the reverse proxy's header (see `TRUSTED_PROXY_HEADER`): the Docker deployment sits behind Caddy, so the default is on. `false` when the app is exposed directly, or the header is whatever the client sent. The address feeds the sign-up cap and the OAuth client-registration limit.", + "`true` when a reverse proxy (Caddy, nginx, Cloudflare, a platform's edge) sits in front of the app: the client address then comes from the proxy's header (see `TRUSTED_PROXY_HEADER`, `TRUSTED_PROXY_HOPS`, `TRUSTED_PROXIES`). Default `false`, for an app exposed directly (what the compose files and installers set up): the address is the connection's own, and any forwarding header a client sends is ignored. The address keys the sign-in and sign-up rate limits, the accounts-per-address cap and the OAuth client-registration limit; behind a proxy with this off, every client shares the proxy's address in them (the app warns once when a request carries the header).", ], TRUSTED_PROXY_HEADER: [ "accounts", "Header that carries the client address when `TRUST_PROXY` is on: `x-forwarded-for` (default; Caddy, nginx, most load balancers), `cf-connecting-ip` (Cloudflare, with the origin closed to everything else) or `x-real-ip` (Railway, whose edge sets it to the visitor's address). Only the selected header is read, so a client cannot choose its address by sending a different one.", ], + TRUSTED_PROXIES: [ + "accounts", + "With `TRUST_PROXY`: the addresses or CIDR ranges of the proxies allowed to name the client, comma-separated (`172.16.0.0/12` for a proxy container on a Docker network, `127.0.0.1,::1` for one on the same host). A request from any other address is keyed on its own address and its header ignored, so a client that reaches the app's port around the proxy cannot choose its address. Empty (default) trusts the header from any connection: only safe when the port is reachable through the proxy alone.", + ], TRUSTED_PROXY_HOPS: [ "accounts", "With `x-forwarded-for`: how many trusted proxies sit in front of the app, each appending the address it saw. The client is the entry that many places from the right, so entries a client prepends are ignored. 1 for Caddy alone, 2 for Cloudflare in front of Caddy.", @@ -428,7 +432,7 @@ export const DOCS: Record = { POSTHOG_HOST: ["observability", "PostHog ingestion host (`https://eu.i.posthog.com` for the EU cloud, or a self-hosted instance)."], POSTHOG_PROXY: [ "observability", - "`true` has the web app send PostHog events to the app's own origin at `/api/relay`, which the server forwards to `POSTHOG_HOST` (and `/static/*` to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For, when TRUST_PROXY is on. Default `false`: the browser talks to `POSTHOG_HOST` directly. Only used with `POSTHOG_KEY`.", + "`true` has the web app send PostHog events to the app's own origin at `/api/relay`, which the server forwards to `POSTHOG_HOST` (and `/static/*` to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For (resolved as for the rate limits: see `TRUST_PROXY`). Default `false`: the browser talks to `POSTHOG_HOST` directly. Only used with `POSTHOG_KEY`.", ], FFMPEG_PATH: ["tools", "ffmpeg binary."], diff --git a/apps/server/src/abuse.ts b/apps/server/src/abuse.ts index 74760a5a..d6bc04c4 100644 --- a/apps/server/src/abuse.ts +++ b/apps/server/src/abuse.ts @@ -13,7 +13,10 @@ * * Every refusal is a sentence. Nothing here reads the request body or the video. */ +import { isIP, type BlockList } from "node:net"; import { and, eq, gte, sql } from "drizzle-orm"; +import type { Context } from "hono"; +import { getConnInfo } from "@hono/node-server/conninfo"; import { ACCOUNT_EXISTS_MESSAGE, type AbuseFlag } from "@reelsaw/shared"; import disposable from "disposable-email-domains/index.json" with { type: "json" }; import { schema, type Db } from "./db/index.js"; @@ -24,23 +27,57 @@ import type { Logger } from "./log.js"; import type { Config } from "./config.js"; import { msg } from "@lingui/core/runtime-macro"; import { AppError } from "./i18n.js"; +import { parseTrustedProxies } from "./lib/trusted-proxies.js"; const DISPOSABLE = new Set(disposable); +type ProxyTrust = Pick; + +/** `::ffff:1.2.3.4` (an IPv4 client on a dual-stack socket) as `1.2.3.4`, so one client has one key. */ +function plainAddress(address: string | null | undefined): string | null { + const a = address?.trim(); + if (!a) return null; + return /^::ffff:\d+\.\d+\.\d+\.\d+$/i.test(a) ? a.slice(7) : a; +} + +const proxyLists = new Map(); +/** Whether the connection may name the client: any peer with an empty list, else only one in it (an unknown peer never). */ +function trustedPeer(peer: string | null, list: string): boolean { + if (!list.trim()) return true; + if (!peer) return false; + let parsed = proxyLists.get(list); + if (!parsed) proxyLists.set(list, (parsed = parseTrustedProxies(list))); + return parsed.check(peer, isIP(peer) === 6 ? "ipv6" : "ipv4"); +} + /** - * The client's address. Behind a reverse proxy (Caddy, Cloudflare; TRUST_PROXY=true, the default for the - * Docker deployment) the proxy's headers name it; otherwise they are whatever the client sent, so they are - * ignored and the guard keys on "unknown" (which never counts). + * The client's address. `peer` is the address of the connection itself (`requestPeer`), which nobody can choose. With + * TRUST_PROXY on (a reverse proxy in front: Caddy, nginx, Cloudflare) the proxy's header names the client instead, but + * only on a connection from a proxy in TRUSTED_PROXIES (any peer when that is empty). Otherwise, or when the header is + * missing or shorter than TRUSTED_PROXY_HOPS, it is the peer: never a value the client sent, and never "unknown", so + * every per-address guard keeps working on an install with no proxy. */ -export function clientIp(headers: Headers, trust: Pick): string | null { - if (!trust.TRUST_PROXY) return null; +export function clientIp(headers: Headers, peer: string | null | undefined, trust: ProxyTrust): string | null { + const direct = plainAddress(peer); + if (!trust.TRUST_PROXY) return direct; + if (!trustedPeer(direct, trust.TRUSTED_PROXIES)) return direct; const value = headers.get(trust.TRUSTED_PROXY_HEADER); - if (!value) return null; - if (trust.TRUSTED_PROXY_HEADER !== "x-forwarded-for") return value.trim() || null; + if (!value) return direct; + if (trust.TRUSTED_PROXY_HEADER !== "x-forwarded-for") return plainAddress(value) ?? direct; // each trusted proxy appends the address it saw, so the client is `hops` entries from the right; anything a client // prepends sits to the left of that and is ignored. Fewer entries than hops means the request did not come through them. const entries = value.split(",").map((e) => e.trim()); - return entries[entries.length - trust.TRUSTED_PROXY_HOPS] || null; + return plainAddress(entries[entries.length - trust.TRUSTED_PROXY_HOPS]) ?? direct; +} + +/** The address of the connection a request came in on (Node's socket), or null outside the Node server (app.request in tests). */ +export function requestPeer(c: Context): string | null { + try { + return getConnInfo(c).remote.address ?? null; + } catch { + // no Node bindings on this context (a request made in-process): there is no connection to name + return null; + } } /** diff --git a/apps/server/src/auth.ts b/apps/server/src/auth.ts index 550831dd..b88ff5bb 100644 --- a/apps/server/src/auth.ts +++ b/apps/server/src/auth.ts @@ -41,15 +41,15 @@ export const API_KEY_PREFIX = "rs_"; export const CLIENT_IP_HEADER = "x-reelsaw-client-ip"; /** - * The request as Better Auth should see it: the address resolved the way every other guard resolves it (abuse.ts `clientIp`, - * TRUST_PROXY and the hop count) on CLIENT_IP_HEADER, and whatever the client sent there dropped. Better Auth on its own + * The request as Better Auth should see it: the address resolved the way every other guard resolves it (abuse.ts `clientIp`: + * the connection's address, or the trusted proxy's header) on CLIENT_IP_HEADER, and whatever the client sent there dropped. Better Auth on its own * only trusts a single-value X-Forwarded-For; behind a proxy that appends (Railway, Caddy) it found no address and put every * sign-in in one shared rate-limit bucket, so one noisy client could lock everyone out. */ -export function withClientIp(req: Request, trust: Pick): Request { +export function withClientIp(req: Request, peer: string | null, trust: Parameters[2]): Request { const headers = new Headers(req.headers); headers.delete(CLIENT_IP_HEADER); - const ip = clientIp(req.headers, trust); + const ip = clientIp(req.headers, peer, trust); if (ip) headers.set(CLIENT_IP_HEADER, ip); return new Request(req, { headers }); } @@ -176,8 +176,10 @@ export function createAuth(config: Config, db: Db, email: Email, log: Logger, se // 422, not 403: with email verification on, Better Auth rewrites a 403 from this hook into a fake // success (no session, and the submitted password is not saved). The form looks like the sign-up // worked, and a password manager stores a password that is not the one in the database. + // the address withClientIp resolved for this request (http.ts hands every auth request over through it); none + // for a sign-up made in-process (the CLI), which is not a network client const headers = ctx?.request?.headers ?? ctx?.headers ?? new Headers(); - const ip = clientIp(headers, config); + const ip = headers.get(CLIENT_IP_HEADER); let guard: { emailKey: string; signupIp: string | null }; try { guard = await signupGuard(db, settings.get(), { email: user.email, ip }, log); @@ -349,6 +351,17 @@ export type Requester = { blocked: null | { kind: "pending" | "banned"; reason: string }; }; +/** + * Whether a request acts with the instance-wide authority of an admin: the account is an admin AND the credential may + * administer (`canAdminister`: a browser session, a key with `admin: ["write"]`, never an OAuth connector). The one rule + * every check that reaches past the caller's own account reads (`adminProcedure`, the owner scope of restore and purge, + * report diagnostics, health details); the role alone lets an admin's limited key or connector act as the admin. + * `test/admin-authority.test.ts` fails on a role-only check in the request paths. + */ +export function actsAsAdmin(who: { user: { role?: string | null }; canAdminister: boolean }): boolean { + return who.user.role === "admin" && who.canAdminister; +} + export function bearerToken(headers: Headers): string | null { const h = headers.get("authorization"); if (h && /^bearer\s+/i.test(h)) return h.replace(/^bearer\s+/i, "").trim(); diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index 31c5c21b..078a5ba8 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -2430,7 +2430,7 @@ ${usage}`); } if (!user) throw new Error(t(msg`no account`)); // docker exec is operator access: --instance is always allowed - const actor = instance ? { id: user.id, role: "admin" as const } : { id: user.id, role: user.role }; + const actor = { user: instance ? { id: user.id, role: "admin" as const } : { id: user.id, role: user.role }, canAdminister: true }; const zip = await createReportZip(svc, actor, projectId, { description, clipIds: [], diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index b0dd2f3a..3516a6a9 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -3,6 +3,7 @@ import path from "node:path"; import { fontFamilySchema } from "@reelsaw/shared"; import { parseLogLevels } from "./log.js"; import { parseYtdlpProxies } from "./ytdlp-proxy.js"; +import { parseTrustedProxies } from "./lib/trusted-proxies.js"; import { bundledAssetPath } from "./lib/assets.js"; import { OPENCODE_DEFAULT_BASE_URL } from "./ai/provider-ids.js"; @@ -83,12 +84,14 @@ export const envSchema = z.object({ RESEND_API_KEY: z.string().optional(), /** With an email driver: users must click the verification link before they can sign in. */ REQUIRE_EMAIL_VERIFICATION: boolFalse, - /** Behind a reverse proxy (Caddy, Cloudflare; the Docker deployment), the client address comes from its headers. false = ignore them (exposed directly). */ - TRUST_PROXY: boolTrue, + /** A reverse proxy sits in front (Caddy, nginx, Cloudflare): the client address comes from its header. Off (the default) = the connection's own address (exposed directly). */ + TRUST_PROXY: boolFalse, /** With TRUST_PROXY and X-Forwarded-For: how many proxies in front of the app append to it. The client is the entry that many from the right. */ TRUSTED_PROXY_HOPS: z.coerce.number().int().min(1).max(10).default(1), /** Which header names the client address behind the proxy. */ TRUSTED_PROXY_HEADER: z.enum(["x-forwarded-for", "cf-connecting-ip", "x-real-ip"]).default("x-forwarded-for"), + /** With TRUST_PROXY: the proxies' addresses or CIDR ranges, comma-separated; a request from anywhere else is keyed on its own address. Empty = any. */ + TRUSTED_PROXIES: z.string().default(""), /** Sign-up guards (abuse.ts); 0 / false = off. Runtime settings. */ MAX_SIGNUPS_PER_IP_PER_DAY: z.coerce.number().int().min(0).default(0), BLOCK_DISPOSABLE_EMAILS: boolFalse, @@ -388,6 +391,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { if (c.NODE_ENV === "production" && c.BETTER_AUTH_SECRET.length < 32) throw new ConfigError("BETTER_AUTH_SECRET must be at least 32 characters in production"); try { if (c.YTDLP_PROXY) parseYtdlpProxies(c.YTDLP_PROXY); + parseTrustedProxies(c.TRUSTED_PROXIES); } catch (err) { throw new ConfigError(err instanceof Error ? err.message : String(err)); } diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index e92503d3..104c2c78 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -26,11 +26,11 @@ import { ensureBumperThumb } from "./pipeline/bumpers.js"; import { DEFAULT_BUNDLED_DIR } from "./library/catalog.js"; import { createExportZip, exportPlan, parseClipIds } from "./export.js"; import { LINK_NOT_FOUND, recordUse, resolveToken } from "./media-links/service.js"; -import { requester, activeRequester, bearerToken, cannotUseApp, mcpResource, withClientIp, API_KEY_PREFIX } from "./auth.js"; +import { requester, activeRequester, actsAsAdmin, bearerToken, cannotUseApp, mcpResource, withClientIp, API_KEY_PREFIX } from "./auth.js"; import { gateEmailVerification } from "./email-verify.js"; import { requireMcpAuth } from "@better-auth/mcp"; import { handleMcp } from "./mcp.js"; -import { clientIp, WindowCounter } from "./abuse.js"; +import { clientIp, requestPeer, WindowCounter } from "./abuse.js"; import { createReportZip, reportCapabilities, reportPreview } from "./report/bundle.js"; import { EMAIL_TOPICS, isEmailTopic, reportRequestSchema, TEXT_FONTS } from "@reelsaw/shared"; import { execFile } from "node:child_process"; @@ -86,6 +86,16 @@ export function createApp(svc: Services) { app.use(requestLogger(svc.log)); // every request renders its messages in one locale: the web app's header, the account's, Accept-Language, English (i18n.ts) app.use(localeMiddleware()); + // TRUST_PROXY is off (the default) and a request names a client in the proxy header: behind a proxy that relied on the + // old default, every client now shares the proxy's address in the per-address limits. Said once per process. + let proxyHeaderSeen = config.TRUST_PROXY; + app.use(async (c, next) => { + if (!proxyHeaderSeen && c.req.header(config.TRUSTED_PROXY_HEADER)) { + proxyHeaderSeen = true; + c.get("log").warn({ header: config.TRUSTED_PROXY_HEADER, peer: requestPeer(c) }, "proxy header ignored: TRUST_PROXY is off"); + } + await next(); + }); // The built SPA's id (hash of its index.html). Every API response carries it, and the page carries // the one it was served from, so a tab left open across a deploy notices and reloads on its next // route change instead of asking for chunks that are gone (apps/web/src/lib/stale-chunk.ts). @@ -152,7 +162,7 @@ export function createApp(svc: Services) { app.get("/api/health", async (c) => { const open = svc.settings.get().HEALTH_DETAILS; const who = open ? null : await activeRequester(auth, db, c.req.raw.headers); - const details = open || who?.user.role === "admin"; + const details = open || (!!who && actsAsAdmin(who)); const { ok, checks } = await runHealthChecks(svc); return c.json({ ok, checks, ...version, ...(details ? { resources: await svc.resources.snapshot() } : {}) }, ok ? 200 : 503); }); @@ -202,7 +212,7 @@ export function createApp(svc: Services) { const registrations = new WindowCounter(20); app.on(["GET", "POST"], "/api/auth/*", async (c) => { if (config.MCP_OAUTH && c.req.method === "POST" && c.req.path === "/api/auth/oauth2/register") { - const ip = clientIp(c.req.raw.headers, config); + const ip = clientIp(c.req.raw.headers, requestPeer(c), config); if (ip && !registrations.hit(ip)) { c.get("log").warn({ ip }, "oauth client registration refused: too many from this address today"); return c.json({ error: "too_many_requests", error_description: "Too many apps were registered from this network today. Try again tomorrow." }, 429); @@ -218,7 +228,7 @@ export function createApp(svc: Services) { return c.redirect(`${to.pathname}${to.search}`); } } - const res = await auth.handler(withClientIp(c.req.raw, config)); + const res = await auth.handler(withClientIp(c.req.raw, requestPeer(c), config)); logAuth(c, res.status); return res; }); @@ -265,7 +275,7 @@ export function createApp(svc: Services) { }; // OAuth discovery lives at the origin root (RFC 8414 / 9728). The plugin matches the request's // own pathname (root well-known paths, with the resource path suffix), so the raw request goes through. - if (config.MCP_OAUTH) app.get("/.well-known/*", (c) => auth.handler(withClientIp(c.req.raw, config))); + if (config.MCP_OAUTH) app.get("/.well-known/*", (c) => auth.handler(withClientIp(c.req.raw, requestPeer(c), config))); // Stripe webhooks (ee): raw body (bounded: events are a few hundred KB at most, and the signature is checked only after // the body is read), 2xx only once the event and its sync job committed if (svc.ee) app.post("/api/billing/webhook", bodyLimit({ maxSize: 1024 * 1024 }), (c) => svc.ee!.webhook(c)); @@ -704,7 +714,7 @@ export function createApp(svc: Services) { app.get("/api/projects/:projectId/report/preview", async (c) => { const session = await actor(c); if (!session) return c.json({ error: "unauthorized" }, 401); - const caps = reportCapabilities(svc, session.user); + const caps = reportCapabilities(svc, session); if (!caps.zip) return c.json({ error: "Send feedback from the app instead of downloading a report on this instance." }, 403); const info = await reportPreview(svc, session.user.id, c.req.param("projectId")); return info ? c.json(info) : c.json({ error: "not found" }, 404); @@ -732,11 +742,11 @@ export function createApp(svc: Services) { const sendReport = async (c: Context, projectId: string | null) => { const session = await actor(c); if (!session) return c.json({ error: "unauthorized" }, 401); - const caps = reportCapabilities(svc, session.user); + const caps = reportCapabilities(svc, session); if (!caps.zip) return c.json({ error: "Send feedback from the app instead of downloading a report on this instance." }, 403); const parsed = c.req.method === "GET" ? reportFromQuery(c) : reportRequestSchema.safeParse(await c.req.json().catch(() => null)); if (!parsed.success) return c.json({ error: parsed.error.issues[0]?.message ?? "invalid report" }, 400); - const zip = await createReportZip(svc, session.user, projectId, parsed.data); + const zip = await createReportZip(svc, session, projectId, parsed.data); if (!zip) return c.json({ error: "not found" }, 404); c.header("Content-Type", "application/zip"); c.header("Content-Disposition", `attachment; filename="${zip.filename}"`); diff --git a/apps/server/src/lib/trusted-proxies.ts b/apps/server/src/lib/trusted-proxies.ts new file mode 100644 index 00000000..cf2382d3 --- /dev/null +++ b/apps/server/src/lib/trusted-proxies.ts @@ -0,0 +1,22 @@ +import { BlockList, isIP } from "node:net"; + +/** + * TRUSTED_PROXIES (config.ts) as a list `node:net` can match: comma-separated addresses ("::1") and CIDR ranges + * ("172.16.0.0/12"). Throws on an entry that is neither, so a typo fails at boot instead of trusting nobody. + */ +export function parseTrustedProxies(list: string): BlockList { + const out = new BlockList(); + for (const raw of list.split(",")) { + const entry = raw.trim(); + if (!entry) continue; + const m = /^([^/]+)(?:\/(\d{1,3}))?$/.exec(entry); + const family = m?.[1] ? isIP(m[1]) : 0; + const prefix = m?.[2] === undefined ? null : Number(m[2]); + if (!m?.[1] || !family || (prefix !== null && prefix > (family === 4 ? 32 : 128))) + throw new Error(`TRUSTED_PROXIES: "${entry}" is not an IP address or a CIDR range`); + const type = family === 4 ? "ipv4" : "ipv6"; + if (prefix === null) out.addAddress(m[1], type); + else out.addSubnet(m[1], prefix, type); + } + return out; +} diff --git a/apps/server/src/mcp.ts b/apps/server/src/mcp.ts index 1d970d32..d8af03a9 100644 --- a/apps/server/src/mcp.ts +++ b/apps/server/src/mcp.ts @@ -583,13 +583,13 @@ export function createMcpServer( server.registerTool("report_issue", TOOLS.report_issue, ({ description, projectId, clipIds, instance, logs, system, previews, allClips, source }) => run(async () => { - const caps = reportCapabilities(svc, user); + const caps = reportCapabilities(svc, { user, canAdminister: access.canAdminister }); if (!caps.zip) throw new AppError( "FORBIDDEN", msg({ id: "mcp.report_issue.no_zip", message: "Send feedback from the app instead of downloading a report on this instance." }), ); - if (instance && !(caps.instance && access.canAdminister)) + if (instance && !caps.instance) throw new AppError("FORBIDDEN", msg({ id: "mcp.report_issue.admins_only", message: "Instance-wide diagnostics are for admins." })); if (projectId) await api.projects.get({ id: projectId }); const q = new URLSearchParams({ description }); diff --git a/apps/server/src/posthog-proxy.ts b/apps/server/src/posthog-proxy.ts index 4ab8914c..0e6af719 100644 --- a/apps/server/src/posthog-proxy.ts +++ b/apps/server/src/posthog-proxy.ts @@ -6,11 +6,11 @@ * to the ingestion host. * * Only what PostHog needs goes upstream: no cookie (the session cookie stays here), no authorization header. The - * client address goes as X-Forwarded-For so PostHog's GeoIP sees the visitor rather than this server, and only - * when TRUST_PROXY says the address is real (abuse.ts#clientIp). + * client address goes as X-Forwarded-For so PostHog's GeoIP sees the visitor rather than this server: the connection's + * address, or the trusted proxy's header (abuse.ts#clientIp). */ import type { Context } from "hono"; -import { clientIp } from "./abuse.js"; +import { clientIp, requestPeer } from "./abuse.js"; import type { Config } from "./config.js"; export const POSTHOG_PROXY_PATH = "/api/relay"; @@ -47,7 +47,7 @@ export function upstreamUrl(requestUrl: string, proxyPath: string, host: string) return `${base}${rest}${url.search}`; } -export function posthogProxy(config: Pick) { +export function posthogProxy(config: Pick & Parameters[2]) { return async (c: Context) => { const target = upstreamUrl(c.req.url, POSTHOG_PROXY_PATH, config.POSTHOG_HOST); if (!target) return c.notFound(); @@ -56,7 +56,7 @@ export function posthogProxy(config: Pick { const db = svc.database.db; - const caps = reportCapabilities(svc, user); + const user = who.user; + const caps = reportCapabilities(svc, who); if (!caps.zip) return null; const include = applyReportInclude(caps, req.include); const reqSafe = { ...req, include }; diff --git a/apps/server/src/report/capabilities.ts b/apps/server/src/report/capabilities.ts index 244cd867..105e7ae6 100644 --- a/apps/server/src/report/capabilities.ts +++ b/apps/server/src/report/capabilities.ts @@ -6,7 +6,7 @@ */ import type { ReportInclude } from "@reelsaw/shared"; import type { Services } from "../services.js"; -import type { UserRole } from "../db/schema.js"; +import { actsAsAdmin } from "../auth.js"; export type ReportCapabilities = { /** download a zip of own project/account data */ @@ -19,9 +19,10 @@ export type ReportCapabilities = { feedback: boolean; }; -export function reportCapabilities(svc: Pick, user: { role: UserRole }): ReportCapabilities { +/** `who`: the account and whether its credential may administer; an admin's limited key or connector reports as a non-admin. */ +export function reportCapabilities(svc: Pick, who: Parameters[0]): ReportCapabilities { const hosted = !!svc.ee; - const admin = user.role === "admin"; + const admin = actsAsAdmin(who); const feedback = svc.telemetry.enabled.sentry || svc.telemetry.enabled.posthog; // hosted + telemetry: normal users send feedback only; self-host and admins keep the zip const zip = !hosted || admin || !feedback; diff --git a/apps/server/src/trpc/context.ts b/apps/server/src/trpc/context.ts index f156699c..07b5025c 100644 --- a/apps/server/src/trpc/context.ts +++ b/apps/server/src/trpc/context.ts @@ -78,6 +78,7 @@ export const protectedProcedure = signedInProcedure.use(async ({ ctx, next, type }); export const adminProcedure = protectedProcedure.use(({ ctx, next }) => { + // role-ok: the role half of actsAsAdmin, checked apart so each refusal says what is missing if (ctx.user.role !== "admin") throw new AppError("FORBIDDEN", msg({ id: "auth.admins_only", message: "Admins only" })); // an API key or OAuth connector acts as its admin only when it was allowed to (auth.ts, README "MCP") if (!ctx.who.canAdminister) throw new AppError("FORBIDDEN", ADMIN_REFUSED); diff --git a/apps/server/src/trpc/router.ts b/apps/server/src/trpc/router.ts index 1db4d12e..b5c7d94b 100644 --- a/apps/server/src/trpc/router.ts +++ b/apps/server/src/trpc/router.ts @@ -7,6 +7,7 @@ import type { AnyPgColumn } from "drizzle-orm/pg-core"; import { randomUUID } from "node:crypto"; import { TRPCError, tracked } from "@trpc/server"; import { router, mergeRouters, protectedProcedure, publicProcedure, signedInProcedure, adminProcedure } from "./context.js"; +import { actsAsAdmin, type Requester } from "../auth.js"; import { mediaLinksRouter, webhooksRouter } from "./integrations.js"; import { approveUser, @@ -455,7 +456,8 @@ function ownedProject(db: Db, userId: string, projectId: string) { return findProject(db, { id: userId, admin: false }, projectId, { deleted: false }); } -const actorOf = (user: { id: string; role?: string | null }): { id: string; admin: boolean } => ({ id: user.id, admin: user.role === "admin" }); +/** The owner scope for a service call: an admin reaches other accounts' items only with a credential that may administer (auth.ts `actsAsAdmin`). */ +const actorOf = (who: Requester): { id: string; admin: boolean } => ({ id: who.user.id, admin: actsAsAdmin(who) }); /** The billing service, or the sentence a self-hosted instance answers with. */ function billingOf(svc: Services) { if (!svc.ee) @@ -532,7 +534,7 @@ const headRouter = router({ /** which enterprise features this instance runs (ee/); the web shows the Billing tab from this */ ee: { billing: !!ctx.svc.ee }, /** zip vs Sentry/PostHog feedback for "Report an issue" (report/capabilities.ts) */ - report: reportCapabilities(ctx.svc, ctx.user), + report: reportCapabilities(ctx.svc, ctx.who), /** whether this account's next render carries the watermark, and why (instance, plan, an admin's choice) */ watermark: ctx.who.blocked ? null : await watermarkFor(ctx.svc.database.db, s, ctx.user, ctx.svc.entitlements), /** how tall this account's links are downloaded (null = full quality) and the plan that lifts the cap */ @@ -607,6 +609,7 @@ const headRouter = router({ .mutation(async ({ ctx, input }) => { if (ctx.who.via !== "session") throw new AppError("FORBIDDEN", msg({ id: "api_key.create_in_browser", message: "Create keys from the Settings page after signing in." })); + // role-ok: a browser session (checked above) may administer; this asks whether the account itself is an admin if (input.admin && ctx.user.role !== "admin") throw new AppError("FORBIDDEN", msg({ id: "api_key.admin_only", message: "Only admins can create a key that administers the instance." })); const created = await ctx.svc.auth.api.createApiKey({ @@ -971,7 +974,7 @@ const restRouter = router({ * the uploaded ones (`admin.fonts`). The same code serves `list_fonts` / `add_font` / `remove_fonts` and `reelsaw fonts`. */ fonts: router({ - list: protectedProcedure.query(({ ctx }) => listFonts(ctx.svc, { admin: ctx.user.role === "admin" })), + list: protectedProcedure.query(({ ctx }) => listFonts(ctx.svc, { admin: actsAsAdmin(ctx.who) })), }), /** * The spoken languages the transcription model in force takes (ai/spoken-languages.ts), each with what Reelsaw does @@ -1406,10 +1409,10 @@ const restRouter = router({ list: protectedProcedure.query(({ ctx }) => listDeleted(ctx.svc, ctx.user.id)), restore: protectedProcedure .input(z.object({ items: z.array(deletedItemRefSchema).min(1).max(200) })) - .mutation(({ ctx, input }) => restoreDeleted(ctx.svc, actorOf(ctx.user), input.items)), + .mutation(({ ctx, input }) => restoreDeleted(ctx.svc, actorOf(ctx.who), input.items)), purge: protectedProcedure .input(z.object({ items: z.array(deletedItemRefSchema).min(1).max(200), forgetDecisions: z.boolean().default(false) })) - .mutation(({ ctx, input }) => purgeDeleted(ctx.svc, actorOf(ctx.user), input.items, { forgetDecisions: input.forgetDecisions })), + .mutation(({ ctx, input }) => purgeDeleted(ctx.svc, actorOf(ctx.who), input.items, { forgetDecisions: input.forgetDecisions })), }), /** @@ -1717,7 +1720,7 @@ const restRouter = router({ .mutation(({ ctx, input }) => rerenderProjects(ctx.svc, { id: ctx.user.id, admin: false }, input.ids)), /** Undo a delete (the owner, or an admin for anyone's project). */ - restore: protectedProcedure.input(z.object({ id: z.string() })).mutation(({ ctx, input }) => restoreProject(ctx.svc, actorOf(ctx.user), input.id)), + restore: protectedProcedure.input(z.object({ id: z.string() })).mutation(({ ctx, input }) => restoreProject(ctx.svc, actorOf(ctx.who), input.id)), /** Remove a deleted project for good: files go, storage is freed. Minutes already used stay counted. */ purge: protectedProcedure @@ -1990,10 +1993,10 @@ const restRouter = router({ .mutation(({ ctx, input }) => deleteClips(ctx.svc, { id: ctx.user.id, admin: false }, input.projectId, input.clipIds)), /** Bring back a deleted clip or one a re-analyze replaced (listed as replacedClips on projects.get). */ - restore: protectedProcedure.input(z.object({ id: z.string() })).mutation(({ ctx, input }) => restoreClip(ctx.svc, actorOf(ctx.user), input.id)), + restore: protectedProcedure.input(z.object({ id: z.string() })).mutation(({ ctx, input }) => restoreClip(ctx.svc, actorOf(ctx.who), input.id)), /** Remove an already-deleted clip of a live project for good so its render is freed. */ - purge: protectedProcedure.input(z.object({ id: z.string() })).mutation(({ ctx, input }) => purgeOwnedClip(ctx.svc, actorOf(ctx.user), input.id)), + purge: protectedProcedure.input(z.object({ id: z.string() })).mutation(({ ctx, input }) => purgeOwnedClip(ctx.svc, actorOf(ctx.who), input.id)), /** * Re-render several clips of a project at once (the selection bar, "Retry failed"). One transaction, one run: diff --git a/apps/server/test/abuse-stack.test.ts b/apps/server/test/abuse-stack.test.ts index e09f663d..28905e12 100644 --- a/apps/server/test/abuse-stack.test.ts +++ b/apps/server/test/abuse-stack.test.ts @@ -20,7 +20,7 @@ async function trpc(cookie: string, path: string, input?: unknown, method: "GET" const body = (await res.json()) as { result?: { data: unknown }; error?: { message: string; data: { code: string } } }; return { status: res.status, data: body.result?.data as never, error: body.error }; } -/** A raw sign-up attempt from a given (proxied) address; returns the status and the server's sentence. */ +/** A raw sign-up attempt from a given (proxied) address: the app must run with TRUST_PROXY=true (stack.yml sets it); returns the status and the server's sentence. */ const trySignup = (email: string, ip: string) => postSignUp({ email, password: `pw-${randomUUID()}`, name: "Guard" }, { "x-forwarded-for": ip }); describe("abuse guards", () => { diff --git a/apps/server/test/abuse.test.ts b/apps/server/test/abuse.test.ts index 34729d26..a97b5fe3 100644 --- a/apps/server/test/abuse.test.ts +++ b/apps/server/test/abuse.test.ts @@ -2,32 +2,53 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; import { clientIp, WindowCounter, emailKey, isDisposable, emailDomain } from "../src/abuse.js"; +import { parseTrustedProxies } from "../src/lib/trusted-proxies.js"; import { CLIENT_IP_HEADER, withClientIp } from "../src/auth.js"; -const trust = (over: Partial[1]> = {}): Parameters[1] => ({ +const trust = (over: Partial[2]> = {}): Parameters[2] => ({ TRUST_PROXY: true, TRUSTED_PROXY_HEADER: "x-forwarded-for", TRUSTED_PROXY_HOPS: 1, + TRUSTED_PROXIES: "", ...over, }); +/** the connection's own address: a proxy on a Docker network, or the client itself with no proxy */ +const PEER = "172.18.0.5"; describe("clientIp", () => { it("takes the X-Forwarded-For entry `hops` from the right, so entries a client prepends are ignored", () => { - assert.equal(clientIp(new Headers({ "x-forwarded-for": "9.9.9.9, 6.6.6.6, 2.2.2.2" }), trust()), "2.2.2.2"); - assert.equal(clientIp(new Headers({ "x-forwarded-for": "2.2.2.2" }), trust()), "2.2.2.2"); - assert.equal(clientIp(new Headers({ "x-forwarded-for": " 9.9.9.9 , 2.2.2.2 , 3.3.3.3" }), trust({ TRUSTED_PROXY_HOPS: 2 })), "2.2.2.2"); - assert.equal(clientIp(new Headers({ "x-forwarded-for": "2.2.2.2" }), trust({ TRUSTED_PROXY_HOPS: 2 })), null); + assert.equal(clientIp(new Headers({ "x-forwarded-for": "9.9.9.9, 6.6.6.6, 2.2.2.2" }), PEER, trust()), "2.2.2.2"); + assert.equal(clientIp(new Headers({ "x-forwarded-for": "2.2.2.2" }), PEER, trust()), "2.2.2.2"); + assert.equal(clientIp(new Headers({ "x-forwarded-for": " 9.9.9.9 , 2.2.2.2 , 3.3.3.3" }), PEER, trust({ TRUSTED_PROXY_HOPS: 2 })), "2.2.2.2"); + // fewer entries than proxies: it did not come through them all, so the connection is all that is known + assert.equal(clientIp(new Headers({ "x-forwarded-for": "2.2.2.2" }), PEER, trust({ TRUSTED_PROXY_HOPS: 2 })), PEER); }); it("reads only the selected header", () => { const h = new Headers({ "cf-connecting-ip": "1.1.1.1", "x-real-ip": "4.4.4.4", "x-forwarded-for": "2.2.2.2" }); - assert.equal(clientIp(h, trust()), "2.2.2.2"); - assert.equal(clientIp(h, trust({ TRUSTED_PROXY_HEADER: "cf-connecting-ip" })), "1.1.1.1"); - assert.equal(clientIp(h, trust({ TRUSTED_PROXY_HEADER: "x-real-ip" })), "4.4.4.4"); - assert.equal(clientIp(new Headers({ "cf-connecting-ip": "1.1.1.1" }), trust()), null); + assert.equal(clientIp(h, PEER, trust()), "2.2.2.2"); + assert.equal(clientIp(h, PEER, trust({ TRUSTED_PROXY_HEADER: "cf-connecting-ip" })), "1.1.1.1"); + assert.equal(clientIp(h, PEER, trust({ TRUSTED_PROXY_HEADER: "x-real-ip" })), "4.4.4.4"); + assert.equal(clientIp(new Headers({ "cf-connecting-ip": "1.1.1.1" }), PEER, trust()), PEER); }); - it("is null when the proxy is not trusted or the header is missing", () => { - assert.equal(clientIp(new Headers({ "x-forwarded-for": "2.2.2.2" }), trust({ TRUST_PROXY: false })), null); - assert.equal(clientIp(new Headers(), trust()), null); + it("without a trusted proxy it is the connection's address, whatever the client sends", () => { + const off = trust({ TRUST_PROXY: false }); + assert.equal(clientIp(new Headers({ "x-forwarded-for": "2.2.2.2" }), "198.51.100.7", off), "198.51.100.7"); + assert.equal(clientIp(new Headers({ "x-forwarded-for": "6.6.6.6" }), "198.51.100.7", off), "198.51.100.7", "a new header is not a new address"); + assert.equal(clientIp(new Headers(), "::ffff:198.51.100.7", off), "198.51.100.7", "an IPv4 client on a dual-stack socket"); + assert.equal(clientIp(new Headers(), PEER, trust()), PEER, "header missing behind a proxy"); + assert.equal(clientIp(new Headers({ "x-forwarded-for": "2.2.2.2" }), null, off), null, "no connection (in-process)"); + }); + it("with TRUSTED_PROXIES, honours the header only on a connection from one of them", () => { + const listed = trust({ TRUSTED_PROXIES: "172.16.0.0/12, ::1" }); + const h = new Headers({ "x-forwarded-for": "2.2.2.2" }); + assert.equal(clientIp(h, PEER, listed), "2.2.2.2"); + assert.equal(clientIp(h, "::1", listed), "2.2.2.2"); + assert.equal(clientIp(h, "198.51.100.7", listed), "198.51.100.7", "around the proxy: its own address"); + assert.equal(clientIp(h, null, listed), null, "an unknown peer is not a listed proxy"); + }); + it("refuses a TRUSTED_PROXIES entry that is not an address or a range", () => { + assert.doesNotThrow(() => parseTrustedProxies("10.0.0.0/8, 192.168.1.10, fd00::/8, ::1")); + for (const bad of ["10.0.0.0/33", "proxy.local", "10.0.0.0/", "1.2.3.4/8/9"]) assert.throws(() => parseTrustedProxies(bad), /TRUSTED_PROXIES/, bad); }); }); @@ -35,16 +56,18 @@ describe("withClientIp (the address Better Auth rate-limits on)", () => { const post = (headers: Record) => new Request("http://app.test/api/auth/sign-in/email", { method: "POST", headers, body: JSON.stringify({ email: "a@b.test" }) }); it("hands Better Auth the resolved address from a multi-hop X-Forwarded-For, and keeps the body", async () => { - const r = withClientIp(post({ "x-forwarded-for": "9.9.9.9, 2.2.2.2", "content-type": "application/json" }), trust()); + const r = withClientIp(post({ "x-forwarded-for": "9.9.9.9, 2.2.2.2", "content-type": "application/json" }), PEER, trust()); assert.equal(r.headers.get(CLIENT_IP_HEADER), "2.2.2.2"); assert.deepEqual(await r.json(), { email: "a@b.test" }); }); - it("drops a client-sent value, and sends none when the proxy is not trusted", () => { - assert.equal(withClientIp(post({ [CLIENT_IP_HEADER]: "6.6.6.6", "x-forwarded-for": "2.2.2.2" }), trust()).headers.get(CLIENT_IP_HEADER), "2.2.2.2"); - assert.equal( - withClientIp(post({ [CLIENT_IP_HEADER]: "6.6.6.6", "x-forwarded-for": "2.2.2.2" }), trust({ TRUST_PROXY: false })).headers.get(CLIENT_IP_HEADER), - null, - ); + it("drops a client-sent value, and sends the connection's address when the proxy is not trusted", () => { + assert.equal(withClientIp(post({ [CLIENT_IP_HEADER]: "6.6.6.6", "x-forwarded-for": "2.2.2.2" }), PEER, trust()).headers.get(CLIENT_IP_HEADER), "2.2.2.2"); + const direct = trust({ TRUST_PROXY: false }); + // two sign-in attempts with different forwarded values from one connection share one rate-limit key + const a = withClientIp(post({ [CLIENT_IP_HEADER]: "6.6.6.6", "x-forwarded-for": "2.2.2.2" }), "198.51.100.7", direct); + const b = withClientIp(post({ "x-forwarded-for": "3.3.3.3" }), "198.51.100.7", direct); + assert.equal(a.headers.get(CLIENT_IP_HEADER), "198.51.100.7"); + assert.equal(b.headers.get(CLIENT_IP_HEADER), "198.51.100.7"); }); }); diff --git a/apps/server/test/admin-authority-stack.test.ts b/apps/server/test/admin-authority-stack.test.ts new file mode 100644 index 00000000..85a34ee4 --- /dev/null +++ b/apps/server/test/admin-authority-stack.test.ts @@ -0,0 +1,84 @@ +/** + * An admin's limited credential (an API key without instance administration, an MCP/OAuth connector) acts as an + * ordinary account: restoring or purging someone else's deleted project or clip is NOT_FOUND through it, while the + * admin's own browser session still can (auth.ts `actsAsAdmin`). The procedures run in-process through the real router + * against Postgres, the same way MCP tools reach them (mcp.ts builds its caller with the credential's `canAdminister`). + * + * Needs only Postgres (lifecycle-harness.ts; TEST_DATABASE_URL pointing at a migrated database). + */ +import { after, before, describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { eq } from "drizzle-orm"; +import { appRouter } from "../src/trpc/router.js"; +import { schema } from "../src/db/index.js"; +import { lifecycleHarness } from "./lifecycle-harness.js"; + +const h = lifecycleHarness(); +let skip: string | null = null; + +describe("admin authority needs a credential that may administer", () => { + let adminId: string; + let victimId: string; + before(async () => { + skip = await h.ready(); + if (skip) return; + adminId = await h.makeUser(); + victimId = await h.makeUser(); + await h.pool.query(`update "user" set role = 'admin', approved_at = now() where id = $1`, [adminId]); + await h.pool.query(`update "user" set approved_at = now() where id = $1`, [victimId]); + }); + after(() => h.cleanup()); + + const as = async (via: "session" | "apikey" | "oauth", canAdminister: boolean) => { + const user = await h.svc.database.db.query.user.findFirst({ where: eq(schema.user.id, adminId) }); + assert.ok(user); + return appRouter.createCaller({ + svc: { ...h.svc, entitlements: null }, + who: { user, via, canAdminister, session: null, blocked: null } as never, + req: new Request("http://test.local"), + requestId: "test", + log: h.svc.log, + }); + }; + const deletedProject = async () => { + const id = await h.makeProject(victimId, "done"); + await h.pool.query(`update projects set deleted_at = now() where id = $1`, [id]); + return id; + }; + const exists = async (id: string) => (await h.pool.query(`select deleted_at from projects where id = $1`, [id])).rows[0]; + + it("a key without instance administration cannot purge or restore another account's deleted project", async (t) => { + if (skip) return t.skip(skip); + const id = await deletedProject(); + const api = await as("apikey", false); + const notFound = (e: { code?: string }) => e.code === "NOT_FOUND"; + // a selection where every item fails answers with the first item's error (lib/each.ts) + await assert.rejects(api.deleted.purge({ items: [{ kind: "project", id }] }), notFound); + assert.ok(await exists(id), "the project is still there"); + await assert.rejects(api.deleted.restore({ items: [{ kind: "project", id }] }), notFound); + await assert.rejects(api.projects.restore({ id }), notFound); + assert.ok((await exists(id))?.deleted_at, "still deleted"); + }); + + it("an OAuth connector cannot purge or restore another account's deleted clip", async (t) => { + if (skip) return t.skip(skip); + const projectId = await h.makeProject(victimId, "done"); + const clipId = await h.makeClip(projectId, 1, "done"); + await h.pool.query(`update clips set deleted_at = now() where id = $1`, [clipId]); + const api = await as("oauth", false); + const notFound = (e: { code?: string }) => e.code === "NOT_FOUND"; + await assert.rejects(api.clips.purge({ id: clipId }), notFound); + await assert.rejects(api.clips.restore({ id: clipId }), notFound); + const row = (await h.pool.query(`select deleted_at from clips where id = $1`, [clipId])).rows[0]; + assert.ok(row?.deleted_at, "the clip is still there and still deleted"); + }); + + it("the admin's own session still restores another account's project", async (t) => { + if (skip) return t.skip(skip); + const id = await deletedProject(); + const api = await as("session", true); + const r = await api.projects.restore({ id }); + assert.equal(r.changed, true); + assert.equal((await exists(id))?.deleted_at, null); + }); +}); diff --git a/apps/server/test/admin-authority.test.ts b/apps/server/test/admin-authority.test.ts new file mode 100644 index 00000000..5b8a83fb --- /dev/null +++ b/apps/server/test/admin-authority.test.ts @@ -0,0 +1,56 @@ +/** + * Admin authority is the role AND a credential that may administer (auth.ts `actsAsAdmin`), read in one place. Before, + * the restore/purge owner scope and the report's instance diagnostics read the role alone, so an admin's key without + * instance administration, or an MCP/OAuth connector, could reach other accounts. The source scan fails on a new + * role-only check in the request paths; a check about the account itself (not about reaching others) says so with a + * `role-ok: ` comment on the line or the one above. + * node --import tsx --test test/admin-authority.test.ts + */ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { actsAsAdmin } from "../src/auth.js"; +import { reportCapabilities } from "../src/report/capabilities.js"; + +const src = path.join(import.meta.dirname, "..", "src"); +/** Where a request is authorised: tRPC procedures, the HTTP routes, MCP tools and the issue report. */ +const SCANNED = ["trpc", "http.ts", "mcp.ts", "report"]; +const ROLE_CHECK = /\brole\s*[!=]==?\s*["']admin["']|["']admin["']\s*[!=]==?\s*\w*\.?role\b/; + +function files(p: string): string[] { + const full = path.join(src, p); + if (fs.statSync(full).isFile()) return [full]; + return fs.readdirSync(full).flatMap((f) => files(path.join(p, f))); +} + +describe("actsAsAdmin", () => { + it("needs both the admin role and a credential that may administer", () => { + assert.equal(actsAsAdmin({ user: { role: "admin" }, canAdminister: true }), true); + assert.equal(actsAsAdmin({ user: { role: "admin" }, canAdminister: false }), false, "an admin's limited key or connector"); + assert.equal(actsAsAdmin({ user: { role: "user" }, canAdminister: true }), false); + assert.equal(actsAsAdmin({ user: { role: null }, canAdminister: true }), false); + }); + + it("an admin's limited credential gets no instance-wide report diagnostics", () => { + const svc = { ee: null, telemetry: { enabled: { sentry: false, posthog: false } } }; + assert.equal(reportCapabilities(svc, { user: { role: "admin" }, canAdminister: false }).instance, false); + assert.equal(reportCapabilities(svc, { user: { role: "admin" }, canAdminister: true }).instance, true); + const hosted = { ee: { billing: true } as never, telemetry: { enabled: { sentry: false, posthog: false } } }; + assert.equal(reportCapabilities(hosted, { user: { role: "admin" }, canAdminister: false }).system, false, "hosted: like any non-admin"); + }); + + it("the request paths check admin authority through actsAsAdmin, never the role alone", () => { + const found = SCANNED.flatMap(files) + .filter((f) => f.endsWith(".ts")) + .flatMap((f) => + fs + .readFileSync(f, "utf8") + .split("\n") + .map((line, i, all) => ({ where: `${path.relative(src, f)}:${i + 1}`, line, above: all[i - 1] ?? "" })) + .filter(({ line, above }) => ROLE_CHECK.test(line) && !`${above}${line}`.includes("role-ok:")), + ) + .map(({ where, line }) => `${where}: ${line.trim()}`); + assert.deepEqual(found, [], "use actsAsAdmin(who) (auth.ts), or mark a check about the account itself with `role-ok: `"); + }); +}); diff --git a/apps/server/test/posthog-proxy.test.ts b/apps/server/test/posthog-proxy.test.ts index 3657d30a..19626c4b 100644 --- a/apps/server/test/posthog-proxy.test.ts +++ b/apps/server/test/posthog-proxy.test.ts @@ -38,6 +38,7 @@ describe("posthogProxy", () => { TRUST_PROXY: true, TRUSTED_PROXY_HEADER: "x-forwarded-for", TRUSTED_PROXY_HOPS: 1, + TRUSTED_PROXIES: "", }; it("sends no cookie or authorization upstream, the client address as X-Forwarded-For, and sets no cookie back", async () => { diff --git a/apps/server/test/report-capabilities.test.ts b/apps/server/test/report-capabilities.test.ts index 65802480..8dc58ecd 100644 --- a/apps/server/test/report-capabilities.test.ts +++ b/apps/server/test/report-capabilities.test.ts @@ -8,30 +8,32 @@ import { applyReportInclude, reportCapabilities } from "../src/report/capabiliti const tel = (sentry: boolean, posthog: boolean) => ({ enabled: { sentry, posthog } }); const ee = { billing: true } as never; +/** a browser session: its credential may administer, so the role decides */ +const as = (role: "user" | "admin") => ({ user: { role }, canAdminister: true }); const inc = { logs: true, system: true, instance: false, previews: true, allClips: false, source: false }; describe("reportCapabilities", () => { it("self-host: zip + system for everyone; instance only for admins; feedback follows telemetry", () => { - const off = reportCapabilities({ ee: null, telemetry: tel(false, false) }, { role: "user" }); + const off = reportCapabilities({ ee: null, telemetry: tel(false, false) }, as("user")); assert.deepEqual(off, { zip: true, system: true, instance: false, feedback: false }); - const on = reportCapabilities({ ee: null, telemetry: tel(true, false) }, { role: "user" }); + const on = reportCapabilities({ ee: null, telemetry: tel(true, false) }, as("user")); assert.deepEqual(on, { zip: true, system: true, instance: false, feedback: true }); - const admin = reportCapabilities({ ee: null, telemetry: tel(false, false) }, { role: "admin" }); + const admin = reportCapabilities({ ee: null, telemetry: tel(false, false) }, as("admin")); assert.deepEqual(admin, { zip: true, system: true, instance: true, feedback: false }); }); it("hosted non-admin with telemetry: feedback only, no system, no instance", () => { - const caps = reportCapabilities({ ee, telemetry: tel(true, true) }, { role: "user" }); + const caps = reportCapabilities({ ee, telemetry: tel(true, true) }, as("user")); assert.deepEqual(caps, { zip: false, system: false, instance: false, feedback: true }); }); it("hosted non-admin without telemetry: zip without system or instance", () => { - const caps = reportCapabilities({ ee, telemetry: tel(false, false) }, { role: "user" }); + const caps = reportCapabilities({ ee, telemetry: tel(false, false) }, as("user")); assert.deepEqual(caps, { zip: true, system: false, instance: false, feedback: false }); }); it("hosted admin: zip + system + instance, and feedback when telemetry is on", () => { - const caps = reportCapabilities({ ee, telemetry: tel(false, true) }, { role: "admin" }); + const caps = reportCapabilities({ ee, telemetry: tel(false, true) }, as("admin")); assert.deepEqual(caps, { zip: true, system: true, instance: true, feedback: true }); }); diff --git a/apps/server/test/signup-rules-stack.test.ts b/apps/server/test/signup-rules-stack.test.ts index 3624fb0c..876a0030 100644 --- a/apps/server/test/signup-rules-stack.test.ts +++ b/apps/server/test/signup-rules-stack.test.ts @@ -21,7 +21,7 @@ async function trpc(cookie: string, path: string, input?: unknown, method: "GET" const body = (await res.json()) as { result?: { data: unknown }; error?: { message: string; data: { code: string } } }; return { status: res.status, data: body.result?.data as never, error: body.error }; } -/** A sign-up from a given (proxied) address: status, the server's text, the account and its session cookie. */ +/** A sign-up from a given (proxied) address (the app runs with TRUST_PROXY=true; stack.yml sets it): status, the server's text, the account and its session cookie. */ const trySignup = (email: string, ip: string) => postSignUp({ email, password: `pw-${randomUUID()}`, name: "Rule" }, { "x-forwarded-for": ip }); type Rule = { id: string; kind: string; pattern: string; action: string; hits: number }; diff --git a/deploy/.env.example b/deploy/.env.example index a736766b..ab2a14a0 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -63,12 +63,14 @@ SMTP_URL= RESEND_API_KEY= # With an email driver: users must click the verification link before they can sign in. The link works for 24 hours and is single-use; an expired one offers a new send. Runtime setting: admins can change it under Settings → System without a restart. REQUIRE_EMAIL_VERIFICATION=false -# Take the client address from the reverse proxy's header (see TRUSTED_PROXY_HEADER): the Docker deployment sits behind Caddy, so the default is on. false when the app is exposed directly, or the header is whatever the client sent. The address feeds the sign-up cap and the OAuth client-registration limit. -# TRUST_PROXY=true +# true when a reverse proxy (Caddy, nginx, Cloudflare, a platform's edge) sits in front of the app: the client address then comes from the proxy's header (see TRUSTED_PROXY_HEADER, TRUSTED_PROXY_HOPS, TRUSTED_PROXIES). Default false, for an app exposed directly (what the compose files and installers set up): the address is the connection's own, and any forwarding header a client sends is ignored. The address keys the sign-in and sign-up rate limits, the accounts-per-address cap and the OAuth client-registration limit; behind a proxy with this off, every client shares the proxy's address in them (the app warns once when a request carries the header). +# TRUST_PROXY=false # With x-forwarded-for: how many trusted proxies sit in front of the app, each appending the address it saw. The client is the entry that many places from the right, so entries a client prepends are ignored. 1 for Caddy alone, 2 for Cloudflare in front of Caddy. # TRUSTED_PROXY_HOPS=1 # Header that carries the client address when TRUST_PROXY is on: x-forwarded-for (default; Caddy, nginx, most load balancers), cf-connecting-ip (Cloudflare, with the origin closed to everything else) or x-real-ip (Railway, whose edge sets it to the visitor's address). Only the selected header is read, so a client cannot choose its address by sending a different one. (x-forwarded-for | cf-connecting-ip | x-real-ip) # TRUSTED_PROXY_HEADER=x-forwarded-for +# With TRUST_PROXY: the addresses or CIDR ranges of the proxies allowed to name the client, comma-separated (172.16.0.0/12 for a proxy container on a Docker network, 127.0.0.1,::1 for one on the same host). A request from any other address is keyed on its own address and its header ignored, so a client that reaches the app's port around the proxy cannot choose its address. Empty (default) trusts the header from any connection: only safe when the port is reachable through the proxy alone. +# TRUSTED_PROXIES= # Accounts one network address may create per day (sign-up guard). 0 = unlimited. Runtime setting: admins can change it under Settings → System without a restart. # MAX_SIGNUPS_PER_IP_PER_DAY=0 # Refuse sign-ups from known temporary-address domains. Runtime setting: admins can change it under Settings → System without a restart. @@ -355,7 +357,7 @@ STRIPE_WEBHOOK_SECRET= # POSTHOG_KEY= # PostHog ingestion host (https://eu.i.posthog.com for the EU cloud, or a self-hosted instance). # POSTHOG_HOST=https://us.i.posthog.com -# true has the web app send PostHog events to the app's own origin at /api/relay, which the server forwards to POSTHOG_HOST (and /static/* to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For, when TRUST_PROXY is on. Default false: the browser talks to POSTHOG_HOST directly. Only used with POSTHOG_KEY. +# true has the web app send PostHog events to the app's own origin at /api/relay, which the server forwards to POSTHOG_HOST (and /static/* to PostHog's assets host), so ad blockers that block posthog.com do not drop them. Cookies and authorization headers are not forwarded; the client address is, as X-Forwarded-For (resolved as for the rate limits: see TRUST_PROXY). Default false: the browser talks to POSTHOG_HOST directly. Only used with POSTHOG_KEY. # POSTHOG_PROXY=false # Capture model calls: none, logs (one structured line per call: prompt, response, tokens, latency) or langfuse (a trace per job, a generation per call tagged with its step's prompt version, and, for accounts with learning on, a score per decision about the output on the project's session: clip.kept, clip.found, clip.untouched, clip.bounds_kept, clip.copy_kept, fix.accepted, fix.found); comma-separate for several. A failed call's log line carries errName, statusCode and the provider's errCode beside the error. LLM_TRACE=logs diff --git a/deploy/README.md b/deploy/README.md index 1ec67453..afa2ab03 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -115,6 +115,12 @@ macOS has no CUDA in Docker: run Ollama natively (Metal) and leave Speaches on t `.env.example` lists every variable with its default and meaning; the same list as a table is [docs/CONFIG.md](../docs/CONFIG.md) in the repository. +**Behind a reverse proxy** (Caddy, nginx, Cloudflare): set `TRUST_PROXY=true` so sign-in and +sign-up limits key on each visitor's address from the proxy's header rather than on the proxy's +own, and `TRUSTED_PROXIES` to the proxy's address or range (for example `172.16.0.0/12` for a +proxy container on the Docker network) if the app's port can also be reached directly. The +installer writes `TRUST_PROXY=false`, which is right while the port is published directly. + ## Accounts The first account is the admin. `SIGNUP_MODE=open|approval|closed` in `.env` controls sign-ups; diff --git a/deploy/install.ps1 b/deploy/install.ps1 index f0e61df2..53d0a1aa 100644 --- a/deploy/install.ps1 +++ b/deploy/install.ps1 @@ -474,6 +474,11 @@ if ($Existing) { 'SIGNUP_MODE=open') if ($GpuCompose) { $lines += 'COMPOSE_FILE=docker-compose.yml;docker-compose.gpu.yml' } $lines += '' + $lines += @( + "# the app's port is published directly, so rate limits key on the connection's address. Behind a reverse", + '# proxy: TRUST_PROXY=true, and TRUSTED_PROXIES= (see SECURITY.md, "Hardening")', + 'TRUST_PROXY=false', + '') if ($Ai -eq 'local') { $lines += @("# language model: Ollama ($OllamaMode)", "AI_MODEL=compat:$Llm", "OPENAI_COMPATIBLE_BASE_URL=$OllamaUrl", 'OPENAI_COMPATIBLE_API_KEY=ollama') } else { diff --git a/deploy/install.sh b/deploy/install.sh index 4457c809..37396cfa 100755 --- a/deploy/install.sh +++ b/deploy/install.sh @@ -534,6 +534,12 @@ SIGNUP_MODE=open ENV [ -n "$GPU_COMPOSE" ] && echo "COMPOSE_FILE=docker-compose.yml:docker-compose.gpu.yml" echo + cat <<'ENV' +# the app's port is published directly, so rate limits key on the connection's address. Behind a reverse +# proxy: TRUST_PROXY=true, and TRUSTED_PROXIES= (see SECURITY.md, "Hardening") +TRUST_PROXY=false + +ENV if [ "$AI" = local ]; then cat <