From f7ee7738b6be558a0b24f46829a91de8478c7a5d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 16:26:48 -0600 Subject: [PATCH] fix(proxy-relay): strictly validate target ports --- bin/proxy-port.mjs | 23 +++++++ bin/proxy-port.test.mjs | 145 +++++++++++++++++++++++++++++++++++++++- bin/proxy-relay.mjs | 11 +-- 3 files changed, 169 insertions(+), 10 deletions(-) diff --git a/bin/proxy-port.mjs b/bin/proxy-port.mjs index 52bff38ea3..be93b418bf 100644 --- a/bin/proxy-port.mjs +++ b/bin/proxy-port.mjs @@ -23,6 +23,20 @@ export const parseProxyPortValue = (name, raw, fallback) => { ); }; +// Validate each comma-separated target; one bad entry must reject the whole list. +export const parseProxyPortListValue = (name, raw) => { + if (raw === undefined || raw === '') { + throw new Error(`${name} is required (comma list)`); + } + return raw.split(',').map((segment) => { + const value = segment.trim(); + if (value === '') { + throw new Error(`${name}="${raw}" contains an empty port segment`); + } + return parseProxyPortValue(name, value); + }); +}; + // Strict port parsing for a host:port address taken from an env var // (#494). The port is the segment after the last ':'; anything that is // not exactly an integer 1-65535 is an error naming the variable and @@ -47,6 +61,15 @@ export const parseProxyPort = (name, fallback) => { } }; +export const parseProxyPortList = (name) => { + try { + return parseProxyPortListValue(name, process.env[name]); + } catch (err) { + console.error(err.message); + process.exit(1); + } +}; + const MAX_TIMEOUT_MS = 2147483647; // 2^31 - 1 (setTimeout 32-bit signed int limit) export const parseProxyMillisValue = (name, raw, fallback) => { diff --git a/bin/proxy-port.test.mjs b/bin/proxy-port.test.mjs index d39813db36..47fd4e6d69 100644 --- a/bin/proxy-port.test.mjs +++ b/bin/proxy-port.test.mjs @@ -4,10 +4,16 @@ import assert from 'node:assert/strict'; import { spawn, spawnSync } from 'node:child_process'; import fs from 'node:fs'; import net from 'node:net'; +import os from 'node:os'; import path from 'node:path'; import test from 'node:test'; import { fileURLToPath } from 'node:url'; -import { parseProxyPortValue, parseAddressPortValue, parseProxyMillisValue } from './proxy-port.mjs'; +import { + parseProxyPortValue, + parseProxyPortListValue, + parseAddressPortValue, + parseProxyMillisValue +} from './proxy-port.mjs'; const binDir = path.dirname(fileURLToPath(import.meta.url)); @@ -63,6 +69,48 @@ test('invalid values throw an error naming the env var and the value', () => { } }); +test('comma-separated proxy port lists preserve trimmed decimal ports and order', () => { + assert.deepEqual(parseProxyPortListValue('RELAY_TARGET_PORTS', '18745,19745'), [ + 18745, + 19745 + ]); + assert.deepEqual( + parseProxyPortListValue('RELAY_TARGET_PORTS', ' 18745 , 019745 , 18745 '), + [18745, 19745, 18745] + ); +}); + +test('comma-separated proxy port lists reject invalid and empty segments', () => { + const invalid = [ + ['18745,19745junk', '19745junk'], + ['garbage', 'garbage'], + ['18745,99999', '99999'], + ['18745,19745.9', '19745.9'], + ['1e4', '1e4'], + ['0x4a39', '0x4a39'], + ['18745,,19745', '18745,,19745'], + ['18745,', '18745,'], + [',18745', ',18745'] + ]; + for (const [raw, offending] of invalid) { + assert.throws( + () => parseProxyPortListValue('RELAY_TARGET_PORTS', raw), + (err) => { + assert.match(err.message, /RELAY_TARGET_PORTS/); + assert.ok(err.message.includes(`"${offending}"`), err.message); + return true; + }, + `expected ${JSON.stringify(raw)} to be rejected` + ); + } + for (const raw of [undefined, '']) { + assert.throws( + () => parseProxyPortListValue('RELAY_TARGET_PORTS', raw), + /RELAY_TARGET_PORTS is required/ + ); + } +}); + test('host:port addresses are parsed strictly (#494)', () => { assert.equal(parseAddressPortValue('ANTIGRAVITY_LS_ADDRESS', '127.0.0.1:18745'), 18745); assert.equal(parseAddressPortValue('ANTIGRAVITY_LS_ADDRESS', 'localhost:1'), 1); @@ -114,6 +162,17 @@ const runClef = (value) => timeout: 10000 }); +const runRelay = (value) => + spawnSync(process.execPath, [path.join(binDir, 'proxy-relay.mjs')], { + env: { + ...process.env, + RELAY_LISTEN_PORT: '18744', + RELAY_TARGET_PORTS: value + }, + encoding: 'utf8', + timeout: 10000 + }); + test('clef-proxy exits at startup naming the var for abc / 0x… / 99999', () => { for (const raw of ['abc', '0x4a38', '99999']) { const result = runClef(raw); @@ -124,6 +183,90 @@ test('clef-proxy exits at startup naming the var for abc / 0x… / 99999', () => } }); +test('proxy-relay rejects every invalid target segment at startup', () => { + const invalid = [ + ['garbage', 'garbage'], + ['18745,19745junk', '19745junk'], + ['18745,99999', '99999'], + ['18745,19745.9', '19745.9'], + ['1e4', '1e4'], + ['0x4a39', '0x4a39'], + ['18745,,19745', '18745,,19745'], + ['18745,', '18745,'], + [',18745', ',18745'] + ]; + for (const [raw, offending] of invalid) { + const result = runRelay(raw); + assert.equal(result.status, 1, `value ${raw}: ${result.stderr}`); + assert.match(result.stderr, /RELAY_TARGET_PORTS/); + assert.ok(result.stderr.includes(`"${offending}"`), result.stderr); + assert.doesNotMatch(result.stdout, /listening/); + } +}); + +test('proxy-relay starts with an ordered valid target list', async (t) => { + const probe = net.createServer(); + await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); + const port = probe.address().port; + await new Promise((resolve) => probe.close(resolve)); + + const stateHome = fs.mkdtempSync(path.join(os.tmpdir(), 'proxy-relay-test-')); + const child = spawn(process.execPath, [path.join(binDir, 'proxy-relay.mjs')], { + env: { + ...process.env, + RELAY_LISTEN_HOST: '127.0.0.1', + RELAY_LISTEN_PORT: String(port), + RELAY_TARGET_PORTS: '18745,19745', + RELAY_NAME: 'relay-valid-targets', + XDG_STATE_HOME: stateHome + }, + stdio: ['ignore', 'pipe', 'pipe'] + }); + t.after(async () => { + child.kill(); + await new Promise((resolve) => { + if (child.exitCode !== null) resolve(); + else child.once('exit', resolve); + }); + fs.rmSync(stateHome, { recursive: true, force: true }); + }); + + const listening = await new Promise((resolve, reject) => { + let out = ''; + let err = ''; + const timer = setTimeout( + () => reject(new Error(`no listening line: ${out} ${err}`)), + 10000 + ); + child.stdout.on('data', (chunk) => { + out += chunk; + if (out.includes('relay http://')) { + clearTimeout(timer); + resolve(out); + } + }); + child.stderr.on('data', (chunk) => { err += chunk; }); + child.on('exit', () => { + clearTimeout(timer); + reject(new Error(`proxy-relay exited early: ${out} ${err}`)); + }); + }); + assert.ok(listening.includes('18745|19745'), listening); + + const response = await fetch(`http://127.0.0.1:${port}/health`); + assert.equal(response.status, 200); + const health = await response.json(); + assert.equal(health.target, '100.99.113.103:18745|19745'); + assert.equal(health.preferredTarget, 18745); + const endpoint = JSON.parse( + fs.readFileSync( + path.join(stateHome, 'relay-valid-targets', 'endpoint.json'), + 'utf8' + ) + ); + assert.equal(endpoint.relayTo, '100.99.113.103:18745'); +}); + test('clef-proxy binds exactly the requested valid port', async (t) => { const probe = net.createServer(); await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); diff --git a/bin/proxy-relay.mjs b/bin/proxy-relay.mjs index 75a7ddbee5..e59a31321d 100644 --- a/bin/proxy-relay.mjs +++ b/bin/proxy-relay.mjs @@ -34,7 +34,7 @@ import fs from 'node:fs'; import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; -import { parseProxyPort } from './proxy-port.mjs'; +import { parseProxyPort, parseProxyPortList } from './proxy-port.mjs'; const LISTEN_PORT = parseProxyPort('RELAY_LISTEN_PORT', 0); if (!LISTEN_PORT) { @@ -43,14 +43,7 @@ if (!LISTEN_PORT) { } const LISTEN_HOST = process.env.RELAY_LISTEN_HOST || '127.0.0.1'; const TARGET_HOST = process.env.RELAY_TARGET_HOST || '100.99.113.103'; -const TARGET_PORTS = (process.env.RELAY_TARGET_PORTS || '') - .split(',') - .map((s) => Number(s.trim())) - .filter((n) => Number.isInteger(n) && n >= 1 && n <= 65535); -if (TARGET_PORTS.length === 0) { - console.error('RELAY_TARGET_PORTS is required (comma list)'); - process.exit(1); -} +const TARGET_PORTS = parseProxyPortList('RELAY_TARGET_PORTS'); const PROXY_HOST = process.env.RELAY_PROXY_HOST || 'hatch-egress-proxy'; const PROXY_PORT = parseProxyPort('RELAY_PROXY_PORT', 3130); const NAME = process.env.RELAY_NAME || `relay-${LISTEN_PORT}`;