fix(http): let operators name their proxy, and survive a bad TRUST_PROXY_HOPS

Forwarding headers were believed from any connection on a private address.
Behind Docker Desktop, OrbStack and docker-proxy every connection to a
published port arrives from the gateway, a private address, so a caller
reaching the port directly could again choose the client address that rate
limits, the audit log and sign-in notices record. TRUSTED_PROXY_CIDRS
(comma-separated CIDRs) now names the proxies: when set, only those peers may
report a client address. The private-range default stays when it is unset,
the boot log states the rule in force in one line, and the reverse-proxy
guide says what to set for a proxy on the same host, on a Docker network, or
on a public address (which, unlisted, puts all clients in one bucket).

An invalid TRUST_PROXY_HOPS threw on every request that resolved the client
address, so every route answered 500, the health probe included. It now
resolves no address, warns once, and is named at boot.
This commit is contained in:
Marc-André Bombeck committed 2026-10-25 17:44:31 +01:00
1 parent 0b830e6b02
commit d87718407e
10 files changed
+501 -38

No files matched your search

+54 -29
View File
@@ -7,7 +7,11 @@ import {
peerAddressStampInstalled,
readPeerAddress,
} from "@/lib/http/peer-address";
import { isPublicIp } from "@/lib/validations/notifications";
import {
parseTrustProxyHops,
parseTrustedProxyCidrs,
peerMayForward,
} from "@/lib/http/proxy-trust";
export function apiSuccess<T>(data: T, status = 200) {
return NextResponse.json({ data, error: null }, { status });
@@ -508,13 +512,16 @@ export async function safeJson<T = unknown>(
* observed when the request arrived.
* - "N" (>1) → trust N hops; read the Nth-from-rightmost XFF entry.
*
* Forwarding headers are read only from a connection whose peer could be a
* proxy: loopback, a private or unique-local network, CGNAT (Tailscale). A
* connection from a public address reached the server directly, so whatever
* forwarding headers it sends are its own, and its own address is the client
* IP. The peer comes from `@/lib/http/peer-address`. Without that check, the
* default of one trusted hop let any direct caller name a fresh address per
* request and step around every per-IP limit.
* Forwarding headers are read only from a connection whose peer may be a
* proxy (`peerMayForward` in `@/lib/http/proxy-trust`): one inside
* `TRUSTED_PROXY_CIDRS` when that is set, otherwise any loopback, private,
* unique-local or CGNAT (Tailscale) address. Any other connection reached the
* server directly, so whatever forwarding headers it sends are its own, and
* its own address is the client IP. The peer comes from
* `@/lib/http/peer-address`. Without that check, the default of one trusted
* hop let any direct caller name a fresh address per request and step around
* every per-IP limit. An invalid `TRUST_PROXY_HOPS` resolves no address
* (and is named at boot) instead of failing the request.
*
* Cloudflare opt-in (`TRUST_CF_CONNECTING_IP=1`): when the env flag is
* set, the helper prefers the `cf-connecting-ip` header before walking
@@ -561,22 +568,24 @@ function readCfConnectingIp(request: Request): string | null {
return looksLikeIp(trimmed) ? trimmed : null;
}
function parseTrustProxyHops(raw: string | undefined): number {
// Empty is unset. The shipped docker-compose.yml passes
// `TRUST_PROXY_HOPS: "${TRUST_PROXY_HOPS:-}"`, which is an empty string for
// every operator who never set it; reading that as invalid threw on every
// request that asked for the client IP.
const trimmed = raw?.trim() ?? "";
if (trimmed === "") return 1;
if (!/^\d+$/.test(trimmed)) {
// Reject explicitly-invalid values so an operator typo doesn't silently
// switch a real-proxy deployment to "no XFF trust" mode (review
// finding L-1: TRUST_PROXY_HOPS=garbage degraded to hops=0 silently).
throw new Error(
`TRUST_PROXY_HOPS must be a non-negative integer, got: ${JSON.stringify(raw)}`,
);
}
return parseInt(trimmed, 10);
/**
* Once per process: `TRUST_PROXY_HOPS` is not a number. Every request that
* asks for the client address used to throw on it, so every route answered
* 500, `/api/health` included. It resolves no address instead, and says so.
*/
let invalidHopsWarned = false;
function warnInvalidHopsOnce(raw: string | undefined): void {
if (invalidHopsWarned) return;
invalidHopsWarned = true;
console.warn(
`[getClientIp] TRUST_PROXY_HOPS=${JSON.stringify(raw)} is not a non-negative integer; no client address is read from forwarding headers until it is fixed, and every anonymous caller shares one rate-limit bucket.`,
);
}
/** Test-only reset for {@link warnInvalidHopsOnce}. */
export function _resetInvalidHopsWarningForTests(): void {
invalidHopsWarned = false;
}
/**
@@ -646,12 +655,23 @@ let publicPeerForwardingWarned = false;
function warnPublicPeerForwardingOnce(): void {
if (publicPeerForwardingWarned) return;
publicPeerForwardingWarned = true;
const listed =
parseTrustedProxyCidrs(process.env.TRUSTED_PROXY_CIDRS).kind !== "unset";
console.warn(
"[getClientIp] a connection from a public address sent X-Forwarded-For or X-Real-IP; those headers are ignored and the connection's own address is used. " +
"If HealthLog is meant to be reached only through a reverse proxy, the published port is open beyond it.",
listed
? "[getClientIp] a connection from outside TRUSTED_PROXY_CIDRS sent X-Forwarded-For or X-Real-IP; those headers are ignored and the connection's own address is used. " +
"If it was your proxy, add its address to TRUSTED_PROXY_CIDRS; otherwise the published port is reachable beyond the proxy."
: "[getClientIp] a connection from a public address sent X-Forwarded-For or X-Real-IP; those headers are ignored and the connection's own address is used. " +
"If HealthLog is meant to be reached only through a reverse proxy, the published port is open beyond it. " +
"If the proxy connects from a public address, set TRUSTED_PROXY_CIDRS to it.",
);
}
/** Test-only reset for {@link warnPublicPeerForwardingOnce}. */
export function _resetPublicPeerForwardingWarningForTests(): void {
publicPeerForwardingWarned = false;
}
/**
* Tagged return shape so a caller can apply a tighter universal
* rate-limit when the trust chain is misconfigured. F-6 (mobile security
@@ -681,6 +701,10 @@ export function getClientIpOrTrustWarning(request: Request): {
if (cfIp) return { ip: cfIp, trustViolation: false };
const hops = parseTrustProxyHops(process.env.TRUST_PROXY_HOPS);
if (hops === null) {
warnInvalidHopsOnce(process.env.TRUST_PROXY_HOPS);
return { ip: null, trustViolation: true };
}
// The connection's own peer, stamped by the server for every request it
// receives. `undefined` only for a request the server did not receive (a
@@ -693,9 +717,10 @@ export function getClientIpOrTrustWarning(request: Request): {
if (peer !== undefined) {
// No proxy declared: the peer is the client.
if (hops === 0) return { ip: peer, trustViolation: false };
// A peer on a public address reached the server directly; its
// forwarding headers are its own choice, not a proxy's report.
if (isPublicIp(peer)) {
// A peer that is not a proxy (outside TRUSTED_PROXY_CIDRS when it is
// set, on a public address when it is not) reached the server directly;
// its forwarding headers are its own choice, not a proxy's report.
if (!peerMayForward(peer)) {
if (
request.headers.has("x-real-ip") ||
request.headers.get("x-forwarded-for")?.trim() !== peer