import assert from "node:assert/strict" import { createHmac, randomUUID } from "node:crypto" import { pool } from "../db/index.js" import { McpError } from "../modules/mcp/security.js" import { createServerProbeExecutor, type ServerProbeAuthority, type ServerProbeEndpoint, type ServerProbeExecutionDependencies, type ServerProbeJournal, type ServerProbeReceipt } from "./server-probe-execution.js" import { createServerProbeRestExecution } from "./server-probe-rest-execution.js" import type { ServerProbeJournalContext } from "./server-probe-journal.js" // The real common executor is exercised; only transport/storage/authority I/O // is synthetic. Importing/running this profile must never contact an endpoint. const oldQuery = pool.query, oldConnect = pool.connect pool.query = (() => { throw Error("Actual SQL forbidden") }) as never pool.connect = (() => { throw Error("Actual SQL forbidden") }) as never let cases = 0 function fixture() { const now = Date.now(), controller = new AbortController() const authority: ServerProbeAuthority = { transport: "rest", ownerId: "local-operator", requestId: randomUUID(), issuedAt: now, expiresAt: now + 300000, generation: "epoch", policyProof: "a".repeat(64), ownerProof: "b".repeat(64), active: true, operationAllowed: true, scopeServerIds: [1, 2], ownerPermissions: ["mm:servers:write"], policyPermissions: ["mm:servers:write"] } const endpoint: ServerProbeEndpoint = { id: 1, enabled: true, host: "192.0.2.1", port: 80, username: "PRIVATE_USER", password: "PRIVATE_PASSWORD", useSsl: false, verifySsl: true, routingEndpointEpoch: randomUUID() } const sealed = new Map(), claims = new Map(), receipts = new Map() let raw: unknown = [{ seq: "0", ttl: "64", time: "1ms" }], journalContext: ServerProbeJournalContext | undefined, guards: (() => Promise) | undefined let sends = 0, claimsAttempted = 0, loseClaim = false, corruptRead = false, sourceReads = 0, actorCalls = 0, claimProof = "", afterSend: (() => void) | undefined const access = { async readAuthority() { if (!authority.active) throw new McpError("OWNER_CLAIMS_REVOKED", "PRIVATE_REVOKE", 401); return structuredClone(authority) }, async assertProtections() {} } const journal: ServerProbeJournal = { async claim(binding) { claimsAttempted++; claimProof = binding.bindingProof; await guards!(); if (loseClaim) throw Error("PRIVATE_COMMIT_ACK"); if (claims.has(binding.receiptId)) return "exists"; claims.set(binding.receiptId, binding.bindingProof); return "claimed" }, async intent() { await guards!() }, async received() { await guards!() }, async finish(receipt) { await guards!(); receipts.set(receipt.receiptId, structuredClone(receipt)) }, async quarantine(binding) { receipts.set(binding.receiptId, { receiptId: binding.receiptId, tool: binding.tool as ServerProbeReceipt["tool"], serverId: 1, state: "unknown", httpStatus: 503, errorCode: binding.errorCode, attemptedStages: binding.attemptedStages, completedStages: binding.completedStages, automaticReplay: false, forwardingVerified: false }) }, async read(id) { await guards!(); const row = receipts.get(id); return row && corruptRead ? { ...row, output: "FORGED_PUBLIC_RESULT" } : row }, } const dependencies: Omit = { ...access, async getServer(id) { sourceReads++; return [1, 2].includes(id) ? { ...endpoint, id, host: `192.0.2.${id}` } : undefined }, async findDestination() { return { id: 2 } }, async privateProof(domain, value) { return createHmac("sha256", "test-key").update(domain).update(JSON.stringify(value)).digest("hex") }, async seal(value) { const id = randomUUID(); sealed.set(id, value); return id }, async open(id) { return sealed.get(id)! }, async post(_source, _path, _body, _timeout, signal, fence) { signal.throwIfAborted(); await fence(); sends++; afterSend?.(); return structuredClone(raw) }, async routes(_source, _timeout, signal, fence) { signal.throwIfAborted(); await fence(); sends++; afterSend?.(); return structuredClone(raw) }, async dns(_name, _type, signal, fence) { signal.throwIfAborted(); await fence(); sends++; afterSend?.(); return structuredClone(raw) }, } const run = createServerProbeRestExecution({ authority: () => access, executor: injected => createServerProbeExecutor({ ...dependencies, ...injected }), journal: (context, deps) => { journalContext = context; guards = () => deps.assertAuthority!(context, claimProof); return journal }, actor: async (id, work) => { assert.equal(id, authority.ownerId); actorCalls++; return work() }, }) return { authority, controller, receipts, async run(tool = "ping", serverId = "1", extra: Record = {}) { return run(serverId, { tool, target: "192.0.2.2", bwRemoteAddress: "192.0.2.2", ...extra }, { requestId: authority.requestId!, acceptedAt: now, authRequired: false, signal: controller.signal }) }, raw(value: unknown) { raw = value }, loseClaim() { loseClaim = true }, corruptRead() { corruptRead = true }, afterSend(hook: () => void) { afterSend = hook }, counts() { return { sends, claimsAttempted, sourceReads, actorCalls } }, context() { return journalContext }, } } try { for (const tool of ["ping", "traceroute", "bandwidth", "dns", "route", "mtu"]) { const f = fixture() if (tool === "traceroute") f.raw([{ address: "192.0.2.2", loss: "0%", last: "1ms", avg: "1ms" }]) if (tool === "bandwidth") f.raw([{ "tx-current": "1", "rx-current": "2" }]) if (tool === "dns") f.raw(["192.0.2.2"]) if (tool === "route") f.raw([{ ".id": "*1", "dst-address": "192.0.2.0/24", active: "true", gateway: "ether1", distance: "1" }]) const reply = await f.run(tool, "1", { callerSuppliedIdentity: "ignored", executionId: "ignored" }) assert.equal(reply.statusCode, 200, JSON.stringify(reply)); assert.equal(typeof (reply.body as { output: string }).output, "string") assert(!JSON.stringify(reply).includes("PRIVATE_")); assert.equal(f.counts().claimsAttempted, 1); assert.equal(f.counts().actorCalls, 1) const context = f.context()!; assert.equal(context.identity.kind, "rest"); assert.equal("connectionId" in context.identity, false); assert.equal(context.sourceServerId, 1) assert.notEqual(context.identity.executionId, "ignored"); assert.equal(context.destinationServerId, tool === "bandwidth" ? 2 : undefined); cases++ } { const f = fixture(); assert.equal((await f.run("ping", "01")).statusCode, 400); assert.equal(f.counts().sourceReads, 0); assert.equal(f.context(), undefined); cases++ } { const f = fixture(); f.loseClaim(); const reply = await f.run(); assert.equal(reply.statusCode, 503); assert.equal(f.counts().sends, 0); assert(!JSON.stringify(reply).includes("PRIVATE_")); cases++ } { const f = fixture(); f.corruptRead(); const reply = await f.run(); assert.notEqual(reply.statusCode, 200); assert(!JSON.stringify(reply).includes("FORGED_PUBLIC_RESULT")); assert.equal(f.counts().sends, 1); cases++ } { const f = fixture(); f.afterSend(() => { f.authority.active = false }); const reply = await f.run(); assert.notEqual(reply.statusCode, 200); assert(!JSON.stringify(reply).includes("PRIVATE_")); assert.equal(f.counts().sends, 1); cases++ } { const f = fixture(); f.controller.abort(); const reply = await f.run(); assert.notEqual(reply.statusCode, 200); assert.equal(f.counts().sends, 0); assert.equal(f.counts().claimsAttempted, 0); cases++ } console.log(`REST common diagnostic execution: ${cases} inert cases passed; all six real executor paths, owned REST identity, admission failure, exact persisted receipt and late revoke/abort; no actual SQL/DNS/RouterOS`) } finally { pool.query = oldQuery; pool.connect = oldConnect }