Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/api/test/fly-machines-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ describe("bounded Fly Machines client", () => {
res.writeHead(200, { "content-type": "application/json" });
}
});
const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 30, maxRetries: 0 });
const client = createFlyMachinesClient({ token, apiOrigin: origin, timeoutMs: 1_000, maxRetries: 0 });
const created = await client.createMachine("app", { image: "image" }, "op-ambiguous");
expect(created.id).toBe("m-created");
expect(createCount).toBe(1);
Expand Down
160 changes: 160 additions & 0 deletions packages/credential-proxy/src/destination-policy.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
import { connect as tlsConnect, checkServerIdentity } from "node:tls";

const DEFAULT_HTTPS_PORT = 443;

function ipv4Number(address) {
return address.split(".").reduce((value, part) => (value * 256) + Number(part), 0) >>> 0;
}

function ipv6Number(address) {
let source = address.toLowerCase();
if (source.includes(".")) {
const lastColon = source.lastIndexOf(":");
const v4 = ipv4Number(source.slice(lastColon + 1));
source = `${source.slice(0, lastColon)}:${(v4 >>> 16).toString(16)}:${(v4 & 0xffff).toString(16)}`;
}
const halves = source.split("::");
const left = halves[0] ? halves[0].split(":") : [];
const right = halves[1] ? halves[1].split(":") : [];
const groups = halves.length === 1 ? left : [...left, ...Array(8 - left.length - right.length).fill("0"), ...right];
return groups.reduce((value, group) => (value << 16n) | BigInt(`0x${group || "0"}`), 0n);
}

function inV4Range(address, network, prefix) {
const shift = 32 - prefix;
return (ipv4Number(address) >>> shift) === (ipv4Number(network) >>> shift);
}

function inV6Range(value, network, prefix) {
const shift = 128n - BigInt(prefix);
return (value >> shift) === (ipv6Number(network) >> shift);
}

const NON_PUBLIC_V4 = [
["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8],
["169.254.0.0", 16], ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24],
["192.88.99.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["198.51.100.0", 24],
["203.0.113.0", 24], ["224.0.0.0", 4], ["240.0.0.0", 4],
];

const NON_PUBLIC_V6 = [
["::", 128], ["::1", 128], ["::", 96], ["64:ff9b::", 96], ["64:ff9b:1::", 48],
["100::", 64], ["2001::", 23], ["2001:db8::", 32], ["2002::", 16],
["fc00::", 7], ["fe80::", 10], ["ff00::", 8],
];

/** Return true only for globally routable IP literals. */
export function isPublicAddress(address) {
if (typeof address !== "string") return false;
const unzoned = address.split("%")[0];
const family = isIP(unzoned);
if (family === 4) return !NON_PUBLIC_V4.some(([network, prefix]) => inV4Range(unzoned, network, prefix));
if (family !== 6) return false;

const value = ipv6Number(unzoned);
// IPv4-mapped IPv6 addresses inherit the embedded IPv4 address policy.
if (value >> 32n === 0xffffn) {
const embedded = Number(value & 0xffffffffn);
return isPublicAddress([24, 16, 8, 0].map((shift) => (embedded >>> shift) & 255).join("."));
}
// Global unicast is the only IPv6 range eligible for outbound connections.
if ((value >> 125n) !== 1n) return false; // 2000::/3
return !NON_PUBLIC_V6.some(([network, prefix]) => inV6Range(value, network, prefix));
}

function parseHttpsUrl(value, label) {
if (typeof value !== "string" || !value || value !== value.trim() || value.includes("\\")) {
throw new TypeError(`${label} must be an absolute HTTPS URL`);
}
const authorityMatch = /^https:\/\/([^/?#]*)/i.exec(value);
const authority = authorityMatch?.[1] ?? "";
if (!authority || /[%\\\s@]/.test(authority) || authority.endsWith(":")) {
throw new TypeError(`${label} has a malformed authority`);
}
let url;
try { url = new URL(value); } catch { throw new TypeError(`${label} must be an absolute HTTPS URL`); }
if (url.protocol !== "https:") throw new TypeError(`${label} must use HTTPS`);
if (url.username || url.password) throw new TypeError(`${label} must not contain credentials`);
if (!url.hostname || /[%\s]/.test(url.hostname)) throw new TypeError(`${label} has a malformed host`);
const hostname = url.hostname.startsWith("[") ? url.hostname.slice(1, -1).toLowerCase() : url.hostname.toLowerCase();
const family = isIP(hostname);
if (!family && (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(hostname))) {
throw new TypeError(`${label} has a malformed host`);
}
const port = url.port ? Number(url.port) : DEFAULT_HTTPS_PORT;
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new TypeError(`${label} has an invalid port`);
return { url, hostname, port, family };
}

function normalizeAddress(address) {
let value = String(address).split("%")[0].toLowerCase();
if (value.startsWith("::ffff:")) {
const mapped = value.slice(7);
if (isIP(mapped) === 4) value = mapped;
else if (mapped.includes(":")) {
const words = mapped.split(":");
const high = Number.parseInt(words.at(-2), 16);
const low = Number.parseInt(words.at(-1), 16);
value = [high >>> 8, high & 255, low >>> 8, low & 255].join(".");
}
}
if (isIP(value) === 6) return `v6:${ipv6Number(value).toString(16)}`;
return value;
}

async function resolveAll(hostname) {
if (isIP(hostname)) return [{ address: hostname, family: isIP(hostname) }];
return lookup(hostname, { all: true, verbatim: true });
}

function openTlsSocket({ hostname, port, address }) {
return new Promise((resolve, reject) => {
const socket = tlsConnect({
host: address,
port,
servername: isIP(hostname) ? undefined : hostname,
checkServerIdentity: (_server, certificate) => checkServerIdentity(hostname, certificate),
});
const failed = (error) => { socket.destroy(); reject(error); };
socket.once("error", failed);
socket.once("secureConnect", () => {
socket.removeListener("error", failed);
resolve(socket);
});
});
}

/**
* Build a connector bound to one configured HTTPS origin. Every DNS answer is
* checked, and the selected public address is passed directly to the connector
* so a second DNS lookup cannot change the destination between validation and
* connection. Paths, queries, methods, and bodies remain available to callers.
*/
export function createOriginConnector(configuredOrigin, { resolve = resolveAll, connect = openTlsSocket } = {}) {
const configured = parseHttpsUrl(configuredOrigin, "configured origin");
if (configured.url.pathname !== "/" || configured.url.search || configured.url.hash) {
throw new TypeError("configured origin must contain only an HTTPS origin");
}
return async function connectToOrigin(requestUrl) {
const target = parseHttpsUrl(requestUrl, "request URL");
if (target.url.origin !== configured.url.origin || target.hostname !== configured.hostname || target.port !== configured.port) {
throw new TypeError("request URL does not match the configured HTTPS origin");
}
const answers = await resolve(target.hostname);
if (!Array.isArray(answers) || answers.length === 0) throw new Error("origin did not resolve to an address");
for (const answer of answers) {
if (!answer || !isPublicAddress(answer.address)) throw new Error("origin resolved to a non-public address");
}
const address = answers[0].address;
const socket = await connect({ hostname: target.hostname, port: target.port, address, servername: target.hostname });
const rawPeerAddress = socket?.remoteAddress ?? "";
const peerAddress = normalizeAddress(rawPeerAddress);
if (!peerAddress || peerAddress !== normalizeAddress(address) || !isPublicAddress(rawPeerAddress)) {
socket?.destroy?.();
throw new Error("connected peer did not match the validated public address");
}
return { socket, url: target.url };
};
}
110 changes: 110 additions & 0 deletions packages/credential-proxy/test/destination-policy.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createOriginConnector, isPublicAddress } from "../src/destination-policy.mjs";

test("URL policy permits paths and queries only on the configured HTTPS origin", async () => {
const calls = [];
const connect = createOriginConnector("https://api.example.test:8443", {
resolve: async (hostname) => {
assert.equal(hostname, "api.example.test");
return [{ address: "93.184.216.34", family: 4 }];
},
connect: async (options) => {
calls.push(options);
return { remoteAddress: "93.184.216.34" };
},
});

const result = await connect("https://api.example.test:8443/v1/items?limit=5");
assert.equal(result.url.pathname, "/v1/items");
assert.equal(result.url.search, "?limit=5");
assert.deepEqual(calls, [{ hostname: "api.example.test", port: 8443, address: "93.184.216.34", servername: "api.example.test" }]);
});

test("rejects unsafe and malformed request URLs before resolution", async () => {
let resolutions = 0;
const connect = createOriginConnector("https://api.example.test", {
resolve: async () => { resolutions += 1; return [{ address: "93.184.216.34" }]; },
connect: async () => ({ remoteAddress: "93.184.216.34" }),
});
const urls = [
"http://api.example.test/", "file://api.example.test/", "ftp://api.example.test/",
"https://user:pass@api.example.test/", "https://api.example.test.evil.test/",
"https://api.example.test:444/", "https://api.example.test:0/", "https://api.example.test:65536/",
"https://api.example.test:/", "https://%61pi.example.test/", "https://2130706433/",
"https://api.example.test\\@evil.test/", "https://[not-ipv6]/", "https://api_example.test/",
];
for (const url of urls) await assert.rejects(connect(url), { name: "TypeError" }, url);
assert.equal(resolutions, 0);
});

test("configured origin rejects credentials, paths, queries, fragments, and non-HTTPS schemes", () => {
for (const origin of [
"http://api.example.test", "https://user@api.example.test", "https://api.example.test/path",
"https://api.example.test?x=1", "https://api.example.test#fragment", "https://",
]) assert.throws(() => createOriginConnector(origin), TypeError, origin);
});

test("encoded IPv4 authorities normalize to private IP literals and are denied", async () => {
for (const origin of ["https://2130706433", "https://0x7f000001", "https://0177.0.0.1", "https://127.1"]) {
const connect = createOriginConnector(origin);
await assert.rejects(connect(`${origin}/metadata`), /non-public address/, origin);
}
});

test("public address classification covers IPv4, IPv6, mapped and encoded ranges", () => {
const cases = [
["93.184.216.34", true], ["8.8.8.8", true], ["2001:4860:4860::8888", true], ["2606:4700:4700::1111", true],
["0.1.2.3", false], ["10.2.3.4", false], ["100.64.0.1", false], ["127.0.0.1", false],
["169.254.169.254", false], ["172.16.0.1", false], ["192.168.1.1", false], ["192.0.2.10", false],
["198.18.0.1", false], ["198.51.100.4", false], ["203.0.113.1", false], ["224.0.0.1", false],
["::", false], ["::1", false], ["fc00::1", false], ["fe80::1", false], ["ff02::1", false],
["2001:db8::1", false], ["2002:0808:0808::1", false], ["::ffff:127.0.0.1", false],
["1000::1", false], ["4000::1", false],
["::ffff:8.8.8.8", true], ["64:ff9b::a00:1", false], ["::7f00:1", false],
];
for (const [address, expected] of cases) assert.equal(isPublicAddress(address), expected, address);
assert.equal(isPublicAddress("not-an-ip"), false);
});

test("rejects mixed public/private DNS answers and empty answers", async () => {
for (const answers of [
[{ address: "93.184.216.34" }, { address: "10.0.0.4" }],
[{ address: "93.184.216.34" }, { address: "::ffff:127.0.0.1" }],
[],
]) {
let connections = 0;
const connect = createOriginConnector("https://api.example.test", {
resolve: async () => answers,
connect: async () => { connections += 1; return { remoteAddress: "93.184.216.34" }; },
});
await assert.rejects(connect("https://api.example.test/path"));
assert.equal(connections, 0);
}
});

test("pins the validated address and rejects a changed connected peer", async () => {
let resolutions = 0;
let connectorAddress;
const connect = createOriginConnector("https://api.example.test", {
resolve: async () => {
resolutions += 1;
return [{ address: "93.184.216.34" }];
},
connect: async ({ address }) => {
connectorAddress = address;
return { remoteAddress: "8.8.4.4", destroy() { this.destroyed = true; } };
},
});
await assert.rejects(connect("https://api.example.test/"), /connected peer did not match/);
assert.equal(resolutions, 1, "the connector must not perform a second DNS resolution");
assert.equal(connectorAddress, "93.184.216.34", "the validated address is the address given to the connector");
});

test("accepts equivalent IPv6 peer spellings after address pinning", async () => {
const connect = createOriginConnector("https://[2606:4700:4700::1111]", {
resolve: async () => [{ address: "2606:4700:4700:0:0:0:0:1111" }],
connect: async () => ({ remoteAddress: "2606:4700:4700::1111" }),
});
await connect("https://[2606:4700:4700::1111]/health");
});
6 changes: 3 additions & 3 deletions scripts/validation.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { runProcess } from "./portable-proxy-test-helpers.mjs";

const lane = process.argv[2] ?? "all";
const expectedNode = "24.12.0";
const suiteTimeoutMs = 540_000;
const suiteTimeoutMs = 580_000;
const lanes = {
backend: [
["generated contracts", "npm", ["run", "generate"], 90_000],
["generated contract drift", "git", ["diff", "--exit-code", "--", "packages/docs/openapi.yaml", "packages/api-client/src/schema.d.ts"], 15_000],
["application build", "npm", ["run", "build", "--workspace=factorize-app"], 90_000],
["backend checks", "npm", ["run", "check:backend"], 240_000],
["backend checks", "npm", ["run", "check:backend"], 270_000],
["compiled app/API/PostgreSQL integration", "npm", ["run", "test:static-slice", "--workspace=factorize"], 90_000],
],
browser: [
Expand All @@ -21,7 +21,7 @@ const lanes = {
],
proxy: [
["portable proxy harness checks", process.execPath, ["--test", "scripts/validation-runner.test.mjs"], 30_000],
["credential proxy process checks", process.execPath, ["--test", "packages/credential-proxy/test/runtime-process.test.mjs"], 30_000],
["credential proxy checks", process.execPath, ["--test", "packages/credential-proxy/test/*.test.mjs"], 30_000],
],
};

Expand Down
Loading