diff --git a/plugin-sdk/.gitignore b/plugin-sdk/.gitignore index 3c25e1e49..119eb1dd2 100644 --- a/plugin-sdk/.gitignore +++ b/plugin-sdk/.gitignore @@ -1,3 +1,4 @@ node_modules/ dist/ +src/generated/egress-policy.ts *.log diff --git a/plugin-sdk/CLAUDE.md b/plugin-sdk/CLAUDE.md index ef0a8abb3..756483c1b 100644 --- a/plugin-sdk/CLAUDE.md +++ b/plugin-sdk/CLAUDE.md @@ -31,7 +31,7 @@ Because the package ships standalone it cannot import server code, so several fi | SDK copy | Source of truth | Parity test | |---|---|---| | `src/generated/host-facts.ts` (permissions, RPC methods, hooks, event catalog, `KNOWN_ADDONS`, the output contract `PLUGIN_ENTITY_FIELDS` / `PLUGIN_ENTITY_NESTED` / `PLUGIN_METHOD_RESULT`) | `server/src/nest/plugins/protocol/envelope.ts`, `protocol/output-contract.ts` and `server/src/addons.ts` via `server/scripts/gen-plugin-facts.ts` (**machine-written, never hand-edit**) | server `check:plugin-facts` CI gate; the entity interfaces in `src/index.ts` are type-checked against `PLUGIN_ENTITY_FIELDS` | -| `src/egress-policy.ts` (pure helpers, kept **byte-identical**) | `server/src/nest/plugins/runtime/egress-policy.ts` | `test/permissions-parity.test.ts` | +| `src/egress-policy.ts` imports the generated policy written by `scripts/sync-egress-policy.mjs` | `server/src/nest/plugins/runtime/egress-policy.ts` | `test/permissions-parity.test.ts` | | `src/plugin-data-contract.ts` (the `ctx.db` contract `dev` and the mock host apply: the caps, the refusal texts, the NUL refusal and the transaction-control refusal, the whole file **byte-identical**) | `server/src/db/engine/plugin-data-contract.ts` | `test/permissions-parity.test.ts` | | `src/manifest.ts` (validation rules incl. the `trek` version range; its patterns, sets, caps and `PLUGIN_API_VERSION` come from `generated/host-facts.ts`, written from `server/src/nest/plugins/protocol/manifest-rules.ts`) | `server/src/nest/plugins/install/manifest.ts` | the verdicts: `test/fixtures/manifest-corpus.ts`, run here by `test/manifest-corpus.test.ts` and through both validators by `server/tests/unit/plugins/manifest-parity.test.ts` (the SDK may only be stricter, case by case) | | `src/index.ts` (the plugin API types) | `server/src/nest/plugins/runtime/plugin-sdk.ts` (the child's copy) | `test/host-types.test-d.ts` (vitest typecheck mode, on inside the monorepo): plain shapes equal, ctx-carrying shapes and every ctx namespace with the same members; `test/host-types-names.test.ts` makes it list every shared name | diff --git a/plugin-sdk/package.json b/plugin-sdk/package.json index a803db8a7..7072adbf8 100644 --- a/plugin-sdk/package.json +++ b/plugin-sdk/package.json @@ -68,8 +68,8 @@ "update-notifier": "^7.3.1" }, "scripts": { - "build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node scripts/finish-cjs.mjs", - "typecheck": "tsc -p tsconfig.json --noEmit", + "build": "node scripts/sync-egress-policy.mjs && tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && node scripts/finish-cjs.mjs", + "typecheck": "node scripts/sync-egress-policy.mjs && tsc -p tsconfig.json --noEmit", "test": "vitest run", "test:coverage": "vitest run --coverage", "prepublishOnly": "npm run build && npm test" diff --git a/plugin-sdk/scripts/sync-egress-policy.mjs b/plugin-sdk/scripts/sync-egress-policy.mjs new file mode 100644 index 000000000..402e2f9a9 --- /dev/null +++ b/plugin-sdk/scripts/sync-egress-policy.mjs @@ -0,0 +1,11 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; + +const source = new URL('../../server/src/nest/plugins/runtime/egress-policy.ts', import.meta.url); +const directory = new URL('../src/generated/', import.meta.url); +const target = new URL('egress-policy.ts', directory); + +const policy = readFileSync(source, 'utf8'); +if (!existsSync(target) || readFileSync(target, 'utf8') !== policy) { + mkdirSync(directory, { recursive: true }); + writeFileSync(target, policy); +} diff --git a/plugin-sdk/src/egress-policy.ts b/plugin-sdk/src/egress-policy.ts index 0e9d18a86..d5f577a5c 100644 --- a/plugin-sdk/src/egress-policy.ts +++ b/plugin-sdk/src/egress-policy.ts @@ -8,10 +8,8 @@ * worked perfectly in dev and was refused the moment it was installed. This closes * that gap. * - * The pure helpers below (isBlockedIp, makeHostAllow, classifyConnect, …) are copied - * VERBATIM from the server's runtime/egress-policy.ts — trek-plugin-sdk ships - * standalone and cannot import across the package boundary. test/permissions-parity.test.ts - * fails if the two drift. + * The shared policy is generated from the server source at build time. + * The published SDK ships the compiled module alongside this guard. * * What is deliberately NOT mirrored: the host also locks its wrappers * non-configurable and disables process.binding, to contain a HOSTILE plugin in a @@ -28,244 +26,13 @@ import dgram from 'node:dgram'; // Pure policy helpers — kept byte-identical to the server's egress-policy.ts. // --------------------------------------------------------------------------- +import { + makeHostAllow, guardSocketConnect, guardDnsLookup, guardDatagramCall, dgramSendTarget, dgramConnectTarget, +} from './generated/egress-policy.js'; + +export * from './generated/egress-policy.js'; + const apply = Reflect.apply; -const stringSlice = String.prototype.slice; -const stringIndexOf = String.prototype.indexOf; -const stringLower = String.prototype.toLowerCase; -const stringEndsWith = String.prototype.endsWith; -const regexExec = RegExp.prototype.exec; -const numberToString = Number.prototype.toString; -const parseInt = Number.parseInt; -const arrayIsArray = Array.isArray; -const ownKeys = Reflect.ownKeys; -const ownDescriptor = Object.getOwnPropertyDescriptor; -const createObject = Object.create; - -const slice = (s: string, start: number, end?: number): string => apply(stringSlice, s, [start, end]); -const indexOf = (s: string, token: string, start = 0): number => apply(stringIndexOf, s, [token, start]); -const lower = (s: string): string => apply(stringLower, s, []); -const exec = (expression: RegExp, s: string): RegExpExecArray | null => apply(regexExec, expression, [s]); -const hex = (n: number): string => apply(numberToString, n, [16]); - -/** - * Block outbound connections to loopback / private / link-local / ULA / carrier- - * grade-NAT / cloud-metadata / multicast / reserved destinations. This is the - * SSRF backstop: even a declared host that (re)resolves to one of these is - * refused, so a plugin can't pivot to trek.db's host, the 169.254.169.254 - * metadata IP, the local docker network, or other internal services. - */ -export function isBlockedIp(ip: string): boolean { - const v4 = exec(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/, ip); - if (v4) { - const a = +v4[1]; - const b = +v4[2]; - return ( - a === 0 || - a === 10 || - a === 127 || - (a === 172 && b >= 16 && b <= 31) || - (a === 192 && b === 168) || - (a === 169 && b === 254) || // link-local, incl. 169.254.169.254 metadata - (a === 100 && b >= 64 && b <= 127) || // CGNAT 100.64/10 - a >= 224 // multicast + reserved - ); - } - // IPv6: expand to 8 hextets so EVERY spelling is checked (compressed `::`, - // hex IPv4-mapped `::ffff:a9fe:a9fe`, dotted `::ffff:169.254.169.254`, `0::1`). - const g = expandV6(slice(ip, ip[0] === '[' ? 1 : 0, ip[ip.length - 1] === ']' ? -1 : undefined)); - if (g) { - // IPv4-mapped (::ffff:x) and IPv4-compatible (::x) → check the embedded IPv4. - if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0 && (g[5] === 0xffff || g[5] === 0)) { - return isBlockedIp(`${g[6] >> 8}.${g[6] & 0xff}.${g[7] >> 8}.${g[7] & 0xff}`); - } - if ((g[0] & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local - if ((g[0] & 0xfe00) === 0xfc00) return true; // fc00::/7 ULA - // IPv6 transition addresses (NAT64/6to4/Teredo) embedding an IPv4 → re-check - // the embedded target, so a NAT64 spelling of 169.254.169.254 can't tunnel past. - const embedded = embeddedTransitionIpv4(g); - if (embedded) return isBlockedIp(embedded); - } - return false; -} - -/** - * If the expanded hextets `g` are an IPv6 transition address that embeds an IPv4 - * target, return that IPv4 in dotted form; otherwise null. Recognises the NAT64 - * well-known prefix `64:ff9b::/96`, 6to4 `2002::/16`, and Teredo `2001:0000::/32`. - * Kept local so this module stays dependency-free for the isolated plugin child. - */ -function embeddedTransitionIpv4(g: number[]): string | null { - const v4 = (hi: number, lo: number) => `${hi >> 8}.${hi & 0xff}.${lo >> 8}.${lo & 0xff}`; - // NAT64 well-known 64:ff9b::/96 — first 96 bits fixed, last 32 = IPv4. - if (g[0] === 0x0064 && g[1] === 0xff9b && g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0) { - return v4(g[6], g[7]); - } - // 6to4 2002::/16 — hextets 1,2 = IPv4. - if (g[0] === 0x2002) return v4(g[1], g[2]); - // Teredo 2001:0000::/32 — last 32 bits = client IPv4 XOR 0xffffffff. - if (g[0] === 0x2001 && g[1] === 0x0000) return v4(g[6] ^ 0xffff, g[7] ^ 0xffff); - return null; -} - -/** Expand an IPv6 literal into its 8 numeric hextets, or null if not a valid IPv6. */ -function expandV6(ip: string): number[] | null { - const zone = indexOf(ip, '%'); - let host = lower(zone === -1 ? ip : slice(ip, 0, zone)); - if (indexOf(host, ':') === -1) return null; - const dotted = exec(/^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/, host); - if (dotted) { - const a = +dotted[2]; - const b = +dotted[3]; - const c = +dotted[4]; - const d = +dotted[5]; - if (a > 255 || b > 255 || c > 255 || d > 255) return null; - host = `${dotted[1]}${hex((a << 8) | b)}:${hex((c << 8) | d)}`; - } - const groups = [0, 0, 0, 0, 0, 0, 0, 0]; - const gap = indexOf(host, '::'); - if (gap === -1) return readGroups(host, groups, 0) === 8 ? groups : null; - - const head = readGroups(slice(host, 0, gap), groups, 0); - if (head < 0) return null; - const tail = slice(host, gap + 2); - let start = tail.length ? 7 : 8; - for (let i = 0; i < tail.length; i++) if (tail[i] === ':') start--; - if (start <= head) return null; - return readGroups(tail, groups, start) === 8 ? groups : null; -} - -function readGroups(source: string, groups: number[], start: number): number { - if (!source) return start; - let from = 0; - while (start < groups.length) { - const next = indexOf(source, ':', from); - const group = slice(source, from, next === -1 ? undefined : next); - if (!exec(/^[0-9a-f]{1,4}$/, group)) return -1; - groups[start++] = parseInt(group, 16); - if (next === -1) return start; - from = next + 1; - } - return -1; -} - -/** Build a declared-egress host matcher (exact host or `*.suffix` wildcard). */ -export function makeHostAllow(egress: string[]): (host: string) => boolean { - const patterns = egress - .map((h) => h.trim().toLowerCase().replace(/\.$/, '')) // drop a trailing dot (FQDN trick) - .filter((p) => p && p !== '*') - // A wildcard must have a real multi-label suffix — reject the degenerate - // `*.` (matched any trailing-dot host = allow-all) and whole-TLD `*.com`. - .filter((p) => !p.startsWith('*.') || p.slice(2).includes('.')); - return (host: string) => { - const h = lower(host[host.length - 1] === '.' ? slice(host, 0, -1) : host); - for (let i = 0; i < patterns.length; i++) { - const pattern = patterns[i]; - const matches = - pattern[0] === '*' ? h === slice(pattern, 2) || apply(stringEndsWith, h, [slice(pattern, 1)]) : h === pattern; - if (matches) return true; - } - return false; - }; -} - -export interface ConnectTarget { - kind: 'local' | 'literal-ip' | 'hostname'; - host: string; -} - -/** - * Destination host of a `dgram.Socket.send(msg[, offset, length], port[, address][, cb])` - * call, or null when no explicit address is given (Node then uses the socket's - * connected remote or the localhost default — the connect() wrapper already - * vetted that, and a localhost default is not an exfil vector). Only an explicit - * address string is a target we must allowlist. Mirrors both send() overloads: - * the (offset, length) form pushes port/address two slots right. - */ -export function dgramSendTarget(args: unknown[]): string | null { - const offsetForm = typeof args[1] === 'number' && typeof args[2] === 'number'; - const address = args[offsetForm ? 4 : 2]; - return typeof address === 'string' ? address : null; -} - -/** - * Destination host of a `dgram.Socket.connect(port[, address][, cb])` call, or - * null when no address is given (localhost default — not an exfil vector). - */ -export function dgramConnectTarget(args: unknown[]): string | null { - return typeof args[1] === 'string' ? (args[1] as string) : null; -} - -/** - * Node's `net.connect()` pre-normalises its arguments into an `[options, callback]` - * array and then calls `Socket.prototype.connect` with THAT ARRAY as the single - * argument. undici's plain-HTTP connector takes this path; its TLS connector does - * not — which is why HTTPS egress worked and plain HTTP silently did not. - * - * Unwrap it before anything reads `host`/`path`, or those come back undefined off an - * array, every plain-HTTP request a plugin makes is misclassified as `localhost`, and - * it is rejected with a nonsense "localhost is not in the plugin's declared hosts". - */ -export function unwrapConnectArgs(args: unknown[]): unknown[] { - const first = args[0]; - return arrayIsArray(first) ? first : args; -} - -/** Prepare one set of options for validation and connection. */ -export function snapshotConnectArgs(rawArgs: unknown[]): [options: Record, callback: unknown] { - const args = unwrapConnectArgs(rawArgs); - const first = args[0]; - const options = createObject(null) as Record; - let callback = args[1]; - if (first && typeof first === 'object') { - const keys = ownKeys(first); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const descriptor = ownDescriptor(first, key); - if (!descriptor?.enumerable) continue; - if (!ownDescriptor(descriptor, 'value')) throw new Error('egress: socket options must use data properties'); - options[key] = descriptor.value; - } - } else if (typeof first === 'string' && !exec(/^\d+$/, first)) { - options.path = first; - } else { - options.port = first; - if (typeof callback === 'string') { - options.host = callback; - callback = args[2]; - } - } - if (options.path != null && typeof options.path !== 'string') throw new Error('egress: invalid socket path'); - if (options.host != null && typeof options.host !== 'string') throw new Error('egress: invalid socket host'); - if (options.port != null && typeof options.port !== 'string' && typeof options.port !== 'number') { - throw new Error('egress: invalid socket port'); - } - return [options, callback]; -} - -/** - * Classify a `net.Socket.connect(...)` argument list into what we must check: - * a unix-socket/pipe (local, allowed), a literal IP (checked synchronously), or - * a hostname (allowlist + a DNS-resolving guard). Mirrors Node's connect - * overloads: connect(options[,cb]) | connect(port[,host][,cb]) | connect(path[,cb]), - * plus the pre-normalised array form above. - */ -export function classifyConnect(rawArgs: unknown[], isIP: (s: string) => boolean): ConnectTarget { - const args = unwrapConnectArgs(rawArgs); - const first = args[0]; - if (first && typeof first === 'object') { - const o = first as { host?: string; path?: string }; - if (o.path) return { kind: 'local', host: o.path }; - const host = o.host ?? 'localhost'; - return { kind: isIP(host) ? 'literal-ip' : 'hostname', host }; - } - if (typeof first === 'string' && !exec(/^\d+$/, first)) { - // a bare string that isn't a port number is an IPC path - return { kind: 'local', host: first }; - } - // connect(port[, host][, cb]) - const host = typeof args[1] === 'string' ? (args[1] as string) : 'localhost'; - return { kind: isIP(host) ? 'literal-ip' : 'hostname', host }; -} // --------------------------------------------------------------------------- // The dev-server guard. @@ -305,6 +72,7 @@ export function installEgressGuard(hosts: string[]): RestoreEgress { `egress: ${host} is not in the plugin's declared hosts — ` + `add "http:outbound:${host}" to permissions (and "${host}" to egress) in trek-plugin.json`, ); + const networkPolicy = { allowed, refuse, isIp: (host: string) => isIP(host) !== 0, blockPrivate }; const restores: RestoreEgress[] = []; @@ -324,78 +92,20 @@ export function installEgressGuard(hosts: string[]): RestoreEgress { restores.push(() => { globalThis.fetch = realFetch; }); } - // Capture the real resolver before the dns module is gated below, so the connect - // guard keeps resolving even though direct dns.* calls are refused. - const realLookup = dns.lookup.bind(dns); - - // Resolve, then refuse a name that lands on a blocked address — the DNS-rebinding - // backstop, so a declared host can't point at localhost. - const guardedLookup = ( - hostname: string, - options: unknown, - cb: (err: Error | null, address?: unknown, family?: number) => void, - ): void => { - const opts = typeof options === 'function' ? {} : options; - if (typeof options === 'function') cb = options as typeof cb; - realLookup(hostname, opts as dns.LookupOptions, (err, address, family) => { - if (err) return cb(err, address as unknown, family); - const list = arrayIsArray(address) ? address : [{ address: address as string }]; - for (let i = 0; i < list.length; i++) { - const ip = list[i].address; - if (blockPrivate && isBlockedIp(ip)) { - return cb(new Error(`egress: ${hostname} resolves to a blocked address (${ip})`)); - } - } - cb(null, address as unknown, family); - }); - }; - + const guardedLookup = guardDnsLookup(dns.lookup.bind(dns), blockPrivate); const proto = net.Socket.prototype as unknown as { connect: (...a: unknown[]) => unknown }; const realConnect = proto.connect; - proto.connect = function (this: unknown, ...rawArgs: unknown[]): unknown { - const args = snapshotConnectArgs(rawArgs); - const options = args[0]; - const target = classifyConnect(args, (s) => isIP(s) !== 0); - if (target.kind === 'local') { - if (blockPrivate) throw new Error(`egress: connecting to a local socket/pipe (${target.host}) is not allowed`); - delete options.host; - delete options.port; - return apply(realConnect, this, args); - } - if (!allowed(target.host)) throw refuse(target.host); - if (target.kind === 'literal-ip' && blockPrivate && isBlockedIp(target.host)) { - throw new Error(`egress: ${target.host} is a blocked address`); - } - delete options.path; - options.host = target.host; - if (target.kind === 'hostname') options.lookup = guardedLookup; - return apply(realConnect, this, args); - }; + proto.connect = guardSocketConnect(realConnect, { ...networkPolicy, lookup: guardedLookup }); restores.push(() => { proto.connect = realConnect; }); - // UDP: a TCP-only guard would leave a plugin's syslog/statsd channel wide open in - // dev and blocked in prod — the exact asymmetry this exists to kill. - const guardDatagram = (host: string | null): void => { - if (host === null) return; - if (!allowed(host)) throw refuse(host); - if (blockPrivate && isIP(host) !== 0 && isBlockedIp(host)) { - throw new Error(`egress: ${host} is a blocked address`); - } - }; const dgramProto = dgram.Socket.prototype as unknown as { send: (...a: unknown[]) => unknown; connect: (...a: unknown[]) => unknown; }; const realSend = dgramProto.send; - dgramProto.send = function (this: unknown, ...args: unknown[]): unknown { - guardDatagram(dgramSendTarget(args)); - return apply(realSend, this, args); - }; + dgramProto.send = guardDatagramCall(realSend, dgramSendTarget, networkPolicy); const realDgramConnect = dgramProto.connect; - dgramProto.connect = function (this: unknown, ...args: unknown[]): unknown { - guardDatagram(dgramConnectTarget(args)); - return apply(realDgramConnect, this, args); - }; + dgramProto.connect = guardDatagramCall(realDgramConnect, dgramConnectTarget, networkPolicy); restores.push(() => { dgramProto.send = realSend; dgramProto.connect = realDgramConnect; }); // Gate the resolver family: a forward lookup for an undeclared NAME is a DNS-tunnel diff --git a/plugin-sdk/test/permissions-parity.test.ts b/plugin-sdk/test/permissions-parity.test.ts index 68ba2759a..55e0811a1 100644 --- a/plugin-sdk/test/permissions-parity.test.ts +++ b/plugin-sdk/test/permissions-parity.test.ts @@ -46,14 +46,9 @@ describe.skipIf(!inMonorepo)('parity with the host', () => { }); it('the vendored egress-policy helpers are byte-identical to the server\'s', () => { - const ours = fs.readFileSync(path.resolve(here, '../src/egress-policy.ts'), 'utf8').replace(/\r\n/g, '\n'); + const ours = fs.readFileSync(path.resolve(here, '../src/generated/egress-policy.ts'), 'utf8').replace(/\r\n/g, '\n'); const theirs = fs.readFileSync(serverEgress, 'utf8').replace(/\r\n/g, '\n'); - const marker = 'const apply = Reflect.apply;'; - const end = '// ---------------------------------------------------------------------------\n// The dev-server guard.'; - expect(ours.indexOf(marker)).toBeGreaterThan(-1); - expect(ours.indexOf(end)).toBeGreaterThan(ours.indexOf(marker)); - expect(theirs.indexOf(marker)).toBeGreaterThan(-1); - expect(ours.slice(ours.indexOf(marker), ours.indexOf(end)).trim()).toBe(theirs.slice(theirs.indexOf(marker)).trim()); + expect(ours).toBe(theirs); }); }); diff --git a/plugin-sdk/vitest.config.ts b/plugin-sdk/vitest.config.ts index a587c969f..a4a805aac 100644 --- a/plugin-sdk/vitest.config.ts +++ b/plugin-sdk/vitest.config.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; import { defineConfig } from 'vitest/config'; +import './scripts/sync-egress-policy.mjs'; // The host's copy of the plugin API, which test/host-types.test-d.ts compares the SDK's // types against. It exists only inside the TREK monorepo; a standalone checkout of the diff --git a/server/src/nest/plugins/runtime/egress-policy.ts b/server/src/nest/plugins/runtime/egress-policy.ts index 682c10b7b..692581dab 100644 --- a/server/src/nest/plugins/runtime/egress-policy.ts +++ b/server/src/nest/plugins/runtime/egress-policy.ts @@ -5,6 +5,7 @@ * their own (the guard that uses them lives in plugin-host-entry, which is * excluded from coverage as a subprocess entry). */ +import type { LookupAddress, LookupOptions } from 'node:dns'; const apply = Reflect.apply; const stringSlice = String.prototype.slice; @@ -13,7 +14,7 @@ const stringLower = String.prototype.toLowerCase; const stringEndsWith = String.prototype.endsWith; const regexExec = RegExp.prototype.exec; const numberToString = Number.prototype.toString; -const parseInt = Number.parseInt; +const parseNumber = Number.parseInt; const arrayIsArray = Array.isArray; const ownKeys = Reflect.ownKeys; const ownDescriptor = Object.getOwnPropertyDescriptor; @@ -119,7 +120,7 @@ function readGroups(source: string, groups: number[], start: number): number { const next = indexOf(source, ':', from); const group = slice(source, from, next === -1 ? undefined : next); if (!exec(/^[0-9a-f]{1,4}$/, group)) return -1; - groups[start++] = parseInt(group, 16); + groups[start++] = parseNumber(group, 16); if (next === -1) return start; from = next + 1; } @@ -220,6 +221,90 @@ export function snapshotConnectArgs(rawArgs: unknown[]): [options: Record unknown; + +interface NetworkPolicy { + allowed: (host: string) => boolean; + refuse: (host: string) => Error; + isIp: (host: string) => boolean; + blockPrivate: boolean; +} + +interface SocketPolicy extends NetworkPolicy { + lookup: unknown; +} + +/** Use the validated copy for the actual socket operation. */ +export function guardSocketConnect(connect: SocketConnect, policy: SocketPolicy): SocketConnect { + return function (this: unknown, ...rawArgs: unknown[]): unknown { + const args = snapshotConnectArgs(rawArgs); + const options = args[0]; + const target = classifyConnect(args, policy.isIp); + if (target.kind === 'local') { + if (policy.blockPrivate) + throw new Error(`egress: connecting to a local socket/pipe (${target.host}) is not allowed`); + delete options.host; + delete options.port; + return apply(connect, this, args); + } + if (!policy.allowed(target.host)) throw policy.refuse(target.host); + if (target.kind === 'literal-ip' && policy.blockPrivate && isBlockedIp(target.host)) { + throw new Error(`egress: ${target.host} is a blocked address`); + } + delete options.path; + options.host = target.host; + if (target.kind === 'hostname') options.lookup = policy.lookup; + return apply(connect, this, args); + }; +} + +export function firstBlockedAddress(address: string | ReadonlyArray<{ address: string }>): string | undefined { + if (typeof address === 'string') return isBlockedIp(address) ? address : undefined; + for (let i = 0; i < address.length; i++) { + const ip = address[i].address; + if (isBlockedIp(ip)) return ip; + } + return undefined; +} + +type Lookup = ( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, +) => void; +type LookupCallback = (err: Error | null, address?: unknown, family?: number) => void; + +export function guardDnsLookup(lookup: Lookup, blockPrivate: boolean) { + return (hostname: string, options: unknown, callback?: LookupCallback): void => { + const cb = typeof options === 'function' ? (options as LookupCallback) : callback; + if (!cb) throw new Error('egress: DNS lookup requires a callback'); + const opts = typeof options === 'function' ? {} : (options as LookupOptions); + lookup(hostname, opts, (err, address, family) => { + if (err) return cb(err, address, family); + const blocked = blockPrivate ? firstBlockedAddress(address) : undefined; + if (blocked) return cb(new Error(`egress: ${hostname} resolves to a blocked address (${blocked})`)); + cb(null, address, family); + }); + }; +} + +export function guardDatagramCall( + socketCall: SocketConnect, + targetOf: (args: unknown[]) => string | null, + policy: NetworkPolicy, +): SocketConnect { + return function (this: unknown, ...args: unknown[]): unknown { + const host = targetOf(args); + if (host !== null) { + if (!policy.allowed(host)) throw policy.refuse(host); + if (policy.blockPrivate && policy.isIp(host) && isBlockedIp(host)) { + throw new Error(`egress: ${host} is a blocked address`); + } + } + return apply(socketCall, this, args); + }; +} + /** * Classify a `net.Socket.connect(...)` argument list into what we must check: * a unix-socket/pipe (local, allowed), a literal IP (checked synchronously), or diff --git a/server/src/nest/plugins/runtime/plugin-host-entry.ts b/server/src/nest/plugins/runtime/plugin-host-entry.ts index 393899fef..74f1a8d3c 100644 --- a/server/src/nest/plugins/runtime/plugin-host-entry.ts +++ b/server/src/nest/plugins/runtime/plugin-host-entry.ts @@ -11,10 +11,10 @@ */ import type { Envelope, RpcError } from '../protocol/envelope'; import { - isBlockedIp, makeHostAllow, - classifyConnect, - snapshotConnectArgs, + guardSocketConnect, + guardDnsLookup, + guardDatagramCall, dgramSendTarget, dgramConnectTarget, } from './egress-policy'; @@ -444,8 +444,13 @@ function installEgressGuard(egress: string[]): void { const allowed = makeHostAllow(egress); const blockPrivate = (process.env.TREK_PLUGIN_ALLOW_PRIVATE_EGRESS ?? '').toLowerCase() !== 'on'; const apply = Reflect.apply; - const isArray = Array.isArray; const isIP = net.isIP; + const networkPolicy = { + allowed, + refuse: (host: string) => new Error(`egress: ${host} is not in the plugin's declared hosts`), + isIp: (host: string) => isIP(host) !== 0, + blockPrivate, + }; // The wrappers below are the ONLY egress choke point (the OS --permission model // does not restrict the network). Deny the low-level escape hatch a plugin could @@ -481,85 +486,15 @@ function installEgressGuard(egress: string[]): void { }) as typeof fetch; } - // Capture the real resolvers before we patch the dns module below, so the - // connect guard keeps resolving even though direct dns.* calls get gated. - const realLookup = dns.lookup.bind(dns); - - // A DNS lookup that refuses to resolve a name to a blocked address; injected - // into every hostname connect so the socket only ever reaches a vetted IP. - const guardedLookup = ( - hostname: string, - options: unknown, - cb: (err: Error | null, address?: unknown, family?: number) => void, - ): void => { - const opts = typeof options === 'function' ? {} : options; - if (typeof options === 'function') cb = options as typeof cb; - realLookup(hostname, opts as dns.LookupOptions, (err, address, family) => { - if (err) return cb(err, address as unknown, family); - const list = isArray(address) ? address : [{ address: address as string }]; - for (let i = 0; i < list.length; i++) { - const ip = list[i].address; - if (blockPrivate && isBlockedIp(ip)) { - return cb(new Error(`egress: ${hostname} resolves to a blocked address (${ip})`)); - } - } - cb(null, address as unknown, family); - }); - }; - + const guardedLookup = guardDnsLookup(dns.lookup.bind(dns), blockPrivate); const proto = net.Socket.prototype as unknown as { connect: (...a: unknown[]) => unknown }; - const realConnect = proto.connect; - proto.connect = function (this: unknown, ...rawArgs: unknown[]): unknown { - const args = snapshotConnectArgs(rawArgs); - const options = args[0]; - const target = classifyConnect(args, (s) => isIP(s) !== 0); - if (target.kind === 'local') { - // A unix-socket / named-pipe connect is a host-local pivot — a malicious plugin - // could reach docker.sock or a local DB socket, exactly what the private-IP block - // exists to stop, and Node's --permission model doesn't gate socket connects. - // Refuse it under the SAME policy: blocked by default, allowed only when the - // operator explicitly opted into private egress. - if (blockPrivate) throw new Error(`egress: connecting to a local socket/pipe (${target.host}) is not allowed`); - delete options.host; - delete options.port; - return apply(realConnect, this, args); - } - if (!allowed(target.host)) { - throw new Error(`egress: ${target.host} is not in the plugin's declared hosts`); - } - if (target.kind === 'literal-ip' && blockPrivate && isBlockedIp(target.host)) { - throw new Error(`egress: ${target.host} is a blocked address`); - } - delete options.path; - options.host = target.host; - if (target.kind === 'hostname') options.lookup = guardedLookup; - return apply(realConnect, this, args); - }; - - // Refuse an outbound UDP target the plugin never declared, or a private one. - // A null target means "no explicit address" (connected remote / localhost - // default) — the connect wrapper below already vetted connected sockets. - const guardDatagram = (host: string | null): void => { - if (host === null) return; - if (!allowed(host)) throw new Error(`egress: ${host} is not in the plugin's declared hosts`); - if (blockPrivate && isIP(host) !== 0 && isBlockedIp(host)) { - throw new Error(`egress: ${host} is a blocked address`); - } - }; + proto.connect = guardSocketConnect(proto.connect, { ...networkPolicy, lookup: guardedLookup }); const dgramProto = dgram.Socket.prototype as unknown as { send: (...a: unknown[]) => unknown; connect: (...a: unknown[]) => unknown; }; - const realSend = dgramProto.send; - dgramProto.send = function (this: unknown, ...args: unknown[]): unknown { - guardDatagram(dgramSendTarget(args)); - return apply(realSend, this, args); - }; - const realDgramConnect = dgramProto.connect; - dgramProto.connect = function (this: unknown, ...args: unknown[]): unknown { - guardDatagram(dgramConnectTarget(args)); - return apply(realDgramConnect, this, args); - }; + dgramProto.send = guardDatagramCall(dgramProto.send, dgramSendTarget, networkPolicy); + dgramProto.connect = guardDatagramCall(dgramProto.connect, dgramConnectTarget, networkPolicy); // A dgram HOSTNAME target is resolved via the socket's `lookup` before the packet // is sent; force the IP-vetting guardedLookup so a declared name that resolves to // a private/metadata address is refused (the TCP path's rebind backstop, for UDP). diff --git a/server/tests/unit/plugins/egress-policy.test.ts b/server/tests/unit/plugins/egress-policy.test.ts index a5c63557e..b7c885245 100644 --- a/server/tests/unit/plugins/egress-policy.test.ts +++ b/server/tests/unit/plugins/egress-policy.test.ts @@ -8,13 +8,17 @@ import { makeHostAllow, classifyConnect, snapshotConnectArgs, + guardSocketConnect, + guardDnsLookup, + guardDatagramCall, + firstBlockedAddress, unwrapConnectArgs, dgramSendTarget, dgramConnectTarget, } from '../../../src/nest/plugins/runtime/egress-policy'; import net from 'node:net'; -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; const isIP = (s: string) => net.isIP(s) !== 0; @@ -182,6 +186,106 @@ describe('snapshotConnectArgs', () => { }); }); +describe('guardSocketConnect', () => { + const allowed = makeHostAllow(['api.example.com', '127.0.0.1']); + const refuse = (host: string) => new Error(`Not declared: ${host}`); + const lookup = () => {}; + const policy = { allowed, refuse, isIp: isIP, blockPrivate: true, lookup }; + + it('passes a detached, checked option record to the socket', () => { + const socket = vi.fn(); + const connect = guardSocketConnect(socket, policy); + const options = { host: 'api.example.com', port: 443 }; + connect(options); + + expect(socket).toHaveBeenCalledWith({ host: 'api.example.com', port: 443, lookup }, undefined); + expect(socket.mock.calls[0][0]).not.toBe(options); + }); + + it('does not call the socket for a disallowed hostname, address or path', () => { + const socket = vi.fn(); + const connect = guardSocketConnect(socket, policy); + expect(() => connect(443, 'other.example.com')).toThrow('Not declared'); + expect(() => connect(443, '127.0.0.1')).toThrow('blocked address'); + expect(() => connect('/run/app.sock')).toThrow('local socket'); + expect(socket).not.toHaveBeenCalled(); + }); + + it('keeps an opted-in local connection local', () => { + const socket = vi.fn(); + const connect = guardSocketConnect(socket, { ...policy, blockPrivate: false }); + connect({ path: '/run/app.sock', host: 'api.example.com', port: 443 }); + expect(socket).toHaveBeenCalledWith({ path: '/run/app.sock' }, undefined); + }); +}); + +describe('firstBlockedAddress', () => { + it('checks both supported resolver results', () => { + expect(firstBlockedAddress('127.0.0.1')).toBe('127.0.0.1'); + expect(firstBlockedAddress('203.0.113.1')).toBeUndefined(); + expect(firstBlockedAddress([{ address: '203.0.113.1' }, { address: '127.0.0.1' }])).toBe('127.0.0.1'); + expect(firstBlockedAddress([{ address: '203.0.113.1' }])).toBeUndefined(); + }); +}); + +describe('guardDnsLookup', () => { + it('forwards a vetted answer to the callback-only overload', () => { + const lookup = guardDnsLookup((hostname, options, done) => { + expect(hostname).toBe('api.example.com'); + expect(options).toEqual({}); + done(null, '203.0.113.1', 4); + }, true); + const done = vi.fn(); + lookup('api.example.com', done); + expect(done).toHaveBeenCalledWith(null, '203.0.113.1', 4); + }); + + it('rejects a blocked result in an address list', () => { + const addresses = [{ address: '127.0.0.1', family: 4 }]; + const lookup = guardDnsLookup((_host, _options, done) => done(null, addresses, 4), true); + const done = vi.fn(); + lookup('api.example.com', { all: true }, done); + expect(done).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining('blocked address') })); + }); + + it('forwards resolver errors', () => { + const error = new Error('Resolver unavailable'); + const lookup = guardDnsLookup((_host, _options, done) => done(error, '', 0), true); + const done = vi.fn(); + lookup('api.example.com', {}, done); + expect(done).toHaveBeenCalledWith(error, '', 0); + }); +}); + +describe('guardDatagramCall', () => { + it('passes permitted and implicit targets to the socket', () => { + const socket = vi.fn(); + const send = guardDatagramCall(socket, dgramSendTarget, { + allowed: makeHostAllow(['api.example.com']), + refuse: (host) => new Error(`Not declared: ${host}`), + isIp: isIP, + blockPrivate: true, + }); + const data = Buffer.from('data'); + send(data, 443, 'api.example.com'); + send(data); + expect(socket.mock.calls).toEqual([[data, 443, 'api.example.com'], [data]]); + }); + + it('rejects undeclared and blocked datagram targets before calling the socket', () => { + const socket = vi.fn(); + const connect = guardDatagramCall(socket, dgramConnectTarget, { + allowed: makeHostAllow(['127.0.0.1']), + refuse: (host) => new Error(`Not declared: ${host}`), + isIp: isIP, + blockPrivate: true, + }); + expect(() => connect(443, 'other.example.com')).toThrow('Not declared'); + expect(() => connect(443, '127.0.0.1')).toThrow('blocked address'); + expect(socket).not.toHaveBeenCalled(); + }); +}); + describe('dgramSendTarget', () => { const msg = Buffer.from('x'); it('reads the address from send(msg, port, address)', () => {