From 2be35f8ddbb26ba0950088922e8c4a52066bafff Mon Sep 17 00:00:00 2001 From: Afloat Date: Fri, 20 Nov 2026 18:16:32 +0800 Subject: [PATCH] fix: validate loopback hosts before diagnostic exemptions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ⚠️ MODEL-FACING TEXT CHANGE Failure-response host fields now mask 127-prefixed DNS names and keep a portless IPv6 loopback intact. Status, failure kind, code and retry policy are unchanged; the exact visible 502 error is covered by a regression. Require actual IPv4 loopback addresses instead of accepting any 127. prefix. Retain Node's numeric IPv4 aliases after syntax validation and canonicalization. Split bracketed display targets after their closing bracket so an address colon is never mistaken for a port separator. The unchanged base fails six behavior regressions with two controls passing. The fix passes 52 focused tests, typecheck, build and both static gates. --- src/log-mask.ts | 21 +++++- tests/loopback-diagnostic-hosts.test.ts | 96 +++++++++++++++++++++++++ 2 files changed, 114 insertions(+), 3 deletions(-) create mode 100644 tests/loopback-diagnostic-hosts.test.ts diff --git a/src/log-mask.ts b/src/log-mask.ts index 06d51a7d28..4b859d8d3e 100644 --- a/src/log-mask.ts +++ b/src/log-mask.ts @@ -292,7 +292,20 @@ function isIpv4Literal(s: string): boolean { } function isLoopbackIp(ip: string): boolean { - return ip === "::1" || ip === "0:0:0:0:0:0:0:1" || ip === "0.0.0.0" || ip.startsWith("127."); + if (ip === "::1" || ip === "0:0:0:0:0:0:0:1" || ip === "0.0.0.0") return true; + if (!ip.startsWith("127.")) return false; + if (isIpv4Literal(ip)) return true; + // The prefix alone also matches private DNS names such as + // 127.relay.internal. Preserve numeric aliases accepted by Node URLs + // (127.1, 127.0x1, etc.) only when they normalize to an actual IPv4 + // loopback address; never interpret URL syntax as part of a host. + if (!/^[0-9a-fx.]+$/i.test(ip)) return false; + try { + const normalized = new URL(`http://${ip}`).hostname; + return normalized.startsWith("127.") && isIpv4Literal(normalized); + } catch { + return false; + } } /** #4254: is this a loopback host name/address? Loopback identifies a LOCAL @@ -310,8 +323,10 @@ export function isLoopbackHost(host: string): boolean { * is masked with its port kept. Used by the upstream-failure egress path so one * message never mixes a raw loopback next to a masked . */ export function maskHostPortForDisplay(target: string): string { - const i = target.lastIndexOf(":"); - if (i <= 0) return isLoopbackHost(target) ? target : maskHostForLog(target); + // A bracketed address can have no port (new URL("http://[::1]").host). + // Only the colon after the closing bracket can delimit its port. + const i = target.startsWith("[") ? target.indexOf("]") + 1 : target.lastIndexOf(":"); + if (i <= 0 || i === target.length) return isLoopbackHost(target) ? target : maskHostForLog(target); const host = target.slice(0, i); return `${isLoopbackHost(host) ? host : maskHostForLog(host)}${target.slice(i)}`; } diff --git a/tests/loopback-diagnostic-hosts.test.ts b/tests/loopback-diagnostic-hosts.test.ts new file mode 100644 index 0000000000..7f53d7f92c --- /dev/null +++ b/tests/loopback-diagnostic-hosts.test.ts @@ -0,0 +1,96 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { + isLoopbackHost, isMaskHostsEnabled, maskHostPortForDisplay, + maskUrlForDiagnostics, maskUrlsForDiagnostics, setMaskHostsEnabled, +} from "../src/log-mask.js"; +import { describeUpstreamFailure } from "../src/upstream-proxy.js"; +import { buildProxyFailureResponse, withUpstreamFailure } from "../src/upstream-fail.js"; +import { logHostEvent } from "../src/agent/host-log.js"; +import { defaultLogFile } from "../src/paths.js"; +import { rmrf } from "./tmp-rm.js"; + +test("DNS names starting with 127 are not loopback addresses", () => { + for (const host of ["127.customer.internal", "127.0.0.1.customer.internal", "127.dead.beef"]) { + assert.equal(isLoopbackHost(host), false, host); + assert.equal(maskHostPortForDisplay(`${host}:8443`), ":8443", host); + } +}); + +test("diagnostic URL masking protects 127-prefixed private DNS names", () => { + for (const scheme of ["https", "ws", "socks5h"]) { + const input = `${scheme}://alice:synthetic-password@127.customer.internal:8443/v1?q=synthetic#fragment`; + assert.equal(maskUrlForDiagnostics(input), `${scheme}://:8443/v1`); + assert.equal(maskUrlsForDiagnostics(`dial ${input} failed`), `dial ${scheme}://:8443/v1 failed`); + } +}); + +test("the actual failure response never exposes a loopback-looking DNS name", () => { + const host = "127.customer.internal"; + const error = Object.assign(new Error(`getaddrinfo ENOTFOUND ${host}`), { code: "ENOTFOUND" }); + const failure = describeUpstreamFailure(error, `https://${host}:8443/v1`); + assert.equal(failure.detail.host, ":8443"); + const response = buildProxyFailureResponse(failure.message, withUpstreamFailure(error, failure.detail)); + assert.equal(response.status, 502); + const body = JSON.parse(response.body) as { error: string; upstreamFailure: { host: string } }; + assert.equal(body.error, "acp-proxy failure: dns ENOTFOUND :8443"); + assert.equal(body.upstreamFailure.host, ":8443"); + assert.ok(!response.body.includes(host)); +}); + +test("host-event file output masks loopback-looking private DNS names", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-loopback-hostname-")); + const previous = process.env.XDG_STATE_HOME; + process.env.XDG_STATE_HOME = dir; + try { + logHostEvent("warn", "[test-host]", "dial https://127.customer.internal:8443/v1 failed"); + const output = fs.readFileSync(defaultLogFile(), "utf8"); + assert.match(output, /dial https:\/\/:8443\/v1 failed/); + assert.ok(!output.includes("127.customer.internal")); + } finally { + if (previous === undefined) delete process.env.XDG_STATE_HOME; else process.env.XDG_STATE_HOME = previous; + await rmrf(dir); + } +}); + +test("bracketed IPv6 without a port is not split at an address colon", () => { + assert.equal(maskHostPortForDisplay("[::1]"), "[::1]"); + assert.equal(maskHostPortForDisplay("[2001:db8::1]"), ""); + const failure = describeUpstreamFailure(new Error("failed"), "http://[::1]/v1"); + assert.equal(failure.detail.host, "[::1]"); +}); + +test("genuine loopback names and IPv4 aliases remain actionable", () => { + for (const host of ["localhost", "LOCALHOST", "0.0.0.0", "127.0.0.1", "127.255.255.255", "127.1", "127.0.1", "127.0x1", "127.000.1"]) { + assert.equal(isLoopbackHost(host), true, host); + assert.equal(maskHostPortForDisplay(`${host}:8443`), `${host}:8443`, host); + const origin = `http://${host}:8443`; + assert.equal(maskUrlForDiagnostics(origin), origin, "clean loopback origins remain byte-identical"); + } + assert.equal(isLoopbackHost("[::1]"), true); + assert.equal(isLoopbackHost("0:0:0:0:0:0:0:1"), true); + assert.equal(maskHostPortForDisplay("[::1]:9000"), "[::1]:9000"); +}); + +test("invalid numeric addresses and URL syntax are not loopback hosts", () => { + for (const host of ["127.1.2.999", "127.0x1000000", "127..1", "127.0.0.1/path", "127.0.0.1@private.example", "127.0.0.1?query", "127.0.0.1\n", "localhost.private.example"]) { + assert.equal(isLoopbackHost(host), false, JSON.stringify(host)); + } +}); + +test("public hosts and explicit private-host visibility keep their existing policy", () => { + assert.equal(maskHostPortForDisplay("api.openai.com:443"), "api.openai.com:443"); + assert.equal(maskHostPortForDisplay("relay.internal:443"), ":443"); + const previous = isMaskHostsEnabled(); + setMaskHostsEnabled(false); + try { + assert.equal(maskHostPortForDisplay("127.customer.internal:8443"), "127.customer.internal:8443"); + assert.equal(maskUrlForDiagnostics("https://alice:synthetic-password@127.customer.internal/v1?q=synthetic#fragment"), "https://127.customer.internal/v1"); + assert.equal(maskHostPortForDisplay("[2001:db8::1]:8443"), "[2001:db8::1]:8443"); + } finally { + setMaskHostsEnabled(previous); + } +});