refactor(plugins): generate SDK egress policy from the server

This commit is contained in:
Maurice
2026-12-01 12:24:32 +01:00
parent c22c464e68
commit 871135edeb
10 changed files with 236 additions and 394 deletions
@@ -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<Proper
return [options, callback];
}
type SocketConnect = (this: unknown, ...args: unknown[]) => 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
@@ -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).
+105 -1
View File
@@ -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)', () => {