From a680510ae2c37c5af208272149cef485001c239e Mon Sep 17 00:00:00 2001 From: 0libote <79215282+0libote@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:05:18 +0000 Subject: [PATCH 1/2] fix(setup): gate DB port exposure, login lockout, forwarded headers, pair args - POST /ports/expose refuses looks-like-database ports without {"confirmDatabase": true} - key throttle locks an address out after 20 failures for a growing window, rejecting at once without holding shared slots - X-Forwarded-Proto/Host/Prefix only believed from loopback peers; router warns loudly when T3_TRUST_PROXY_HEADERS is set - /pair validates ttl against the CLI duration grammar and label against printable text without a leading dash --- docker/router/server.mjs | 3 + docker/setup/client-address.mjs | 4 + docker/setup/key-throttle.mjs | 31 ++++- docker/setup/request-auth.mjs | 36 ++++- docker/setup/server.mjs | 34 ++++- tests/setup-front-door.test.mjs | 224 ++++++++++++++++++++++++++++++++ 6 files changed, 319 insertions(+), 13 deletions(-) create mode 100644 tests/setup-front-door.test.mjs diff --git a/docker/router/server.mjs b/docker/router/server.mjs index c1a392bd..db2e250e 100644 --- a/docker/router/server.mjs +++ b/docker/router/server.mjs @@ -67,6 +67,9 @@ const where = config.setup ? `T3 Code (port ${config.t3.port}) at /, the setup page (port ${config.setup.port}) at ${config.setupPrefix}` : `T3 Code (port ${config.t3.port}); the setup page is off`; log(`listening on ${host === "::" ? "[::]" : host}:${config.port}: ${where}`); +if (config.trustedProxy) { + log("WARNING: T3_TRUST_PROXY_HEADERS=1 trusts X-Forwarded-Proto/Host from the proxy. Keep this only when this port is reachable solely through your TLS-terminating proxy or tunnel: anyone who can reach it directly can spoof the scheme and host the services behind it see."); +} // Stop taking connections, let what is in flight finish briefly, then go. const stop = () => { diff --git a/docker/setup/client-address.mjs b/docker/setup/client-address.mjs index a7d23c41..73508800 100644 --- a/docker/setup/client-address.mjs +++ b/docker/setup/client-address.mjs @@ -27,3 +27,7 @@ export function clientAddress(req) { const last = plainAddress(forwarded[forwarded.length - 1].trim()); return isIP(last) ? last : peer; } + +/** Whether the request arrived over loopback: the only peer whose forwarded + * headers are believed. Anything else could have written them itself. */ +export const peerIsLoopback = (req) => isLoopback(plainAddress(req?.socket?.remoteAddress)); diff --git a/docker/setup/key-throttle.mjs b/docker/setup/key-throttle.mjs index 40f3d4fa..ee09784b 100644 --- a/docker/setup/key-throttle.mjs +++ b/docker/setup/key-throttle.mjs @@ -1,22 +1,39 @@ // Every supplied setup-key guess, including cookies and headers, takes a slot // before the secret is compared. Failures keep their slots through a per-IP // serialized delay. Successful authentication releases immediately. -export function createKeyThrottle({ matches, wait = ms => new Promise(resolve => setTimeout(resolve, ms)), perAddress = 4, pendingLimit = 256, failureLimit = 1000 } = {}) { - const active = new Map(), tails = new Map(), failures = new Map(); +// +// After enough failures from one address it is locked out: further guesses +// are refused at once, for a growing window, without taking a slot or +// queuing another delayed check. A locked-out flood therefore holds no room +// in the shared pending cap, so other visitors keep getting answers. +export function createKeyThrottle({ matches, wait = ms => new Promise(resolve => setTimeout(resolve, ms)), perAddress = 4, pendingLimit = 256, failureLimit = 1000, lockoutAfter = 20, lockoutBaseMs = 30_000, lockoutMaxMs = 15 * 60 * 1000, now = () => Date.now() } = {}) { + const active = new Map(), tails = new Map(), failures = new Map(), lockedUntil = new Map(); let pending = 0; + const lockoutFor = (strikes) => Math.min(lockoutBaseMs * 2 ** Math.floor((strikes - lockoutAfter) / 5), lockoutMaxMs); return { - clearFailures() { failures.clear(); }, + clearFailures() { failures.clear(); lockedUntil.clear(); }, async check(ip, candidate) { + // Locked out: refuse at once, before taking any shared slot, so a + // guessing flood stops crowding out everyone else's attempts. + const until = lockedUntil.get(ip); + if (until !== undefined) { + if (now() < until) throw Object.assign(new Error('Too many login attempts. Wait a moment and try again.'), { code: 'login-limit' }); + lockedUntil.delete(ip); + } const count = active.get(ip) ?? 0; if (count >= perAddress || pending >= pendingLimit) throw Object.assign(new Error('Too many login attempts. Wait a moment and try again.'), { code: 'login-limit' }); active.set(ip, count + 1); pending++; try { - if (matches(candidate)) { failures.delete(ip); return true; } + if (matches(candidate)) { failures.delete(ip); lockedUntil.delete(ip); return true; } const run = (tails.get(ip) ?? Promise.resolve()).then(() => { - const n = Math.min((failures.get(ip) ?? 0) + 1, 12); - failures.delete(ip); failures.set(ip, n); + const strikes = (failures.get(ip) ?? 0) + 1; + failures.delete(ip); failures.set(ip, strikes); if (failures.size > failureLimit) failures.delete(failures.keys().next().value); - return wait(n * 250); + if (strikes >= lockoutAfter) { + lockedUntil.delete(ip); lockedUntil.set(ip, now() + lockoutFor(strikes)); + if (lockedUntil.size > failureLimit) lockedUntil.delete(lockedUntil.keys().next().value); + } + return wait(Math.min(strikes, 12) * 250); }); const tail = run.catch(() => {}); tails.set(ip, tail); diff --git a/docker/setup/request-auth.mjs b/docker/setup/request-auth.mjs index e42927da..a0f3507c 100644 --- a/docker/setup/request-auth.mjs +++ b/docker/setup/request-auth.mjs @@ -37,8 +37,14 @@ export function cookieValue(header, name) { * usable. A proxy that rewrites the path is supposed to say so: nginx and * Traefik send X-Forwarded-Prefix, and when the path itself no longer * carries the prefix, that header is the only thing left that knows it. + * + * Only believed when `trusted` - from a direct peer the header is the + * visitor's own words, and must not become the cookie path or where + * redirects point. Callers pass whether the socket peer is loopback + * (client-address.mjs); the default keeps existing callers' behavior. */ -export function forwardedPrefix(headers) { +export function forwardedPrefix(headers, { trusted = true } = {}) { + if (!trusted) return ""; const raw = headers?.["x-forwarded-prefix"]; if (typeof raw !== "string") return ""; const trimmed = raw.trim().replace(/\/+$/, ""); @@ -48,3 +54,31 @@ export function forwardedPrefix(headers) { if (trimmed.split("/").slice(1).some((segment) => segment === "" || segment === "." || segment === "..")) return ""; return trimmed; } + +/** + * The scheme a proxy says the visitor used, lowercased, or "" when it said + * nothing. Only believed when `trusted`: from a direct peer the header is + * the visitor's own words, and must not decide the session cookie's Secure + * flag - a forged `https` over plain HTTP would set a cookie the browser + * then never sends back, and every login silently "fails". + */ +export function forwardedProto(headers, { trusted = true } = {}) { + if (!trusted) return ""; + const raw = headers?.["x-forwarded-proto"]; + const first = Array.isArray(raw) ? raw[0] : raw; + return String(first ?? "").split(",")[0].trim().toLowerCase(); +} + +/** + * The host to show: what a proxy says the visitor asked for, else the Host + * the client sent here. Only believed when `trusted`: from a direct peer + * the header is the visitor's own words. + */ +export function forwardedHost(headers, { trusted = true } = {}) { + const direct = headers?.host; + const fallback = Array.isArray(direct) ? direct[0] : direct; + if (!trusted) return fallback; + const forwarded = headers?.["x-forwarded-host"]; + const value = forwarded ?? fallback; + return Array.isArray(value) ? value[0] : value; +} diff --git a/docker/setup/server.mjs b/docker/setup/server.mjs index 8dcd3c0f..db20d3a8 100644 --- a/docker/setup/server.mjs +++ b/docker/setup/server.mjs @@ -45,8 +45,8 @@ import { createGatewayProcesses } from "./gateways/processes.mjs"; import { createGatewayT3 } from "./gateways/t3.mjs"; import { createGatewayVault } from "./gateways/vault.mjs"; import { createSessionStore, TERMINAL_STATES } from "./signin-sessions.mjs"; -import { clientAddress } from "./client-address.mjs"; -import { cookieValue, forwardedPrefix } from "./request-auth.mjs"; +import { clientAddress, peerIsLoopback } from "./client-address.mjs"; +import { cookieValue, forwardedHost, forwardedPrefix, forwardedProto } from "./request-auth.mjs"; import { createKeyThrottle } from "./key-throttle.mjs"; import { newKey, readKeyFile, validKey, writeKeyFile } from "./setup-key.mjs"; import { createCredentialStore, credentialFailure, CredentialError, credentialDirectory } from "./credentials.mjs"; @@ -1079,6 +1079,16 @@ const revoke = async ({ kind, id }) => { }; const mintPairing = async ({ ttl, label }) => { + // argv, not a shell, but the CLI still parses a leading `-` as its own + // flag (`--ttl --help` prints help instead of issuing a pairing). Refuse + // flag-like values before anything else, so a bad ttl/label fails here + // rather than as a confusing error from further down. + if (ttl !== undefined && ttl !== null && ttl !== "" && (typeof ttl !== "string" || !/^[1-9][0-9]{0,6}[smhdw]$/.test(ttl))) { + throw new Error('invalid ttl: use a duration like "30d" (a number followed by s, m, h, d or w)'); + } + if (label !== undefined && label !== null && label !== "" && (typeof label !== "string" || label.length > 128 || label.startsWith("-") || /[^\x20-\x7E]/.test(label))) { + throw new Error("invalid label: use up to 128 printable characters that do not start with -"); + } const { url } = publicUrl(); if (!url) { throw new Error("Set the public URL first: a pairing link points at it, and without it a device has nowhere to go."); @@ -2534,8 +2544,11 @@ const startStorageWork = async (storage, kind, input) => { // The session cookie. Secure when the request reached us over HTTPS (directly // or through a proxy that says so); a plain-http LAN address must still work. +// The proxy's word is only believed over loopback: from a direct peer +// X-Forwarded-Proto is the visitor's own claim, and a forged `https` would +// set a Secure cookie the browser never sends back over http. const cookie = (req, mount, value, maxAge) => { - const secure = req.socket.encrypted || /^https$/i.test(String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim()); + const secure = req.socket.encrypted || forwardedProto(req.headers, { trusted: peerIsLoopback(req) }) === "https"; return `${COOKIE}=${value}; HttpOnly; SameSite=Strict; Path=${mount || "/"}; Max-Age=${maxAge}${secure ? "; Secure" : ""}`; }; @@ -2639,7 +2652,10 @@ const server = createServer(async (req, res) => { const route = resolved.route; // The inferred mount wins when the prefix survived the hop; otherwise fall // back to what the proxy declared. - const mount = resolved.mount || forwardedPrefix(req.headers); + // The inferred mount wins when the prefix survived the hop; otherwise fall + // back to what the proxy declared - but only when the peer is loopback. + // From a direct peer the header is the visitor's own claim. + const mount = resolved.mount || forwardedPrefix(req.headers, { trusted: peerIsLoopback(req) }); // The page sends a cookie; the in-container CLIs send a header. Same key, // same comparison - so `t3-expose` and the page are the same client as far // as this server is concerned, and neither can act on state the other cannot. @@ -2719,7 +2735,9 @@ const server = createServer(async (req, res) => { if (route === "/") { if (authed) return sendPage(req, res, (nonce) => renderConsole({ assets: ASSETS, nonce, mount, embed, host, layout })); // The host the browser asked for, for the card's eyebrow; escaped by the template. - const hostname = String(req.headers["x-forwarded-host"] ?? req.headers.host ?? "").split(",")[0].trim().slice(0, 200); + // The host the browser asked for, for the card's eyebrow; escaped by the template. + // A proxy's X-Forwarded-Host is only believed over loopback. + const hostname = String(forwardedHost(req.headers, { trusted: peerIsLoopback(req) }) ?? "").split(",")[0].trim().slice(0, 200); return sendPage(req, res, (nonce) => renderUnlock({ assets: ASSETS, nonce, mount, host, hostname, layout, publicUrl: publicUrl().url, error: raw.searchParams.get("error") === "1", embed, })); @@ -2984,6 +3002,12 @@ const server = createServer(async (req, res) => { if (req.method === "POST" && route === "/ports/expose") { try { const input = JSON.parse((await readBody(req)) || "{}"); + // A quick tunnel has nothing in front of it, so a dev database must + // not be published by port number alone: refuse looks-like-database + // ports unless the request says it means it. + if (looksLikeDatabase(Number(input.port)) && input.confirmDatabase !== true) { + return sendJson(res, 400, { error: `Port ${Number(input.port)} looks like a database. Resend with {"confirmDatabase": true} to publish it anyway.` }); + } return sendJson(res, 200, publicTunnel(startTunnel(input.port))); } catch (error) { return sendJson(res, 400, { error: String(error?.message ?? error) }); diff --git a/tests/setup-front-door.test.mjs b/tests/setup-front-door.test.mjs new file mode 100644 index 00000000..10689652 --- /dev/null +++ b/tests/setup-front-door.test.mjs @@ -0,0 +1,224 @@ +// Regression tests for the setup front door (DB port confirmation, login +// lockout, forwarded-header trust, /pair validation). +// +// node --test tests/setup-front-door.test.mjs +import assert from "node:assert/strict"; +import test from "node:test"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import os from "node:os"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { createServer } from "node:net"; +import { fileURLToPath } from "node:url"; + +import { createKeyThrottle } from "../docker/setup/key-throttle.mjs"; +import { clientAddress, peerIsLoopback } from "../docker/setup/client-address.mjs"; +import { forwardedHost, forwardedPrefix, forwardedProto } from "../docker/setup/request-auth.mjs"; + +// ------------------------------------------------------- login lockout -- + +test("guessing past the failure budget locks the address out at once", async () => { + let clock = 1_000_000; + const waits = []; + const throttle = createKeyThrottle({ + matches: (key) => key === "good", + wait: async (ms) => { waits.push(ms); }, + now: () => clock, + lockoutAfter: 5, + lockoutBaseMs: 30_000, + lockoutMaxMs: 120_000, + }); + for (let i = 0; i < 5; i++) assert.equal(await throttle.check("attacker", "bad"), false); + // The next guess is refused immediately: no slot taken, no delay queued. + const at = Date.now(); + await assert.rejects(throttle.check("attacker", "bad"), { code: "login-limit" }); + await assert.rejects(throttle.check("attacker", "good"), { code: "login-limit" }); + assert.ok(Date.now() - at < 1000, "a locked-out guess must not wait out another delay"); + assert.equal(waits.length, 5, "locked-out guesses queue no further delays"); + // Another address is unaffected, before and during the attacker's window. + assert.equal(await throttle.check("operator", "good"), true); + // The window passes: guessing resumes, and a right key still ends it. + clock += 30_001; + assert.equal(await throttle.check("attacker", "bad"), false, "guesses resume once the window lapses"); + assert.equal(waits.at(-1), 1500, "the delay keeps capping at 12 steps"); + await assert.rejects(throttle.check("attacker", "bad"), { code: "login-limit" }, "that failure locks the address again at once"); + clock += 30_001; + assert.equal(await throttle.check("attacker", "good"), true, "a right key still ends the lockout"); + assert.equal(await throttle.check("attacker", "bad"), false); + assert.equal(waits.at(-1), 250, "a success resets the failure count"); +}); + +test("the lockout window grows while failures keep coming", async () => { + let clock = 0; + const throttle = createKeyThrottle({ + matches: () => false, + wait: async () => {}, + now: () => clock, + lockoutAfter: 1, + lockoutBaseMs: 10_000, + lockoutMaxMs: 60_000, + }); + await throttle.check("attacker", "bad"); // strike 1: a 10s window + for (let strike = 2; strike <= 6; strike++) { + clock += 10_001; // each window lapses + assert.equal(await throttle.check("attacker", "bad"), false, `strike ${strike} is answered, then locks again`); + } + // Six strikes in, the window has doubled to 20s: 10s past is still locked. + clock += 10_001; + await assert.rejects(throttle.check("attacker", "bad"), { code: "login-limit" }, "the sixth window lasts twice as long"); + clock += 9_999; + assert.equal(await throttle.check("attacker", "bad"), false, "doubled window over, guesses resume"); +}); + +test("a locked-out flood holds no shared slots, so others keep logging in", async () => { + let release; + const gate = new Promise((resolve) => { release = resolve; }); + let clock = 0; + const throttle = createKeyThrottle({ + matches: (key) => key === "good", + wait: () => gate, + now: () => clock, + perAddress: 4, + pendingLimit: 4, + lockoutAfter: 4, + lockoutBaseMs: 60_000, + }); + // The attacker fills every shared slot with slow failures, then drains them. + const flood = Array.from({ length: 4 }, () => throttle.check("attacker", "bad")); + await assert.rejects(throttle.check("operator", "good"), { code: "login-limit" }, "at capacity even a right key waits"); + release(); + assert.deepEqual(await Promise.all(flood), [false, false, false, false]); + // Past the budget the attacker is locked out: their guesses are refused + // without taking slots, so the operator logs in while the flood continues. + clock += 60_001; // let the first lockout (if any) lapse; strikes stand + await throttle.check("attacker", "bad"); // 5th strike: locked again at once afterwards + const spam = Array.from({ length: 20 }, () => throttle.check("attacker", "bad").then(() => "kept", (error) => error.code)); + assert.equal(await throttle.check("operator", "good"), true, "locked-out spam must not crowd out a legitimate login"); + assert.deepEqual(await Promise.all(spam), Array(20).fill("login-limit")); + assert.equal(await throttle.check("operator", "good"), true); +}); + +// ------------------------------------------------- forwarded headers -- + +test("forwarded scheme/host/prefix are only believed from loopback", () => { + const headers = { + host: "direct.example", + "x-forwarded-proto": "https", + "x-forwarded-host": "proxy.example", + "x-forwarded-prefix": "/__setup", + }; + assert.equal(forwardedProto(headers, { trusted: true }), "https"); + assert.equal(forwardedProto(headers, { trusted: false }), "", "a direct peer's scheme claim is not believed"); + assert.equal(forwardedHost(headers, { trusted: true }), "proxy.example"); + assert.equal(forwardedHost(headers, { trusted: false }), "direct.example", "a direct peer's host claim is not believed"); + assert.equal(forwardedPrefix(headers, { trusted: true }), "/__setup"); + assert.equal(forwardedPrefix(headers, { trusted: false }), "", "a direct peer's prefix claim is not believed"); + assert.equal(forwardedProto({ "x-forwarded-proto": "https, http" }, { trusted: true }), "https", "first value wins, as before"); +}); + +test("the peer gate follows the socket, not the headers", () => { + const req = (remoteAddress, headers = {}) => ({ socket: { remoteAddress }, headers }); + assert.equal(peerIsLoopback(req("127.0.0.1")), true); + assert.equal(peerIsLoopback(req("::ffff:127.0.0.1")), true); + assert.equal(peerIsLoopback(req("::1")), true); + assert.equal(peerIsLoopback(req("192.168.1.20", { "x-forwarded-for": "127.0.0.1" })), false, "headers never promote a peer"); + assert.equal(peerIsLoopback(req("10.0.0.4")), false); + assert.equal(clientAddress(req("192.168.1.20", { "x-forwarded-for": "127.0.0.1" })), "192.168.1.20"); +}); + +// ------------------------------------------------------- live server -- + +const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +const launch = async (t) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "t3-front-door-")); + const socket = createServer().listen(0, "127.0.0.1"); + await once(socket, "listening"); + const port = socket.address().port; + await new Promise((resolve) => socket.close(resolve)); + const home = path.join(root, "home"); + await fs.mkdir(home); + const child = spawn(process.execPath, [fileURLToPath(new URL("../docker/setup/server.mjs", import.meta.url))], { + env: { + ...process.env, HOME: home, T3CODE_HOME: path.join(home, ".t3"), + CLAUDE_CONFIG_DIR: path.join(home, ".claude"), T3_WORKSPACE: root, + MISE_DATA_DIR: path.join(root, "mise-data"), MISE_STATE_DIR: path.join(root, "mise-state"), + MISE_CONFIG_DIR: path.join(root, "mise-config"), + T3_HARNESS_MODULE: fileURLToPath(new URL("../docker/harness/index.mjs", import.meta.url)), + T3_SETUP_KEY: "front-door-fixture-key", T3_SETUP_KEY_SOURCE: "env", + T3_SETUP_PORT: String(port), T3CODE_PORT: "1", T3_INFRA_LAUNCHER: "/bin/false", + T3_RUN_DIR: path.join(root, "run"), + T3_RUNTIME_MODULE: fileURLToPath(new URL("../docker/runtime/manager.mjs", import.meta.url)), + }, + stdio: ["ignore", "pipe", "pipe"], + }); + let logs = ""; + child.stdout.on("data", (x) => { logs += x; }); + child.stderr.on("data", (x) => { logs += x; }); + t.after(async () => { + if (child.exitCode === null) { + const exit = once(child, "exit"); + child.kill(); + await exit; + } + await fs.rm(root, { recursive: true, force: true }); + }); + const base = `http://127.0.0.1:${port}`; + for (let i = 0; i < 200; i++) { + if (child.exitCode !== null) throw new Error(logs); + try { await fetch(`${base}/hello`); break; } catch { await pause(20); } + } + return base; +}; + +test("a database port is refused without confirmation and published with it", { timeout: 30000 }, async (t) => { + const base = await launch(t); + const auth = { "x-t3-setup-key": "front-door-fixture-key", "content-type": "application/json" }; + const refused = await fetch(`${base}/ports/expose`, { method: "POST", headers: auth, body: JSON.stringify({ port: 5432 }) }); + assert.equal(refused.status, 400); + assert.match((await refused.json()).error, /looks like a database/i); + const confirmed = await fetch(`${base}/ports/expose`, { method: "POST", headers: auth, body: JSON.stringify({ port: 5432, confirmDatabase: true }) }); + assert.equal(confirmed.status, 200, `confirmed expose should start, got ${confirmed.status}: ${await confirmed.text()}`); + const other = await fetch(`${base}/ports/expose`, { method: "POST", headers: auth, body: JSON.stringify({ port: 3000 }) }); + assert.equal(other.status, 200, "an ordinary port still needs no confirmation"); + const unauth = await fetch(`${base}/ports/expose`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ port: 5432, confirmDatabase: true }) }); + assert.equal(unauth.status, 401, "confirmation is not a substitute for authentication"); +}); + +test("the Secure cookie still follows the proxy's scheme over loopback", { timeout: 30000 }, async (t) => { + const base = await launch(t); + const login = (headers = {}) => fetch(`${base}/login`, { + method: "POST", redirect: "manual", headers, + body: new URLSearchParams({ key: "front-door-fixture-key" }), + }); + const plain = await login(); + assert.equal(plain.status, 303); + assert.doesNotMatch(plain.headers.get("set-cookie") ?? "", /; Secure(;|$)/, "plain http sets no Secure flag"); + const viaProxy = await login({ "x-forwarded-proto": "https" }); + assert.match(viaProxy.headers.get("set-cookie") ?? "", /; Secure(;|$)/, "the router's https still earns the Secure flag"); +}); + +test("/pair refuses flag-like ttl and label values", { timeout: 30000 }, async (t) => { + const base = await launch(t); + const auth = { "x-t3-setup-key": "front-door-fixture-key", "content-type": "application/json" }; + const pair = (input) => fetch(`${base}/pair`, { method: "POST", headers: auth, body: JSON.stringify(input) }); + for (const ttl of ["--help", "-h", "--ttl", "30d;id", "1h --label x", "", " ", "0d", "ten-days", 30, ["30d"]]) { + if (ttl === "") continue; // empty means “no ttl”, as before + const response = await pair({ ttl }); + assert.equal(response.status, 400, `ttl ${JSON.stringify(ttl)}`); + assert.match((await response.json()).error, /invalid ttl/, `ttl ${JSON.stringify(ttl)}`); + } + for (const label of ["--label", "-x", "a\nb", "a\0b", "x".repeat(129), 42, { text: "phone" }]) { + const response = await pair({ label }); + assert.equal(response.status, 400, `label ${JSON.stringify(label)}`); + assert.match((await response.json()).error, /invalid label/, `label ${JSON.stringify(label)}`); + } + // Well-formed values get past validation: whatever the launcher or the + // public URL then says, it is not a complaint about the value itself. + for (const input of [{ ttl: "30d" }, { ttl: "5m", label: "my phone" }, { label: "tablet" }, {}]) { + const response = await pair(input); + assert.equal(response.status, 400, JSON.stringify(input)); + assert.doesNotMatch((await response.json()).error, /invalid (ttl|label)/, JSON.stringify(input)); + } +}); From 5a79e37f4a13d4938e76965d33b8b8f22b7219c3 Mon Sep 17 00:00:00 2001 From: Ziyang Zeng Date: Sat, 14 Nov 2026 14:44:22 -0800 Subject: [PATCH 2/2] fix: preserve explicit proxy support and safe pairing labels --- .env.example | 5 +++-- docker/setup/client-address.mjs | 14 +++++++++----- docker/setup/server.mjs | 28 ++++++++++++---------------- docs/configuration.md | 2 +- tests/setup-front-door.test.mjs | 22 +++++++++++++++++++--- 5 files changed, 44 insertions(+), 27 deletions(-) diff --git a/.env.example b/.env.example index 3fe6cfbe..0bba6c1f 100644 --- a/.env.example +++ b/.env.example @@ -33,8 +33,9 @@ T3_SETUP_BASE_PATH= # tunnel, proxy or hosting platform needs a single upstream. Publish it in # place of the two ports in compose.yaml. T3_SINGLE_PORT= -# Trust forwarding headers only when that port is reachable solely through -# your TLS-terminating proxy or tunnel. Keep 0 for a directly reached listener. +# Trust forwarding headers for the one-port router or the direct Setup port +# only when reachable solely through your TLS-terminating proxy or tunnel. +# Keep 0 for a directly reached listener. T3_TRUST_PROXY_HEADERS=0 # How long links minted by t3-pair and the setup UI stay redeemable. diff --git a/docker/setup/client-address.mjs b/docker/setup/client-address.mjs index 73508800..e250365a 100644 --- a/docker/setup/client-address.mjs +++ b/docker/setup/client-address.mjs @@ -18,16 +18,20 @@ export const isLoopback = (address) => { return plain === "::1" || /^127\.\d+\.\d+\.\d+$/.test(plain); }; -/** The visitor's address: the socket's peer, or the router's word for it. */ -export function clientAddress(req) { +/** The visitor's address: the peer, or an explicitly trusted proxy's report. */ +export function clientAddress(req, { trustProxyHeaders = false } = {}) { const peer = plainAddress(req?.socket?.remoteAddress) || "?"; - if (!isLoopback(peer)) return peer; + if (!trustsProxyHeaders(req, trustProxyHeaders)) return peer; const header = req?.headers?.["x-forwarded-for"]; const forwarded = (Array.isArray(header) ? header.join(",") : String(header ?? "")).split(","); const last = plainAddress(forwarded[forwarded.length - 1].trim()); return isIP(last) ? last : peer; } -/** Whether the request arrived over loopback: the only peer whose forwarded - * headers are believed. Anything else could have written them itself. */ +/** Whether the request arrived over loopback, as the in-container router does. */ export const peerIsLoopback = (req) => isLoopback(plainAddress(req?.socket?.remoteAddress)); + +// Direct Setup deployments can opt in to their TLS proxy using the same +// explicit trust setting as the single-port router. Never infer trust from +// request headers or accept a truthy string as authorization. +export const trustsProxyHeaders = (req, configured = false) => peerIsLoopback(req) || configured === true; diff --git a/docker/setup/server.mjs b/docker/setup/server.mjs index db20d3a8..b658f58c 100644 --- a/docker/setup/server.mjs +++ b/docker/setup/server.mjs @@ -45,7 +45,7 @@ import { createGatewayProcesses } from "./gateways/processes.mjs"; import { createGatewayT3 } from "./gateways/t3.mjs"; import { createGatewayVault } from "./gateways/vault.mjs"; import { createSessionStore, TERMINAL_STATES } from "./signin-sessions.mjs"; -import { clientAddress, peerIsLoopback } from "./client-address.mjs"; +import { clientAddress, trustsProxyHeaders } from "./client-address.mjs"; import { cookieValue, forwardedHost, forwardedPrefix, forwardedProto } from "./request-auth.mjs"; import { createKeyThrottle } from "./key-throttle.mjs"; import { newKey, readKeyFile, validKey, writeKeyFile } from "./setup-key.mjs"; @@ -1086,8 +1086,8 @@ const mintPairing = async ({ ttl, label }) => { if (ttl !== undefined && ttl !== null && ttl !== "" && (typeof ttl !== "string" || !/^[1-9][0-9]{0,6}[smhdw]$/.test(ttl))) { throw new Error('invalid ttl: use a duration like "30d" (a number followed by s, m, h, d or w)'); } - if (label !== undefined && label !== null && label !== "" && (typeof label !== "string" || label.length > 128 || label.startsWith("-") || /[^\x20-\x7E]/.test(label))) { - throw new Error("invalid label: use up to 128 printable characters that do not start with -"); + if (label !== undefined && label !== null && label !== "" && (typeof label !== "string" || !label.isWellFormed() || label.length > 128 || label.startsWith("-") || /[\x00-\x1F\x7F-\x9F]/.test(label))) { + throw new Error("invalid label: use up to 128 characters without control characters or a leading -"); } const { url } = publicUrl(); if (!url) { @@ -2544,11 +2544,11 @@ const startStorageWork = async (storage, kind, input) => { // The session cookie. Secure when the request reached us over HTTPS (directly // or through a proxy that says so); a plain-http LAN address must still work. -// The proxy's word is only believed over loopback: from a direct peer -// X-Forwarded-Proto is the visitor's own claim, and a forged `https` would -// set a Secure cookie the browser never sends back over http. +// Trust the in-container router or an explicitly configured proxy. A direct +// visitor cannot choose the cookie's Secure flag through forwarding headers. +const proxyHeadersTrusted = req => trustsProxyHeaders(req, process.env.T3_TRUST_PROXY_HEADERS === "1"); const cookie = (req, mount, value, maxAge) => { - const secure = req.socket.encrypted || forwardedProto(req.headers, { trusted: peerIsLoopback(req) }) === "https"; + const secure = req.socket.encrypted || forwardedProto(req.headers, { trusted: proxyHeadersTrusted(req) }) === "https"; return `${COOKIE}=${value}; HttpOnly; SameSite=Strict; Path=${mount || "/"}; Max-Age=${maxAge}${secure ? "; Secure" : ""}`; }; @@ -2646,16 +2646,13 @@ const resolve = (pathname) => { const server = createServer(async (req, res) => { // The visitor, not the router in front of them: see client-address.mjs. - const ip = clientAddress(req); + const ip = clientAddress(req, { trustProxyHeaders: process.env.T3_TRUST_PROXY_HEADERS === "1" }); const raw = new URL(req.url ?? "/", "http://localhost"); const resolved = resolve(raw.pathname); const route = resolved.route; // The inferred mount wins when the prefix survived the hop; otherwise fall - // back to what the proxy declared. - // The inferred mount wins when the prefix survived the hop; otherwise fall - // back to what the proxy declared - but only when the peer is loopback. - // From a direct peer the header is the visitor's own claim. - const mount = resolved.mount || forwardedPrefix(req.headers, { trusted: peerIsLoopback(req) }); + // back to a trusted proxy's prefix. Direct visitors cannot choose it. + const mount = resolved.mount || forwardedPrefix(req.headers, { trusted: proxyHeadersTrusted(req) }); // The page sends a cookie; the in-container CLIs send a header. Same key, // same comparison - so `t3-expose` and the page are the same client as far // as this server is concerned, and neither can act on state the other cannot. @@ -2735,9 +2732,8 @@ const server = createServer(async (req, res) => { if (route === "/") { if (authed) return sendPage(req, res, (nonce) => renderConsole({ assets: ASSETS, nonce, mount, embed, host, layout })); // The host the browser asked for, for the card's eyebrow; escaped by the template. - // The host the browser asked for, for the card's eyebrow; escaped by the template. - // A proxy's X-Forwarded-Host is only believed over loopback. - const hostname = String(forwardedHost(req.headers, { trusted: peerIsLoopback(req) }) ?? "").split(",")[0].trim().slice(0, 200); + // Forwarded host names require the same explicit trust as the scheme. + const hostname = String(forwardedHost(req.headers, { trusted: proxyHeadersTrusted(req) }) ?? "").split(",")[0].trim().slice(0, 200); return sendPage(req, res, (nonce) => renderUnlock({ assets: ASSETS, nonce, mount, host, hostname, layout, publicUrl: publicUrl().url, error: raw.searchParams.get("error") === "1", embed, })); diff --git a/docs/configuration.md b/docs/configuration.md index 37cc1875..477414cf 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -19,7 +19,7 @@ Environment variables (all optional except where noted): | `T3_PRINT_SETUP_KEY` | `0` | Print a generated setup key to the log in full on a first/ephemeral start. Without it, only a SHA-256 fingerprint is logged. Prefer retrieving the owner-only key file; opt in only when the hosting platform has no shell. | | `T3_SETUP_PORT` | `3774` | Setup page port inside the container | | `T3_SETUP_BASE_PATH` | — | Serve the setup page under a path, such as `/__setup` | -| `T3_TRUST_PROXY_HEADERS` | `0` | Trust the `X-Forwarded-Proto`/`Host` the proxy in front of `T3_SINGLE_PORT` set (`1` only when that port is reachable solely through your TLS-terminating proxy or tunnel) | +| `T3_TRUST_PROXY_HEADERS` | `0` | Trust forwarding headers from the proxy in front of `T3_SINGLE_PORT` or the direct Setup listener. This preserves the external HTTPS scheme, host, path prefix and visitor address. Use `1` only when the listener is reachable solely through your trusted proxy or tunnel. Loopback requests from the in-container router remain trusted. | | `T3_SINGLE_PORT` | — | Also serve T3 Code and the setup page together on this port, the setup page under `/__setup`, for a tunnel, proxy or hosting platform that routes one port. See [Exposing it through one hostname](remote-access.md#exposing-it-through-one-hostname). | | `T3_SETUP_ACCEPT_T3_SESSIONS` | `1` | Let a browser signed in to T3 Code with terminal access open the setup page without the key. `0` always asks for the key. | | `T3_ALLOW_SUDO` | `0` | Give agents passwordless sudo in the container | diff --git a/tests/setup-front-door.test.mjs b/tests/setup-front-door.test.mjs index 10689652..16373886 100644 --- a/tests/setup-front-door.test.mjs +++ b/tests/setup-front-door.test.mjs @@ -13,7 +13,7 @@ import { createServer } from "node:net"; import { fileURLToPath } from "node:url"; import { createKeyThrottle } from "../docker/setup/key-throttle.mjs"; -import { clientAddress, peerIsLoopback } from "../docker/setup/client-address.mjs"; +import { clientAddress, peerIsLoopback, trustsProxyHeaders } from "../docker/setup/client-address.mjs"; import { forwardedHost, forwardedPrefix, forwardedProto } from "../docker/setup/request-auth.mjs"; // ------------------------------------------------------- login lockout -- @@ -127,6 +127,19 @@ test("the peer gate follows the socket, not the headers", () => { assert.equal(clientAddress(req("192.168.1.20", { "x-forwarded-for": "127.0.0.1" })), "192.168.1.20"); }); +test("an explicitly configured direct Setup proxy preserves scheme, prefix and visitor identity", () => { + const req={socket:{remoteAddress:'10.0.0.4'},headers:{host:'internal:3774','x-forwarded-proto':'https','x-forwarded-host':'t3.example.com','x-forwarded-prefix':'/console','x-forwarded-for':'192.0.2.42'}}; + assert.equal(trustsProxyHeaders(req),false); + assert.equal(trustsProxyHeaders(req,'false'),false); + assert.equal(clientAddress(req),'10.0.0.4'); + const trusted=trustsProxyHeaders(req,true); + assert.equal(trusted,true); + assert.equal(forwardedProto(req.headers,{trusted}),'https'); + assert.equal(forwardedHost(req.headers,{trusted}),'t3.example.com'); + assert.equal(forwardedPrefix(req.headers,{trusted}),'/console'); + assert.equal(clientAddress(req,{trustProxyHeaders:true}),'192.0.2.42'); +}); + // ------------------------------------------------------- live server -- const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -148,6 +161,9 @@ const launch = async (t) => { T3_HARNESS_MODULE: fileURLToPath(new URL("../docker/harness/index.mjs", import.meta.url)), T3_SETUP_KEY: "front-door-fixture-key", T3_SETUP_KEY_SOURCE: "env", T3_SETUP_PORT: String(port), T3CODE_PORT: "1", T3_INFRA_LAUNCHER: "/bin/false", + // Exercise validation and startup acceptance without ever publishing + // a real host port, even when cloudflared is installed on the machine. + T3CODE_CLOUDFLARED_PATH: "/bin/false", T3_TRUST_PROXY_HEADERS: "0", T3_RUN_DIR: path.join(root, "run"), T3_RUNTIME_MODULE: fileURLToPath(new URL("../docker/runtime/manager.mjs", import.meta.url)), }, @@ -172,7 +188,7 @@ const launch = async (t) => { return base; }; -test("a database port is refused without confirmation and published with it", { timeout: 30000 }, async (t) => { +test("a database port needs confirmation before tunnel startup", { timeout: 30000 }, async (t) => { const base = await launch(t); const auth = { "x-t3-setup-key": "front-door-fixture-key", "content-type": "application/json" }; const refused = await fetch(`${base}/ports/expose`, { method: "POST", headers: auth, body: JSON.stringify({ port: 5432 }) }); @@ -216,7 +232,7 @@ test("/pair refuses flag-like ttl and label values", { timeout: 30000 }, async ( } // Well-formed values get past validation: whatever the launcher or the // public URL then says, it is not a complaint about the value itself. - for (const input of [{ ttl: "30d" }, { ttl: "5m", label: "my phone" }, { label: "tablet" }, {}]) { + for (const input of [{ ttl: "30d" }, { ttl: "5m", label: "my phone" }, { label: "tablet" }, {label:"我的手机 📱"}, {}]) { const response = await pair(input); assert.equal(response.status, 400, JSON.stringify(input)); assert.doesNotMatch((await response.json()).error, /invalid (ttl|label)/, JSON.stringify(input));