diff --git a/plugin-sdk/package-lock.json b/plugin-sdk/package-lock.json index 5baa78c9c..7b6c71157 100644 --- a/plugin-sdk/package-lock.json +++ b/plugin-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "trek-plugin-sdk", - "version": "1.10.0", + "version": "1.10.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "trek-plugin-sdk", - "version": "1.10.0", + "version": "1.10.1", "license": "MIT", "dependencies": { "@clack/prompts": "^1.8.1", diff --git a/plugin-sdk/package.json b/plugin-sdk/package.json index e1e51b634..a803db8a7 100644 --- a/plugin-sdk/package.json +++ b/plugin-sdk/package.json @@ -1,6 +1,6 @@ { "name": "trek-plugin-sdk", - "version": "1.10.0", + "version": "1.10.1", "description": "SDK for building TREK plugins: types, definePlugin, a mock host, manifest validation, and the create-trek-plugin / trek-plugin CLIs.", "type": "module", "license": "MIT", diff --git a/plugin-sdk/src/egress-policy.ts b/plugin-sdk/src/egress-policy.ts index 6c8130d09..0e9d18a86 100644 --- a/plugin-sdk/src/egress-policy.ts +++ b/plugin-sdk/src/egress-policy.ts @@ -10,7 +10,7 @@ * * 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/egress-parity.test.ts + * standalone and cannot import across the package boundary. test/permissions-parity.test.ts * fails if the two drift. * * What is deliberately NOT mirrored: the host also locks its wrappers @@ -28,6 +28,25 @@ import dgram from 'node:dgram'; // Pure policy helpers — kept byte-identical to the server's egress-policy.ts. // --------------------------------------------------------------------------- +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 @@ -36,10 +55,10 @@ import dgram from 'node:dgram'; * metadata IP, the local docker network, or other internal services. */ export function isBlockedIp(ip: string): boolean { - const v4 = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/); + const v4 = exec(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/, ip); if (v4) { - const a = Number(v4[1]); - const b = Number(v4[2]); + const a = +v4[1]; + const b = +v4[2]; return ( a === 0 || a === 10 || @@ -53,11 +72,10 @@ export function isBlockedIp(ip: string): boolean { } // 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(ip.replace(/^\[/, '').replace(/\]$/, '')); + const g = expandV6(slice(ip, ip[0] === '[' ? 1 : 0, ip[ip.length - 1] === ']' ? -1 : undefined)); if (g) { - if (g.every((x) => x === 0)) return true; // :: (unspecified) // IPv4-mapped (::ffff:x) and IPv4-compatible (::x) → check the embedded IPv4. - if (g.slice(0, 5).every((x) => x === 0) && (g[5] === 0xffff || g[5] === 0)) { + 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 @@ -91,26 +109,43 @@ function embeddedTransitionIpv4(g: number[]): string | null { /** Expand an IPv6 literal into its 8 numeric hextets, or null if not a valid IPv6. */ function expandV6(ip: string): number[] | null { - // Cut the zone id off (`fe80::1%eth0`): indexOf rather than a `%.*$` regex, whose - // greedy tail rescans the whole string once per `%` on a host that never matches. - const zone = ip.indexOf('%'); - let h = (zone === -1 ? ip : ip.slice(0, zone)).toLowerCase(); - if (!h.includes(':')) return null; - const dotted = h.match(/^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/); + 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 v4 = dotted[2].split('.').map(Number); - if (v4.some((n) => n > 255)) return null; - h = dotted[1] + ((v4[0] << 8) | v4[1]).toString(16) + ':' + ((v4[2] << 8) | v4[3]).toString(16); + 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 halves = h.split('::'); - if (halves.length > 2) return null; - const head = halves[0] ? halves[0].split(':') : []; - const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : []; - const groups = - halves.length === 2 ? [...head, ...new Array(8 - head.length - tail.length).fill('0'), ...tail] : head; - if (groups.length !== 8) return null; - const nums = groups.map((x) => (x === '' ? Number.NaN : Number.parseInt(x, 16))); - return nums.some((n) => !Number.isInteger(n) || n < 0 || n > 0xffff) ? null : nums; + 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). */ @@ -122,8 +157,14 @@ export function makeHostAllow(egress: string[]): (host: string) => boolean { // `*.` (matched any trailing-dot host = allow-all) and whole-TLD `*.com`. .filter((p) => !p.startsWith('*.') || p.slice(2).includes('.')); return (host: string) => { - const h = host.toLowerCase().replace(/\.$/, ''); - return patterns.some((p) => (p.startsWith('*.') ? h === p.slice(2) || h.endsWith(p.slice(1)) : h === p)); + 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; }; } @@ -134,7 +175,11 @@ export interface ConnectTarget { /** * Destination host of a `dgram.Socket.send(msg[, offset, length], port[, address][, cb])` - * call, or null when no explicit address is given. + * 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'; @@ -142,7 +187,10 @@ export function dgramSendTarget(args: unknown[]): string | null { return typeof address === 'string' ? address : null; } -/** Destination host of a `dgram.Socket.connect(port[, address][, cb])` call, or 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; } @@ -152,15 +200,54 @@ export function dgramConnectTarget(args: unknown[]): string | null { * 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[] { - return Array.isArray(args[0]) ? (args[0] as unknown[]) : args; + 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), a literal IP (checked synchronously), or a hostname - * (allowlist + a DNS-resolving guard). + * 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); @@ -171,7 +258,7 @@ export function classifyConnect(rawArgs: unknown[], isIP: (s: string) => boolean const host = o.host ?? 'localhost'; return { kind: isIP(host) ? 'literal-ip' : 'hostname', host }; } - if (typeof first === 'string' && !/^\d+$/.test(first)) { + 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 }; } @@ -209,6 +296,7 @@ const DNS_METHODS = [ export function installEgressGuard(hosts: string[]): RestoreEgress { const allowed = makeHostAllow(hosts); const blockPrivate = (process.env.TREK_PLUGIN_ALLOW_PRIVATE_EGRESS ?? '').toLowerCase() !== 'on'; + const isIP = net.isIP; // Name the fix in the error. Production can only say "not declared"; dev knows the // author is looking at the manifest right now, so it says what to add. @@ -251,10 +339,11 @@ export function installEgressGuard(hosts: string[]): RestoreEgress { 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 = Array.isArray(address) ? address : [{ address: address as string }]; - for (const a of list) { - if (blockPrivate && isBlockedIp((a as { address: string }).address)) { - return cb(new Error(`egress: ${hostname} resolves to a blocked address (${(a as { address: string }).address})`)); + 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); @@ -264,23 +353,23 @@ export function installEgressGuard(hosts: string[]): RestoreEgress { 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 = unwrapConnectArgs(rawArgs); - const target = classifyConnect(args, (s) => net.isIP(s) !== 0); + 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`); - return realConnect.apply(this, rawArgs); + delete options.host; + delete options.port; + return apply(realConnect, this, args); } if (!allowed(target.host)) throw refuse(target.host); - if (target.kind === 'literal-ip') { - if (blockPrivate && isBlockedIp(target.host)) throw new Error(`egress: ${target.host} is a blocked address`); - return realConnect.apply(this, rawArgs); + if (target.kind === 'literal-ip' && blockPrivate && isBlockedIp(target.host)) { + throw new Error(`egress: ${target.host} is a blocked address`); } - // Hostname: inject the resolving guard, preserving any existing options. - const first = args[0]; - const options = first && typeof first === 'object' ? { ...(first as object) } : { host: target.host, port: args[0] }; - (options as { lookup?: unknown }).lookup = guardedLookup; - const rest = first && typeof first === 'object' ? args.slice(1) : args.slice(typeof args[1] === 'string' ? 2 : 1); - return realConnect.call(this, options, ...rest); + delete options.path; + options.host = target.host; + if (target.kind === 'hostname') options.lookup = guardedLookup; + return apply(realConnect, this, args); }; restores.push(() => { proto.connect = realConnect; }); @@ -289,7 +378,7 @@ export function installEgressGuard(hosts: string[]): RestoreEgress { const guardDatagram = (host: string | null): void => { if (host === null) return; if (!allowed(host)) throw refuse(host); - if (blockPrivate && net.isIP(host) !== 0 && isBlockedIp(host)) { + if (blockPrivate && isIP(host) !== 0 && isBlockedIp(host)) { throw new Error(`egress: ${host} is a blocked address`); } }; @@ -300,12 +389,12 @@ export function installEgressGuard(hosts: string[]): RestoreEgress { const realSend = dgramProto.send; dgramProto.send = function (this: unknown, ...args: unknown[]): unknown { guardDatagram(dgramSendTarget(args)); - return realSend.apply(this, args); + return apply(realSend, this, args); }; const realDgramConnect = dgramProto.connect; dgramProto.connect = function (this: unknown, ...args: unknown[]): unknown { guardDatagram(dgramConnectTarget(args)); - return realDgramConnect.apply(this, args); + return apply(realDgramConnect, this, args); }; restores.push(() => { dgramProto.send = realSend; dgramProto.connect = realDgramConnect; }); @@ -323,13 +412,13 @@ export function installEgressGuard(hosts: string[]): RestoreEgress { const real = obj[name]; if (typeof real !== 'function') continue; obj[name] = function (this: unknown, hostname: unknown, ...rest: unknown[]): unknown { - if (typeof hostname === 'string' && net.isIP(hostname) === 0 && !allowed(hostname)) { + if (typeof hostname === 'string' && isIP(hostname) === 0 && !allowed(hostname)) { const err = new Error(`egress: DNS lookup for ${hostname} is not in the plugin's declared hosts`); const cb = rest.find((a) => typeof a === 'function') as ((e: Error) => void) | undefined; if (cb) return cb(err); return Promise.reject(err); } - return (real as (...a: unknown[]) => unknown).call(this, hostname, ...rest); + return apply(real, this, [hostname, ...rest]); }; restores.push(() => { obj[name] = real; }); } diff --git a/plugin-sdk/test/egress-policy.test.ts b/plugin-sdk/test/egress-policy.test.ts index 1b8c33fa7..cc50e6b14 100644 --- a/plugin-sdk/test/egress-policy.test.ts +++ b/plugin-sdk/test/egress-policy.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, afterEach } from 'vitest'; import { - makeHostAllow, isBlockedIp, classifyConnect, unwrapConnectArgs, dgramSendTarget, dgramConnectTarget, + makeHostAllow, isBlockedIp, classifyConnect, snapshotConnectArgs, unwrapConnectArgs, dgramSendTarget, dgramConnectTarget, installEgressGuard, type RestoreEgress, } from '../src/egress-policy.js'; @@ -79,6 +79,16 @@ describe('connect / dgram argument parsing', () => { expect(classifyConnect([[{ host: 'a.com', port: 80 }, () => {}]], isIP)).toEqual({ kind: 'hostname', host: 'a.com' }); }); + it('snapshots normalized and positional socket arguments', () => { + const options = { host: 'a.com', port: 443 }; + const callback = () => {}; + const [copy, actualCallback] = snapshotConnectArgs([[options, callback]]); + expect(copy).toEqual(options); + expect(copy).not.toBe(options); + expect(actualCallback).toBe(callback); + expect(snapshotConnectArgs([443, 'a.com', callback])).toEqual([options, callback]); + }); + it('finds the dgram destination in both send() overloads', () => { expect(dgramSendTarget(['msg', 514, 'logs.example.com'])).toBe('logs.example.com'); expect(dgramSendTarget(['msg', 0, 3, 514, 'logs.example.com'])).toBe('logs.example.com'); // (offset,length) form diff --git a/plugin-sdk/test/permissions-parity.test.ts b/plugin-sdk/test/permissions-parity.test.ts index 71c3ffc29..68ba2759a 100644 --- a/plugin-sdk/test/permissions-parity.test.ts +++ b/plugin-sdk/test/permissions-parity.test.ts @@ -46,20 +46,14 @@ 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'); - const theirs = fs.readFileSync(serverEgress, 'utf8'); - - // Compare the pure helpers only — our file additionally carries installEgressGuard - // (the server's lives in plugin-host-entry.ts, where it is coupled to the child). - const fns = ['isBlockedIp', 'expandV6', 'makeHostAllow', 'dgramSendTarget', 'dgramConnectTarget', 'unwrapConnectArgs', 'classifyConnect']; - const body = (src: string, name: string): string => { - const start = src.indexOf(`function ${name}(`); - expect(start, `${name} not found`).toBeGreaterThan(-1); - // From the signature to the closing brace at column 0 — these are all top-level fns. - const end = src.indexOf('\n}', start); - return src.slice(start, end).replace(/\s+/g, ' ').trim(); - }; - for (const fn of fns) expect(body(ours, fn), `${fn} has drifted from the server`).toBe(body(theirs, fn)); + const ours = fs.readFileSync(path.resolve(here, '../src/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()); }); }); diff --git a/server/src/nest/oidc/oidc.service.ts b/server/src/nest/oidc/oidc.service.ts index ad8368885..ea2fd3143 100644 --- a/server/src/nest/oidc/oidc.service.ts +++ b/server/src/nest/oidc/oidc.service.ts @@ -787,6 +787,7 @@ export class OidcService implements OnModuleDestroy { return { user: toClientUser(user), roleChange }; } + /** @txIndependent An existing-account refresh returns before registration. A lookup with no account writes nothing. */ async findOrCreateUser( userInfo: OidcUserInfo, config: OidcConfig, diff --git a/server/tests/unit/docker-entrypoint.test.ts b/server/tests/unit/docker-entrypoint.test.ts index 269748139..38cee0254 100644 --- a/server/tests/unit/docker-entrypoint.test.ts +++ b/server/tests/unit/docker-entrypoint.test.ts @@ -94,7 +94,7 @@ describe('entrypoint script', () => { const branchEnd = code.indexOf('\nfi\n', nonRootCheck); expect(branchEnd).toBeGreaterThan(nonRootCheck); const branch = code.slice(nonRootCheck, branchEnd); - expect(branch).toContain('exec node --require tsconfig-paths/register dist/index.js'); + expect(branch).toContain('exec node --disable-sigusr1 --require tsconfig-paths/register dist/index.js'); expect(branch).not.toContain('setpriv'); expect(code.indexOf('chown')).toBeGreaterThan(branchEnd); expect(code.indexOf('setpriv')).toBeGreaterThan(branchEnd); @@ -104,7 +104,7 @@ describe('entrypoint script', () => { // each answers, so a host that drops that signal hung it at full CPU (#3135). it('drops to node through setpriv, not gosu, when started as root', () => { expect(source).toContain( - 'exec setpriv --reuid=node --regid=node --init-groups -- node --require tsconfig-paths/register dist/index.js', + 'exec setpriv --reuid=node --regid=node --init-groups -- node --disable-sigusr1 --require tsconfig-paths/register dist/index.js', ); expect(source).toContain('export HOME=/home/node'); expect(source).not.toMatch(/^\s*exec gosu/m);