import assert from "node:assert/strict" import { createHash, randomUUID } from "node:crypto" import { createSocket } from "node:dgram" import { createServer as httpServer } from "node:http" import { createServer as tcpServer, type Socket } from "node:net" import { createRequire, syncBuiltinESMExports } from "node:module" import { basename, dirname, resolve } from "node:path" import { realpath } from "node:fs/promises" import { setTimeout as delay } from "node:timers/promises" import type { ServerProbeRequest } from "../../services/server-probe-execution-model.js" const gate = () => { let resolve!: () => void; const promise = new Promise(done => { resolve = done }); return { promise, resolve } } async function bounded(value: Promise, label: string) { let timer: ReturnType | undefined try { return await Promise.race([value, new Promise((_yes, no) => { timer = setTimeout(() => no(Error(label)), 15000) })]) } finally { clearTimeout(timer) } } /** All six public tools through genuine production registry/runner/storage. * Only owned HTTP/DNS endpoints and one real-SQL pending-run barrier are used; * no service, authority, source, resolver method or query result is replaced. */ export async function acceptServerProbeAllToolsSql() { assert.equal(process.env.MMAPP_OWN_PROBE_STORAGE_JOURNAL, "true") const routeOnly = process.env.MMAPP_OWN_ALL_TOOLS_ROUTE_ONLY === "true" const url = new URL(process.env.DATABASE_URL ?? "") assert.equal(url.hostname, "127.0.0.1"); assert.equal(url.pathname, "/postgres"); assert.equal(decodeURIComponent(url.username), "mcp_test") assert.equal(process.env.MMAPP_OWN_SQL_DB, "postgres"); assert.equal(url.search, ""); assert.equal(url.hash, "") assert(["postgres:", "postgresql:"].includes(url.protocol)); assert(process.env.MCP_STATE_DIR) const state = resolve(process.env.MCP_STATE_DIR) assert.equal(basename(state), "state"); assert.match(basename(dirname(state)), /^mm-mcp-test-[A-Za-z0-9-]+$/) assert.equal(resolve(await realpath(state)).toLowerCase(), state.toLowerCase()) const { pool } = await import("../../db/index.js") const { invokeMcpTool, approvePlan, applyPlan } = await import("./runtime.js") const { createMcpConnection, authenticateMcpToken, rotateConnectionToken } = await import("./store.js") const { mcpConnectionCreateSchema } = await import("@mmapp/contracts/mcp") const { findAction } = await import("./actions.js") const { SERVER_PROBE_CANCEL_OPERATION } = await import("./server-probe-registration.js") const { SERVER_PROBE_OPERATION, SERVER_PROBE_RECEIPT_READ_OPERATION } = await import("../../services/server-probe-authority.js") assert.equal(findAction("mm_server_probe_plan").operation.id, SERVER_PROBE_OPERATION) assert.equal((await pool.query("SELECT to_regclass('server_probe_storage_admissions') IS NOT NULL AS ready")).rows[0].ready, true) const dnsPromises = createRequire(import.meta.url)("node:dns/promises") as typeof import("node:dns/promises") const originalResolver = dnsPromises.Resolver, originalQuery = pool.query const connections: string[] = [], servers: number[] = [], cases: string[] = [], sockets = new Set() const username = "OWNED_ALLTOOLS_PRIVATE_USER", password = "OWNED_ALLTOOLS_PRIVATE_PASSWORD", privateValues = [username, password] let requests = 0, dnsUdp = 0, dnsTcp = 0, resolvers = 0, protocolErrors = 0 let routerListening = false, dnsListening = false, tcpListening = false const previousEnabled = (await pool.query("SELECT enabled FROM mcp_settings WHERE id=1")).rows[0].enabled const hidden = (value: unknown) => { const content = JSON.stringify(value); assert(!privateValues.some(secret => content.includes(secret)), "Private endpoint material escaped") } const router = httpServer(async (request, response) => { response.setHeader("content-type", "application/json") try { requests++; assert.equal(request.socket.remoteAddress, "127.0.0.1") assert.equal(request.headers.authorization, "Basic " + Buffer.from(`${username}:${password}`).toString("base64")) if (request.method === "GET") { assert.equal(request.url, "/rest/ip/route") response.end(JSON.stringify([{ active: "true", "dst-address": "0.0.0.0/0", gateway: "127.0.0.1", distance: "1" }])) return } assert.equal(request.method, "POST") let raw = ""; for await (const chunk of request) raw += chunk const body = JSON.parse(raw) as Record assert.equal(body.address, "127.0.0.1") if (request.url === "/rest/tool/bandwidth-test") { assert.equal(body.user, username); assert.equal(body.password, password) response.end(JSON.stringify([{ "tx-current": "1000", "rx-current": "2000" }])) } else if (request.url === "/rest/tool/traceroute") response.end(JSON.stringify([{ address: "127.0.0.1", loss: "0%", last: "1ms", avg: "1ms" }])) else { assert.equal(request.url, "/rest/tool/ping") if (body["do-not-fragment"] === "true" && body.size === "1500") response.end(JSON.stringify([{ seq: "0", status: "timeout" }])) else response.end(JSON.stringify([{ seq: "0", ttl: "64", time: "1ms", received: "1" }])) } } catch { protocolErrors++; response.statusCode = 502; response.end('{"error":"Owned all-tools protocol mismatch"}') } }) const udp = createSocket("udp4") const question = (packet: Buffer) => { assert(packet.length >= 17); assert.equal(packet.readUInt16BE(4), 1) let offset = 12; const labels: string[] = [] while (packet[offset]) { const length = packet[offset++]; assert(length <= 63 && offset + length < packet.length); labels.push(packet.subarray(offset, offset + length).toString("ascii")); offset += length } offset++; assert.equal(labels.join("."), "owned-alltools.invalid"); assert.equal(packet.readUInt16BE(offset), 16); assert.equal(packet.readUInt16BE(offset + 2), 1) return packet.subarray(12, offset + 4) } const answer = (packet: Buffer, truncate: boolean) => { const selected = question(packet), header = Buffer.alloc(12) header.writeUInt16BE(packet.readUInt16BE(0), 0); header.writeUInt16BE(truncate ? 0x8380 : 0x8180, 2); header.writeUInt16BE(1, 4) if (truncate) return Buffer.concat([header, selected]) header.writeUInt16BE(2, 6) const records = ["FIRST_PUBLIC_DNS_RECORD_", "SECOND_PUBLIC_DNS_RECORD_"].map(prefix => { const chunks = Array.from({ length: 16 }, (_, index) => Buffer.from((prefix + index + "_").padEnd(200, "A"), "ascii")) const data = Buffer.concat(chunks.flatMap(chunk => [Buffer.from([chunk.length]), chunk])), rr = Buffer.alloc(12) rr.writeUInt16BE(0xc00c, 0); rr.writeUInt16BE(16, 2); rr.writeUInt16BE(1, 4); rr.writeUInt32BE(60, 6); rr.writeUInt16BE(data.length, 10) return Buffer.concat([rr, data]) }) return Buffer.concat([header, selected, ...records]) } udp.on("message", (packet, remote) => { try { dnsUdp++; assert.equal(remote.address, "127.0.0.1"); udp.send(answer(packet, true), remote.port, remote.address) } catch { protocolErrors++ } }) const tcp = tcpServer(socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)); socket.on("error", () => {}) let received = Buffer.alloc(0) socket.on("data", chunk => { try { received = Buffer.concat([received, chunk]); if (received.length < 2 || received.length < received.readUInt16BE(0) + 2) return assert.equal(socket.remoteAddress, "127.0.0.1"); dnsTcp++ const response = answer(received.subarray(2, received.readUInt16BE(0) + 2), false), size = Buffer.alloc(2); size.writeUInt16BE(response.length) socket.end(Buffer.concat([size, response])); received = Buffer.alloc(0) } catch { protocolErrors++; socket.destroy() } }) }) let releasePending: (() => void) | undefined try { await new Promise((yes, no) => { router.once("error", no); router.listen(0, "127.0.0.1", yes) }); routerListening = true await new Promise((yes, no) => { udp.once("error", no); udp.bind(0, "127.0.0.1", yes) }); dnsListening = true const dnsPort = udp.address().port await new Promise((yes, no) => { tcp.once("error", no); tcp.listen(dnsPort, "127.0.0.1", yes) }); tcpListening = true // Constructor endpoint wrapper only: every resolve operation, wire parser, // production beforeDispatch fence and cancellation method remains genuine. dnsPromises.Resolver = class extends originalResolver { constructor(...args: ConstructorParameters) { super(...args); this.setServers([`127.0.0.1:${dnsPort}`]); resolvers++ assert.deepEqual(this.getServers(), [`127.0.0.1:${dnsPort}`]) } } syncBuiltinESMExports() await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1") servers.push(...(await pool.query("INSERT INTO servers(name,host,port,use_ssl,verify_ssl,enabled,username,password) VALUES('owned-alltools-source','127.0.0.1',$1,false,false,true,$2,$3),('owned-alltools-destination','127.0.0.1',$1,false,false,true,$2,$3) RETURNING id", [(router.address() as { port: number }).port, username, password])).rows.map(row => Number(row.id))) const fixture = async () => { const actor = { id: "owned-alltools-" + randomUUID(), email: "fixture@example.test", name: "Owned all tools", apps: ["mm"], permissions: ["mm:servers:write", "mm:servers:read", "mm:mcp:approve"], issuedAt: Date.now() - 1000, expiresAt: Date.now() + 3600000 } const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Owned all-tools production registry", mode: "approval", expiresAt: new Date(actor.expiresAt).toISOString(), permissions: ["mm:servers:write", "mm:servers:read"], scope: { serverIds: servers, operationIds: [SERVER_PROBE_OPERATION, SERVER_PROBE_RECEIPT_READ_OPERATION, SERVER_PROBE_CANCEL_OPERATION], allowGlobal: false }, limits: { callsPerMinute: 120, mutationsPerHour: 1000 } }), actor) connections.push(access.connection.id); privateValues.push(access.token) return { actor, principal: await authenticateMcpToken(access.token) } } const terminal = async (operationId: string) => { for (const until = Date.now() + 90000; Date.now() < until;) { const row = (await pool.query("SELECT id,state,result,error_code FROM mcp_operations WHERE id=$1", [operationId])).rows[0] assert(row); if (!["pending", "running"].includes(row.state)) return row await delay(20) } throw Error("Owned all-tools operation did not reach terminal state") } const prepare = async (f: Awaited>, request: ServerProbeRequest) => { const before = requests + dnsUdp + dnsTcp const result = await invokeMcpTool(f.principal, "mm_server_probe_plan", { serverId: servers[0], request }) as { planId: string; state: string } hidden(result); assert.equal(result.state, "awaiting-approval"); assert.equal(requests + dnsUdp + dnsTcp, before) await assert.rejects(applyPlan(f.principal, result.planId, randomUUID())); assert.equal(requests + dnsUdp + dnsTcp, before) await approvePlan(result.planId, f.actor, true) return result.planId } const selectedTools: readonly ServerProbeRequest["tool"][] = routeOnly ? ["route"] : ["ping", "traceroute", "bandwidth", "dns", "route", "mtu"] for (const tool of selectedTools) { const f = await fixture() const request: ServerProbeRequest = tool === "bandwidth" ? { tool, bwRemoteAddress: "127.0.0.1", dstServerId: servers[1] } : tool === "dns" ? { tool, target: "owned-alltools.invalid", dnsType: "TXT" } : { tool, target: "127.0.0.1", ...(tool === "ping" ? { pingCount: 1 } : {}) } const startedAt = Date.now(), requestStart = requests, udpStart = dnsUdp, tcpStart = dnsTcp const planId = await prepare(f, request), key = randomUUID(), operation = await applyPlan(f.principal, planId, key), done = await terminal(operation.id) const progress = done.result?.diagnosticProgress const stageTimes = (await pool.query(`SELECT s.stage_index,s.kind,s.state,s.created_at,s.received_at FROM server_probe_execution_stages s JOIN server_probe_executions e USING(receipt_id) WHERE e.execution_id=$1 ORDER BY s.stage_index`, [operation.id])).rows // Emit bounded, selected facts BEFORE success assertions. No IDs, source // fields, raw provider data, private bindings, credentials or error text. console.log("Owned all-tools stage trace:", JSON.stringify({ tool, elapsedMs: Date.now() - startedAt, state: done.state, errorCode: done.error_code ?? null, httpRequests: requests - requestStart, dnsUdpQueries: dnsUdp - udpStart, dnsTcpQueries: dnsTcp - tcpStart, ...(progress ? { progress: { state: progress.state, attemptedStages: progress.attemptedStages, completedStages: progress.completedStages } } : {}), stages: stageTimes.map(row => ({ index: row.stage_index, kind: row.kind, state: row.state, createdAt: row.created_at, receivedAt: row.received_at })) })) assert.equal(done.state, "applied", tool + ": " + String(done.error_code)); hidden(done.result) assert.equal(done.result.confirmedWrites, 0); assert.equal(done.result.completedServiceSteps, 1); assert.equal(done.result.verificationScope, "acknowledgement") const receipt = done.result.diagnosticReceipt as { receiptId: string; stageBudget: number; attemptedStages: number; completedStages: number; totalPages: number; sha256: string } assert(receipt); assert.equal(receipt.attemptedStages, receipt.completedStages); assert(receipt.attemptedStages > 0 && receipt.attemptedStages <= receipt.stageBudget) let captured = false for (const until = Date.now()+2000; Date.now()>'terminalAt'=to_char(GREATEST(o.finished_at,p.expires_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS terminal_matches FROM server_probe_terminal_proofs f JOIN mcp_operations o ON o.id=f.operation_id JOIN mcp_plans p ON p.id=o.plan_id WHERE f.operation_id=$1 AND f.receipt_id=$2`, [done.id,receipt.receiptId])).rows[0] if (proof) { assert.equal(proof.terminal_matches,true); captured = true; break } await delay(20) } assert.equal(captured,true,"Owned successful diagnostic did not publish its terminal proof") const step = (await pool.query("SELECT state,result FROM mcp_operation_steps WHERE operation_id=$1", [done.id])).rows assert.equal(step.length, 1); assert.equal(step[0].state, "acknowledged") for (const field of ["output", "data", "contentB64", "bindingCiphertext"]) assert(!Object.hasOwn(step[0].result, field)) const ledger = (await pool.query("SELECT stage_index,kind,state FROM server_probe_execution_stages WHERE receipt_id=$1 ORDER BY stage_index", [receipt.receiptId])).rows assert.equal(ledger.length, receipt.attemptedStages); assert(ledger.every((row, index) => row.stage_index === index + 1 && row.state === "received")) if (tool === "mtu") assert.deepEqual(ledger.map(row => row.kind), ["native-mtu-1500", "native-mtu-1492"]) const beforeRead = requests + dnsUdp + dnsTcp, chunks: Buffer[] = [] for (let page = 0; page < receipt.totalPages; page++) { const part = await invokeMcpTool(f.principal, "mm_server_probe_receipt_get", { operationId: done.id, receiptId: receipt.receiptId, page }) as { sha256: string; contentB64: string } assert.equal(part.sha256, receipt.sha256); chunks.push(Buffer.from(part.contentB64, "base64")); hidden(part) } const complete = Buffer.concat(chunks); assert.equal(createHash("sha256").update(complete).digest("hex"), receipt.sha256) const measurement = JSON.parse(complete.toString("utf8")); hidden(measurement); assert.equal(measurement.tool, tool); assert.equal(measurement.forwardingVerified, false) if (tool === "dns") { assert(receipt.totalPages > 1); assert.equal(dnsUdp, 1); assert.equal(dnsTcp, 1); assert.equal(resolvers, 1) const rotated = await rotateConnectionToken(f.principal.connectionId, f.actor); privateValues.push(rotated.token) await pool.query("UPDATE mcp_connections SET owner_permissions=$2::jsonb,policy=jsonb_set(jsonb_set(jsonb_set(policy,'{permissions}',$2::jsonb),'{scope,operationIds}',$3::jsonb),'{mode}','\"observer\"'::jsonb) WHERE id=$1", [f.principal.connectionId, JSON.stringify(["mm:servers:read"]), JSON.stringify([SERVER_PROBE_RECEIPT_READ_OPERATION])]) const reader = await authenticateMcpToken(rotated.token) for (let page = 0; page < receipt.totalPages; page++) await invokeMcpTool(reader, "mm_server_probe_receipt_get", { operationId: done.id, receiptId: receipt.receiptId, page }) await assert.rejects(invokeMcpTool(f.principal, "mm_server_probe_receipt_get", { operationId: done.id, receiptId: receipt.receiptId, page: 0 })) await pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{scope,serverIds}','[]') WHERE id=$1", [reader.connectionId]) await assert.rejects(invokeMcpTool(reader, "mm_server_probe_receipt_get", { operationId: done.id, receiptId: receipt.receiptId, page: 1 })) } if (tool !== "dns") assert.equal((await applyPlan(f.principal, planId, key)).id, done.id) assert.equal(requests + dnsUdp + dnsTcp, beforeRead) const audit = (await pool.query("SELECT payload FROM mcp_audit WHERE connection_id=$1 AND action='operation.complete'", [f.principal.connectionId])).rows assert.equal(audit.length, 1); assert.equal(audit[0].payload.confirmedWrites, 0) cases.push(tool + ": actual public plan/approval/apply, receipt metadata, full stage ledger and checksum pages without redispatch") } // Force a genuine capture SQL failure after the real diagnostic has // committed. A sequence records the rejected attempt despite rollback. const captureFault = await fixture() const faultPlan = await prepare(captureFault, { tool: "route", target: "127.0.0.1" }) await pool.query("CREATE SEQUENCE public.owned_probe_capture_failure") try { await pool.query(`CREATE FUNCTION public.owned_probe_capture_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.source->>'connectionId'=TG_ARGV[0] THEN PERFORM nextval('public.owned_probe_capture_failure'); RAISE EXCEPTION 'owned terminal proof insertion refused'; END IF; RETURN NEW; END $$`) try { assert.match(captureFault.principal.connectionId,/^[a-f0-9-]{36}$/) await pool.query(`CREATE TRIGGER owned_probe_capture_failure BEFORE INSERT ON public.server_probe_terminal_proofs FOR EACH ROW EXECUTE FUNCTION public.owned_probe_capture_failure('${captureFault.principal.connectionId}')`) try { const beforeFault = requests+dnsUdp+dnsTcp, faultKey=randomUUID() const applied = await applyPlan(captureFault.principal,faultPlan,faultKey), done=await terminal(applied.id) let attempted = false for (const until=Date.now()+2500;Date.now()running SQL BEFORE sending it. This // leaves a real pending approved source, allowing genuine durable cancel. // A server-table lock after 'running' would have no intent step yet and the // source loader correctly refuses that incomplete running source. const f = await fixture(), planId = await prepare(f, { tool: "ping", target: "127.0.0.1", pingCount: 1 }) const entered = gate(), resume = gate(); releasePending = resume.resolve let heldOperation = "", held = false pool.query = (async function (...args: unknown[]) { const query = args[0] as { text?: string; values?: unknown[] } | undefined if (!held && query?.text?.startsWith("/* mcp-operation-root:claim */") && typeof query.values?.[0] === "string") { held = true; heldOperation = query.values[0]; entered.resolve(); await resume.promise } return Reflect.apply(originalQuery, pool, args) }) as typeof pool.query const beforeCancel = requests + dnsUdp + dnsTcp, key = randomUUID(), operation = await applyPlan(f.principal, planId, key) await bounded(entered.promise, "Runner did not reach real SQL pending barrier"); assert.equal(heldOperation, operation.id) assert.equal((await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [operation.id])).rows[0].state, "pending") const stopped = await invokeMcpTool(f.principal, "mm_server_probe_cancel", { operationId: operation.id }) as { cancelRequested: boolean; terminal: boolean } assert.equal(stopped.cancelRequested, true); assert.equal(stopped.terminal, false) pool.query = originalQuery; resume.resolve(); releasePending = undefined const done = await terminal(operation.id); assert.equal(done.state, "rejected"); assert.equal(done.result.confirmedWrites, 0) assert.deepEqual(done.result.diagnosticProgress && { attempted: done.result.diagnosticProgress.attemptedStages, completed: done.result.diagnosticProgress.completedStages, state: done.result.diagnosticProgress.state }, { attempted: 0, completed: 0, state: "cancelled" }) assert.equal(done.result.needsReview, false); assert.equal(requests + dnsUdp + dnsTcp, beforeCancel) const untouched = (await pool.query(`SELECT (SELECT count(*)::int FROM server_probe_executions WHERE execution_id=$1) AS anchors, (SELECT count(*)::int FROM server_probe_execution_stages s JOIN server_probe_executions e USING(receipt_id) WHERE e.execution_id=$1) AS stages, (SELECT count(*)::int FROM server_probe_execution_payloads p JOIN server_probe_executions e USING(receipt_id) WHERE e.execution_id=$1) AS payloads, (SELECT count(*)::int FROM mcp_diagnostic_cancellations WHERE operation_id=$1) AS stops, (SELECT count(*)::int FROM mcp_audit WHERE action='diagnostic.cancel-requested' AND payload->>'operationId'=$1::text) AS audits`, [operation.id])).rows[0] assert.deepEqual(untouched, { anchors: 0, stages: 0, payloads: 0, stops: 1, audits: 1 }) assert.equal((await applyPlan(f.principal, planId, key)).id, operation.id); assert.equal(requests + dnsUdp + dnsTcp, beforeCancel) cases.push("pre-first-send: actual pending SQL barrier, public durable cancellation, rejected zero-stage/no-anchor/no-payload and idempotent replay without provider I/O") assert.equal(protocolErrors, 0) return { cases, actualProductionRegistry: true, allSixTools: !routeOnly, isolatedRouteOnly: routeOnly, productionAuthorityAndStorage: true, loopbackHttpRequests: requests, localDnsUdpQueries: dnsUdp, localDnsTcpQueries: dnsTcp, actualDnsWireParsingAndTcpFallback: !routeOnly, dnsResolverConstructorEndpointWrapperOnly: true, dnsResolutionOrServiceOverrides: false, largeDnsPagesWithChecksum: !routeOnly, currentReadonlyCredentialPages: !routeOnly, genuinePendingSqlBarrierBeforeFirstDispatch: true, preCancelledZeroStageNoAnchor: true, confirmedConfigurationWrites: 0, productionOrMachineDnsChanges: false, externalNetwork: false } } finally { pool.query = originalQuery; releasePending?.() dnsPromises.Resolver = originalResolver; syncBuiltinESMExports(); assert.equal(dnsPromises.Resolver, originalResolver) if (connections.length) await pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"revoked\"'::jsonb) WHERE id=ANY($1::uuid[])", [connections]) if (servers.length) await pool.query("UPDATE servers SET enabled=false WHERE id=ANY($1::int[])", [servers]) await pool.query("UPDATE mcp_settings SET enabled=$1 WHERE id=1", [previousEnabled]) router.closeAllConnections(); for (const socket of sockets) socket.destroy() if (routerListening) await new Promise(yes => router.close(() => yes())) if (tcpListening) await new Promise(yes => tcp.close(() => yes())) if (dnsListening) await new Promise(yes => udp.close(() => yes())) } }