diff --git a/test/e2e/live/messaging-providers-helpers.ts b/test/e2e/live/messaging-providers-helpers.ts index 78489f03336..28d19278ab4 100644 --- a/test/e2e/live/messaging-providers-helpers.ts +++ b/test/e2e/live/messaging-providers-helpers.ts @@ -41,6 +41,33 @@ export const LIVE_TIMEOUT_MS = 90 * 60_000; export const OPENSHELL_EXEC_ARGUMENT_LIMIT_BYTES = 32_768; const FAKE_API_IMAGE = "node:22-trixie-slim@sha256:db8a96a63e5264607ada2d206758876ebbed6a12be2ada7517793cbfb0c2a29c"; +const FAKE_API_PROXY_SOURCE = String.raw` +const net = require("node:net"); +const upstream = process.env.NEMOCLAW_FAKE_API_UPSTREAM; +const ports = (process.env.NEMOCLAW_FAKE_API_PROXY_PORTS || "") + .split(",") + .filter(Boolean) + .map(Number); + +if (!upstream || ports.length === 0 || ports.some((port) => !Number.isInteger(port))) { + process.exit(2); +} + +for (const port of ports) { + const server = net.createServer((client) => { + const backend = net.connect(port, upstream); + const close = () => { + client.destroy(); + backend.destroy(); + }; + client.on("error", close); + backend.on("error", close); + client.pipe(backend).pipe(client); + }); + server.on("error", () => process.exit(3)); + server.listen(port, "0.0.0.0"); +} +`; // Leave ample headroom beneath OpenShell's strict per-argument ceiling. const SANDBOX_SOURCE_CHUNK_BYTES = 16_384; @@ -112,8 +139,15 @@ export function assertDiscordGatewayCapture(captureFile: string, expectedToken: expect(identify?.tokenLooksPlaceholder, "Discord placeholder leaked").toBe(false); } +export type FakeDockerApiKind = + | "slack" + | "telegram" + | "wechat" + | "discord-gateway" + | "discord-message"; + export type FakeDockerApi = { - kind: string; + kind: FakeDockerApiKind; port: string; alternatePort?: string; dir: string; @@ -600,7 +634,7 @@ export async function startFakeDockerApi( host: HostCliClient, cleanup: (name: string, run: () => Promise) => void, options: { - kind: "slack" | "telegram" | "wechat" | "discord-gateway" | "discord-message"; + kind: FakeDockerApiKind; imageScript: string; nodeArgs?: readonly string[]; containerPrefix: string; @@ -617,7 +651,9 @@ export async function startFakeDockerApi( const portFile = path.join(dir, "port"); const captureFile = path.join(dir, "capture.jsonl"); const container = uniqueContainerName(options.containerPrefix); + const proxyContainer = uniqueContainerName(`${options.containerPrefix}-proxy`); const network = uniqueContainerName("nemoclaw-fake-api-network"); + const containerPorts = options.kind === "slack" ? [8080, 8081] : [8080]; fs.writeFileSync(captureFile, ""); const networkCreate = await runHost( @@ -657,8 +693,6 @@ export async function startFakeDockerApi( container, "--network", network, - "-p", - "0:8080", "-e", `${options.portEnv}=8080`, "-e", @@ -666,9 +700,7 @@ export async function startFakeDockerApi( "-e", `${options.captureFileEnv}=/tmp/fake/capture.jsonl`, ]; - if (options.kind === "slack") { - dockerArgs.push("-p", "0:8081", "-e", "FAKE_SLACK_API_WEBSOCKET_PORT=8081"); - } + if (options.kind === "slack") dockerArgs.push("-e", "FAKE_SLACK_API_WEBSOCKET_PORT=8081"); for (const [key, value] of Object.entries(options.expectedEnv)) { dockerArgs.push("-e", `${key}=${value}`); } @@ -707,40 +739,110 @@ export async function startFakeDockerApi( }); expectExitZero(start, `start fake ${options.kind} API`); + let apiReady = false; for (let attempt = 0; attempt < 100; attempt += 1) { if (fs.existsSync(portFile) && fs.statSync(portFile).size > 0) { - const restPort = await runHost(host, "docker", ["port", container, "8080/tcp"], { - artifactName: `port-fake-${options.kind}-api`, + apiReady = true; + break; + } + await sleep(100); + } + if (!apiReady) throw new Error(`fake ${options.kind} API did not become ready`); + + cleanup(`remove ${proxyContainer}`, async () => { + const remove = await runHost(host, "docker", ["rm", "-f", proxyContainer], { + artifactName: `cleanup-${proxyContainer}`, + env: options.env, + redactionValues: options.redactionValues, + timeoutMs: 60_000, + }); + if (remove.exitCode !== 0 && !/No such container:/iu.test(resultText(remove))) { + expectExitZero(remove, `remove fake ${options.kind} API proxy ${proxyContainer}`); + } + }); + + const proxyStart = await runHost( + host, + "docker", + [ + "run", + "-d", + "--rm", + "--name", + proxyContainer, + "--network", + "bridge", + ...containerPorts.flatMap((port) => ["-p", `127.0.0.1::${String(port)}`]), + "--read-only", + "--cap-drop", + "ALL", + "--security-opt", + "no-new-privileges", + "--pids-limit", + "32", + "-e", + `NEMOCLAW_FAKE_API_UPSTREAM=${container}`, + "-e", + `NEMOCLAW_FAKE_API_PROXY_PORTS=${containerPorts.join(",")}`, + FAKE_API_IMAGE, + "node", + "-e", + FAKE_API_PROXY_SOURCE, + ], + { + artifactName: `start-fake-${options.kind}-api-proxy`, + env: options.env, + redactionValues: options.redactionValues, + timeoutMs: 120_000, + }, + ); + expectExitZero(proxyStart, `start fake ${options.kind} API proxy`); + + const proxyConnect = await runHost( + host, + "docker", + ["network", "connect", network, proxyContainer], + { + artifactName: `connect-fake-${options.kind}-api-proxy`, + env: options.env, + redactionValues: options.redactionValues, + timeoutMs: 30_000, + }, + ); + expectExitZero(proxyConnect, `connect fake ${options.kind} API proxy`); + + const publishedPort = async (containerPort: number, artifactName: string): Promise => { + const result = await runHost( + host, + "docker", + ["port", proxyContainer, `${String(containerPort)}/tcp`], + { + artifactName, env: options.env, redactionValues: options.redactionValues, timeoutMs: 30_000, - }); - const publishedRestPort = restPort.stdout.trim().split(":").at(-1)?.trim() ?? ""; - let publishedWebsocketPort = ""; - if (options.kind === "slack") { - const websocketPort = await runHost(host, "docker", ["port", container, "8081/tcp"], { - artifactName: "port-fake-slack-websocket-api", - env: options.env, - redactionValues: options.redactionValues, - timeoutMs: 30_000, - }); - publishedWebsocketPort = websocketPort.stdout.trim().split(":").at(-1)?.trim() ?? ""; - } - if (publishedRestPort && (options.kind !== "slack" || publishedWebsocketPort)) { - return { - kind: options.kind, - port: publishedRestPort, - ...(options.kind === "slack" ? { alternatePort: publishedWebsocketPort } : {}), - dir, - captureFile, - container, - }; - } + }, + ); + expectExitZero(result, `read fake ${options.kind} API proxy port`); + const hostPort = result.stdout.trim().match(/^127\.0\.0\.1:(\d+)$/u)?.[1]; + if (!hostPort) { + throw new Error(`fake ${options.kind} API proxy port did not bind only to 127.0.0.1`); } - await sleep(100); - } + return hostPort; + }; - throw new Error(`fake ${options.kind} API did not publish a port`); + const publishedRestPort = await publishedPort(8080, `port-fake-${options.kind}-api`); + const publishedWebsocketPort = + options.kind === "slack" ? await publishedPort(8081, "port-fake-slack-websocket-api") : ""; + + return { + kind: options.kind, + port: publishedRestPort, + ...(options.kind === "slack" ? { alternatePort: publishedWebsocketPort } : {}), + dir, + captureFile, + container, + }; } export async function applyRestRewritePolicy( diff --git a/test/e2e/support/messaging-providers-runtime-proofs.test.ts b/test/e2e/support/messaging-providers-runtime-proofs.test.ts index 11a67a618c9..620feec9c1c 100644 --- a/test/e2e/support/messaging-providers-runtime-proofs.test.ts +++ b/test/e2e/support/messaging-providers-runtime-proofs.test.ts @@ -9,6 +9,7 @@ import path from "node:path"; import { describe, expect, it } from "vitest"; import { buildProcessTokenProbe } from "../fixtures/process-token-probe.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; import { buildSandboxNodeInvocation, buildSandboxShellInvocation, @@ -16,6 +17,7 @@ import { messagingEnv, OPENSHELL_EXEC_ARGUMENT_LIMIT_BYTES, parseRuntimeProofPort, + startFakeDockerApi, } from "../live/messaging-providers-helpers.ts"; import { parseInstalledSlackProof, @@ -37,7 +39,127 @@ async function waitFor(predicate: () => boolean, message: string): Promise expect(matched, message).toBe(true); } +type CleanupAction = { + name: string; + run: () => Promise; +}; + +function successfulCommand(stdout = "") { + return { + artifacts: { result: "", stderr: "", stdout: "" }, + command: [], + exitCode: 0, + signal: null, + stderr: "", + stdout, + timedOut: false, + }; +} + +function fakeDockerHost(publishedAddress = "127.0.0.1"): { + calls: string[][]; + host: HostCliClient; +} { + const calls: string[][] = []; + const host = { + command: async (command: string, args: string[]) => { + expect(command).toBe("docker"); + calls.push([...args]); + args + .filter((argument) => args[0] === "run" && argument.endsWith(":/tmp/fake")) + .forEach((fakeApiMount) => { + const fixtureDir = fakeApiMount.slice(0, -":/tmp/fake".length); + fs.writeFileSync(path.join(fixtureDir, "port"), "8080"); + }); + return args[0] === "port" + ? successfulCommand(`${publishedAddress}:${args[2] === "8081/tcp" ? "32101" : "32100"}\n`) + : successfulCommand(); + }, + } as unknown as HostCliClient; + return { calls, host }; +} + +async function runCleanup(actions: CleanupAction[]): Promise { + for (let index = actions.length - 1; index >= 0; index -= 1) await actions[index]!.run(); +} + describe("messaging provider installed-runtime proofs", () => { + it.each([ + ["discord-gateway", ["127.0.0.1::8080"], ["8080/tcp"]], + ["slack", ["127.0.0.1::8080", "127.0.0.1::8081"], ["8080/tcp", "8081/tcp"]], + ] as const)( + "proxies the isolated fake %s API through loopback-only ephemeral ports", + async (kind, expectedPublications, expectedPortQueries) => { + const { calls, host } = fakeDockerHost(); + const cleanup: CleanupAction[] = []; + + try { + const api = await startFakeDockerApi(host, (name, run) => cleanup.push({ name, run }), { + kind, + imageScript: `fake-${kind}-api.cjs`, + containerPrefix: `fake-${kind}`, + portEnv: "FAKE_API_PORT", + portFileEnv: "FAKE_API_PORT_FILE", + captureFileEnv: "FAKE_API_CAPTURE_FILE", + expectedEnv: {}, + redactionValues: [], + env: {}, + }); + const networkCreate = calls.find((args) => args[0] === "network" && args[1] === "create"); + const runCalls = calls.filter((args) => args[0] === "run"); + expect(networkCreate).toBeDefined(); + expect(runCalls).toHaveLength(2); + const createdNetwork = networkCreate!; + const [apiRun, proxyRun] = runCalls as [string[], string[]]; + const network = createdNetwork.at(-1); + const apiContainer = apiRun[apiRun.indexOf("--name") + 1]; + const proxyContainer = proxyRun[proxyRun.indexOf("--name") + 1]; + const publications = proxyRun.flatMap((argument, index) => + argument === "-p" ? [proxyRun[index + 1]] : [], + ); + + expect(createdNetwork.slice(0, -1)).toEqual(["network", "create", "--internal"]); + expect(apiRun).toEqual(expect.arrayContaining(["--network", network])); + expect(apiRun).not.toContain("-p"); + expect(apiRun).not.toContain("bridge"); + expect(publications).toEqual(expectedPublications); + expect(proxyRun).toEqual(expect.arrayContaining(["--network", "bridge"])); + expect(calls).toContainEqual(["network", "connect", network, proxyContainer]); + expect( + calls.filter((args) => args[0] === "port").map((args) => [args[1], args[2]]), + ).toEqual(expectedPortQueries.map((port) => [proxyContainer, port])); + expect(proxyContainer).not.toBe(apiContainer); + expect(api.port).toBe("32100"); + expect(api.alternatePort).toBe(kind === "slack" ? "32101" : undefined); + } finally { + await runCleanup(cleanup); + } + }, + ); + + it("rejects a fake API proxy port that Docker publishes beyond loopback", async () => { + const { host } = fakeDockerHost("0.0.0.0"); + const cleanup: CleanupAction[] = []; + + try { + await expect( + startFakeDockerApi(host, (name, run) => cleanup.push({ name, run }), { + kind: "discord-gateway", + imageScript: "fake-discord-gateway-api.cjs", + containerPrefix: "fake-discord-gateway", + portEnv: "FAKE_API_PORT", + portFileEnv: "FAKE_API_PORT_FILE", + captureFileEnv: "FAKE_API_CAPTURE_FILE", + expectedEnv: {}, + redactionValues: [], + env: {}, + }), + ).rejects.toThrow(/did not bind only to 127\.0\.0\.1/u); + } finally { + await runCleanup(cleanup); + } + }); + it("uses a synthetic WeChat token even when the host exports one", () => { const previousToken = process.env.WECHAT_BOT_TOKEN; process.env.WECHAT_BOT_TOKEN = "host-wechat-token-must-not-reach-the-fake-api";