// The ports of the sidecar itself, which the proxy never admits on // loopback whatever the profile lists. const OWN_PORTS = [8931, 3128]; const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1']); // parsePorts reads `egress.loopbackPorts`, a list of ports and ranges // such as ["3000", "5000-5999"], into [low, high] pairs. An entry it // cannot read is an error, so a bad list stops the sidecar. export function parsePorts(entries) { return entries.map(entry => { const match = entry.match(/^(\d{1,5})(?:-(\d{1,5}))?$/); if (!match) throw new Error(`loopback port ${JSON.stringify(entry)} is not a port or a range`); const low = Number(match[1]); const high = Number(match[2] ?? match[1]); if (low < 1 || high > 65535 || low > high) { throw new Error(`loopback port ${JSON.stringify(entry)} is not a range within 1-65535`); } return [low, high]; }); } // isLoopbackHost is true for the three literals the proxy treats as // loopback. A name that merely resolves to loopback is not one. export function isLoopbackHost(host) { return LOOPBACK_HOSTS.has(host); } // loopbackRefusal answers why the proxy refuses a request to a loopback // host, or null when it admits it. The request must be plain http with a // method other than CONNECT, to a listed port that is not the sidecar's // own, and made by the workload or by a loopback page: a page from the // public internet makes its requests cross-site, whatever it fetches. export function loopbackRefusal({ ports, port, method, headers }) { if (method === 'CONNECT') return 'CONNECT to loopback'; if (OWN_PORTS.includes(port)) return `loopback port ${port} is the sidecar's own`; if (!ports.some(([low, high]) => port >= low && port <= high)) { return `loopback port ${port} not in egress.loopbackPorts`; } const site = headers['sec-fetch-site']; if (site === 'none' || site === 'same-origin') return null; if (loopbackOrigin(headers.origin)) return null; return `loopback request is ${site ?? 'of no known'} site, not from the workload or a loopback page`; } function loopbackOrigin(origin) { if (!origin) return false; try { const { protocol, hostname } = new URL(origin); return protocol === 'http:' && isLoopbackHost(hostname.replace(/^\[(.*)\]$/, '$1')); } catch { return false; } }