Files
MikrotikManager/backend/src/modules/mcp/speed-bandwidth-original.sql-helper.ts
T

288 lines
30 KiB
TypeScript

/** Actual owned application/control SQL + localhost HTTP + private MCP origin,
* host receipt and workflow. Trusted verified-change COMPONENT entry only:
* uptime.speed-test has deliberately NOT been registered as public action/service.
* Enrollment quiescence and wire mapping remain explicitly synthetic fixtures. */
import assert from "node:assert/strict"
import { randomBytes, randomUUID, createHash } from "node:crypto"
import { ClientRequest, createServer } from "node:http"
import { writeFile } from "node:fs/promises"
import { join } from "node:path"
import { performance } from "node:perf_hooks"
import { assertOwnedBandwidthSql } from "../../services/bandwidth-admission-process.sql-helper.js"
import type { VerifiedMcpServiceMetadata } from "../../services/config-mutation-policy.js"
import type { McpSpeedBandwidthInput } from "./speed-bandwidth-original.js"
export async function acceptOwnedMcpSpeedWorkflow() {
assertOwnedBandwidthSql(); assert.equal(process.env.MMAPP_OWN_MCP_SPEED_ORIGINAL, "true")
assert.equal(process.env.MMAPP_OWN_BANDWIDTH_EXTERNAL_REGISTRY, "true")
const directory = process.env.MCP_STATE_DIR!
await writeFile(join(directory, "encryption-key"), randomBytes(32), { flag: "wx", mode: 0o600 })
await writeFile(join(directory, "access-generation"), randomBytes(32), { flag: "wx", mode: 0o600 })
const { createOwnedExternalRegistryHarness } = await import("../../services/bandwidth-external-node-registry.sql-helper.js")
const { pool } = await import("../../db/index.js")
const { Client: PgClient } = await import("pg")
const { speedTestCommandSchema, mcpConnectionCreateSchema } = await import("@mmapp/contracts")
const { hasPermission } = await import("../../lib/permissions.js")
const { createMcpConnection, authenticateMcpToken, effectiveMcpConnection } = await import("./store.js")
const { readMcpTemporaryGrantOrigin, assertOriginalMcpTemporaryGrant } = await import("./temporary-grant-origin.js")
const { withVerifiedConfigurationChange } = await import("../../services/config-mutation-policy.js")
const { accessGeneration, encryptSecret, decryptSecret, fingerprint, privateFingerprinterExisting, redact } = await import("./security.js")
const { createMcpSpeedBandwidthOriginalProvider } = await import("./speed-bandwidth-original.js")
const { findMcpService } = await import("./service-registry.js")
const { findActionByOperation } = await import("./actions.js")
assert.equal(findMcpService("uptime.speed-test"), undefined)
assert.throws(() => findActionByOperation("uptime.speed-test"))
const { createBandwidthPeerObservationReader } = await import("../../services/bandwidth-peer-observation.js")
const { createBandwidthPeerExecutionHost, readBandwidthPeerCompletion } = await import("../../services/bandwidth-peer-execution-host.js")
const { createBandwidthSpeedWorkflow } = await import("../../services/bandwidth-speed-workflow.js")
const { createBandwidthSpeedRunIdentity } = await import("../../services/bandwidth-speed-run-identity.js")
const f = await createOwnedExternalRegistryHarness(), application = await pool.connect().catch(async error => { await f.close(); throw error })
const provider = createMcpSpeedBandwidthOriginalProvider(), query = pool.query, clientQuery = PgClient.prototype.query, setTimeoutOriginal = ClientRequest.prototype.setTimeout
const ids: number[] = [], users: string[] = [], receipts: Array<{ canonicalNodeId: string }> = [], checks: string[] = [], metrics: Record<string, unknown>[] = []
const probeId = "owned-mcp-speed-probe-" + randomUUID(), generation = await accessGeneration(), sign = await privateFingerprinterExisting("routing-observation-source-v1")
const claims = [0, 1].map(index => ({ "system-id": "OWNED-MCP-FULL-SPEED-" + index + "-" + randomUUID(), "software-id": "OWNED-MCP-FULL-SPEED-" + index }))
let nativeGets = 0, nativePosts = 0, pingPosts = 0, protocolErrors = 0, credentialQueries = 0, credentialPayloads = 0, authorizerChecks = 0
let phase = "construction", mode = "positive", expectedBody: unknown, nativeBody: unknown, lastNativeFinished = 0, pingDelay = 0
let beforeResponse: (() => Promise<void>) | undefined, beforeCredentials: (() => Promise<void>) | undefined
let rawRows: Array<Record<string, string>> = [], completionReads = 0
type Latency = { completed: number; errors: number; totalMs: number; maxMs: number }
type Measurement = { began: number; appSql: number; controlSql: number; authorizersAtStart: number; families: Record<string, number>; latency: Record<string, Latency>; failures: Record<string, unknown>[] }
let measurement: Measurement = { began: performance.now(), appSql: 0, controlSql: 0, authorizersAtStart: 0, families: {}, latency: {}, failures: [] }
const beginMeasurement = () => { measurement = { began: performance.now(), appSql: 0, controlSql: 0, authorizersAtStart: authorizerChecks, families: {}, latency: {}, failures: [] } }
const latencyReport = () => Object.fromEntries(Object.entries(measurement.latency).map(([family, value]) => [family, {
completed: value.completed, errors: value.errors, totalMs: Math.round(value.totalMs * 1000) / 1000, maxMs: Math.round(value.maxMs * 1000) / 1000,
}]))
const sqlFamily = (text: string) => text.startsWith("/* mcp-speed-original:") ? /^\/\* mcp-speed-original:([a-z-]+)/.exec(text)?.[1] ?? "speed-source" : text.includes("FROM public.mcp_operations") ? "sealed-origin"
: text.includes("mcp_credentials") ? "credential-current" : text.includes("mcp_connections") ? "connection-current" : text.includes("mcp_grants") ? "grant-current"
: text.includes("mcp_owner_revocations") ? "portal-current" : text.includes("mcp_settings") ? "settings-current" : "other"
function failure(label: string, error: unknown, scope?: { deadlineAt: number; signal?: AbortSignal }) {
if (measurement.failures.length >= 12) return
const value = error as { name?: unknown; code?: unknown; phase?: unknown }
measurement.failures.push({ boundary: label, elapsedMs: Math.round(performance.now() - measurement.began),
remainingMs: scope ? Math.round(scope.deadlineAt - Date.now()) : undefined, aborted: scope?.signal?.aborted,
name: typeof value?.name === "string" && /^[A-Za-z]{1,80}$/.test(value.name) ? value.name : undefined,
code: typeof value?.code === "string" && /^[A-Z_0-9]{1,80}$/.test(value.code) ? value.code : undefined,
phase: typeof value?.phase === "string" && /^[a-z-]{1,80}$/.test(value.phase) ? value.phase : undefined })
}
async function observe<T>(label: string, scope: { deadlineAt: number; signal?: AbortSignal }, work: () => Promise<T>): Promise<T> {
try { return await work() } catch (error) { failure(label, error, scope); throw error }
}
const timeouts: Array<{ path: string; timeout: number }> = []
const routers = claims.map((license, index) => createServer(async (request, response) => {
try {
assert.equal(request.socket.remoteAddress, "127.0.0.1")
assert.equal(request.headers.authorization === "Basic " + Buffer.from(users[index] + ":owned-localhost-only").toString("base64"), true)
response.setHeader("content-type", "application/json")
if (request.method === "GET" && request.url === "/rest/system/license") { nativeGets++; response.end(JSON.stringify(license)); return }
if (request.method === "GET" && request.url === "/rest/ip/address") {
nativeGets++; response.end(JSON.stringify(index === 0 ? [{ interface: "source-if", address: "198.51.100.1/30" }] : [
{ interface: "dest-if", address: "198.51.100.99/30", dynamic: "true" }, { interface: "dest-if", address: "198.51.100.77/30", disabled: "true" },
{ interface: "dest-if", address: "198.51.100.66/30", invalid: "true" }, { interface: "dest-if", address: "198.51.100.2/30" },
])); return
}
assert.equal(request.method, "POST"); assert.equal(index, 0)
let text = ""; for await (const chunk of request) { text += String(chunk); assert(Buffer.byteLength(text) <= 65536) }
const body = JSON.parse(text)
if (request.url === "/rest/tool/bandwidth-test") {
nativePosts++; nativeBody = body; assert.deepEqual(body, expectedBody); await beforeResponse?.()
rawRows = [{ status: "testing", "tx-current": "1000000", retained: "owned-sample" }, { status: "done testing", "tx-total-average": "3000000", "rx-total-average": "4M", retained: "owned-terminal" }]
lastNativeFinished = performance.now(); response.end(JSON.stringify(rawRows)); return
}
assert.equal(request.url, "/rest/tool/ping"); pingPosts++
assert.deepEqual(body, { address: "198.51.100.2", count: "4", interface: "source-if", interval: "1s" })
pingDelay = performance.now() - lastNativeFinished; assert(pingDelay >= 2950)
response.end(JSON.stringify([{ sent: "4", received: "3", "packet-loss": "25%", "avg-rtt": "2ms" }]))
} catch { protocolErrors++; response.statusCode = 502; response.end('{"error":"Owned MCP speed HTTP protocol mismatch"}') }
}))
const restoreProbe = async () => {
await application.query("DELETE FROM public.uptime_speed_probes WHERE id=$1", [probeId])
await application.query("INSERT INTO public.uptime_speed_probes(id,src_server_id,dst_server_id,src_interface,dst_interface,protocol,direction,duration_sec,enabled) VALUES($1,$2,$3,'source-if','dest-if','udp','receive',3,true)", [probeId, ids[0], ids[1]])
}
const historyCounts = async () => (await application.query("SELECT (SELECT count(*)::int FROM public.uptime_speed_test_runs) AS speed,(SELECT count(*)::int FROM public.scheduler_runs) AS scheduler,(SELECT count(*)::int FROM public.server_probe_executions) AS diagnostic")).rows[0]
try {
for (const claim of claims) ids.push(await f.managedEndpoint(claim))
users.push(...ids.map(id => "managed-" + id))
for (const id of ids) receipts.push(await f.managedHost.register(await f.managedObservation(id), f.scope()))
assert.notEqual(receipts[0].canonicalNodeId, receipts[1].canonicalNodeId)
for (let index = 0; index < routers.length; index++) {
await new Promise<void>((yes, no) => { routers[index].once("error", no); routers[index].listen(0, "127.0.0.1", yes) })
await application.query("UPDATE public.servers SET port=$2 WHERE id=$1", [ids[index], (routers[index].address() as { port: number }).port])
}
await application.query("UPDATE public.mcp_settings SET enabled=true WHERE id=1")
await restoreProbe(); const signed = await f.createSignedSource()
// Physical driver counts include callback-based pg-pool calls. All original
// SQL/config/params/result objects and ACKs are forwarded unchanged.
PgClient.prototype.query = function(this: InstanceType<typeof PgClient>, ...args: unknown[]) {
const connection = this as unknown as { connectionParameters: { database: string; user: string } }
const text = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text ?? ""
const core = connection.connectionParameters.database === f.databaseName
if (core) measurement.controlSql++; else if (connection.connectionParameters.database === "postgres" && connection.connectionParameters.user === "mcp_test") measurement.appSql++
const family = (core ? "control:" : "application:") + sqlFamily(text); measurement.families[family] = (measurement.families[family] ?? 0) + 1
const measured = measurement, began = performance.now(); let completed = false
// Observe the real driver's completion only. No SQL text, parameters,
// result rows or credentials enter these fixed-family numeric aggregates.
// Capture the measurement object so a late ACK cannot pollute a new case.
const finish = (error?: unknown) => {
if (completed) return; completed = true
const elapsed = performance.now() - began
const value = measured.latency[family] ??= { completed: 0, errors: 0, totalMs: 0, maxMs: 0 }
value.completed++; if (error) value.errors++; value.totalMs += elapsed; value.maxMs = Math.max(value.maxMs, elapsed)
}
const callback = args.at(-1)
if (typeof callback === "function") args[args.length - 1] = function(this: unknown, error: unknown, result: unknown) {
finish(error)
if (error) failure(family, error)
return Reflect.apply(callback, this, [error, result])
}
let result: unknown
try { result = Reflect.apply(clientQuery, this, args) } catch (error) { finish(error); failure(family, error); throw error }
if (!result || typeof (result as Promise<unknown>).then !== "function") return result
return (result as Promise<unknown>).then(value => { finish(); return value }, error => { finish(error); failure(family, error); throw error })
} as typeof PgClient.prototype.query
pool.query = function(this: typeof pool, ...args: unknown[]) {
const text = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text ?? ""
const credentials = text.startsWith("/* mcp-speed-original:credentials */")
return (async () => {
if (credentials) { credentialQueries++; const hook = beforeCredentials; beforeCredentials = undefined; await hook?.() }
let result
try { result = await Reflect.apply(query, this, args) } catch (error) { failure("pool:" + sqlFamily(text), error); throw error }
if (credentials) credentialPayloads += result.rows.length
return result // Original driver result/rows/ACK, never substituted.
})()
} as typeof pool.query
ClientRequest.prototype.setTimeout = function(this: ClientRequest, ...args: Parameters<typeof setTimeoutOriginal>) {
if (this.path === "/rest/tool/bandwidth-test" || this.path === "/rest/tool/ping") timeouts.push({ path: this.path, timeout: args[0] })
return Reflect.apply(setTimeoutOriginal, this, args)
}
async function prepare(approved: boolean) {
phase = "prepare-actual-origin"
const runId = "owned-mcp-full-speed-" + randomUUID(), command = speedTestCommandSchema.parse({ runId, probeId, srcServerId: ids[0], dstServerId: ids[1], srcInterface: "source-if", dstInterface: "dest-if", protocol: "udp", direction: "receive", durationSec: 3 })
const endpointRows = (await application.query('SELECT id,host,port,username,password,use_ssl AS "useSsl",verify_ssl AS "verifySsl",enabled,routing_endpoint_epoch::text AS "routingEndpointEpoch" FROM public.servers WHERE id=ANY($1::bigint[]) ORDER BY id', [ids])).rows
const probe = (await application.query('SELECT id,src_server_id AS "srcServerId",dst_server_id AS "dstServerId",src_interface AS "srcInterface",dst_interface AS "dstInterface",protocol,direction,duration_sec AS "durationSec",enabled FROM public.uptime_speed_probes WHERE id=$1', [probeId])).rows[0]
const input = { command, expectedEndpoints: endpointRows.map(endpoint => ({ serverId: endpoint.id, proof: sign("endpoint:" + fingerprint({ generation, endpoint })) })), expectedProbe: probe } as McpSpeedBandwidthInput
const actor = { id: randomUUID(), email: "[email protected]", name: "Owned MCP speed component", apps: ["mm"], permissions: ["mm:uptime:write", "mm:mcp:approve"], issuedAt: Date.now() - 1000, expiresAt: Date.now() + 300000 }
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Owned MCP speed component", mode: approved ? "approval" : "autonomous", expiresAt: new Date(actor.expiresAt).toISOString(), permissions: ["mm:uptime:write"],
scope: { serverIds: ids, operationIds: ["uptime.speed-test"], allowGlobal: false }, ...(approved ? {} : { dangerousPolicy: "explicit-allow", autonomousDangerousOperationIds: ["uptime.speed-test"] }) }), actor)
const principal = await authenticateMcpToken(access.token)
let grantId: string | undefined
if (approved) { grantId = randomUUID(); await application.query("INSERT INTO public.mcp_grants(id,connection_id,payload) VALUES($1,$2,$3::jsonb)", [grantId, principal.connectionId, JSON.stringify({ credentialId: principal.credentialId, id: randomUUID(), startsAt: new Date(Date.now() - 1000).toISOString(), expiresAt: new Date(Date.now() + 120000).toISOString(), scope: { serverIds: ids, operationIds: ["uptime.speed-test"], allowGlobal: false } })]) }
const originalGrant = await readMcpTemporaryGrantOrigin(pool, principal.connectionId, principal.credentialId)
const expiry = Math.min(Date.now() + 120000, Date.parse(principal.credentialExpiresAt), originalGrant.expiresAt ?? Infinity), began = Date.now(), mono = performance.now()
const grant = { ...originalGrant, monotonicEnd: originalGrant.expiresAt === null ? Infinity : mono + originalGrant.expiresAt - began, admissionExpiresAt: expiry, admissionMonotonicEnd: mono + expiry - began }
const planId = randomUUID(), operationId = randomUUID(), objects = ids.map(serverId => ({ kind: "server", id: String(serverId), serverId }))
const step = { kind: "service", service: "uptime.speed-test", input }, payload = { sealed: await encryptSecret(JSON.stringify({ command })) }, evidence = { sealed: await encryptSecret(JSON.stringify({ objects, steps: [step] })) }
await application.query("INSERT INTO public.mcp_plans(id,connection_id,operation_id,operation_version,policy_version,generation,payload,evidence,state,expires_at,approved_by,approved_at) VALUES($1,$2,'uptime.speed-test',1,1,$3,$4::jsonb,$5::jsonb,'executing',$6,$7,$8)", [planId, principal.connectionId, generation, JSON.stringify(payload), JSON.stringify(evidence), new Date(expiry), approved ? actor.id : null, approved ? new Date() : null])
await application.query("INSERT INTO public.mcp_operations(id,plan_id,connection_id,idempotency_key,state) VALUES($1,$2,$3,$4,'running')", [operationId, planId, principal.connectionId, randomUUID()])
await application.query("INSERT INTO public.mcp_operation_steps(operation_id,step_index,server_id,state,intended_state) VALUES($1,0,NULL,'intent',$2::jsonb)", [operationId, JSON.stringify(redact(step))])
const row = (await application.query("SELECT * FROM public.mcp_plans WHERE id=$1", [planId])).rows[0]
const decrypted = JSON.parse(await decryptSecret(row.evidence.sealed)); assert.deepEqual(decrypted.steps[0].input, input)
assert.deepEqual(JSON.parse(await decryptSecret(row.payload.sealed)), { command })
const metadata: VerifiedMcpServiceMetadata = { operationId, planId, operationName: row.operation_id, serviceName: decrypted.steps[0].service, operationVersion: row.operation_version, policyVersion: row.policy_version,
generation: row.generation, principal, stepIndex: 0, phase: "forward", originalExpiresAt: row.expires_at.getTime(), originalTemporaryGrantProof: originalGrant.proof, originalTemporaryGrantExpiresAt: originalGrant.expiresAt,
sealedEvidenceProof: createHash("sha256").update(row.evidence.sealed).digest("hex"), sealedPayloadProof: createHash("sha256").update(row.payload.sealed).digest("hex"), serviceInput: decrypted.steps[0].input }
const context = { actorId: actor.id, connectionId: principal.connectionId, serverIds: ids, objects, approved: !!row.approved_by, serverWide: true, serviceExecution: metadata,
authorize: async () => {
authorizerChecks++; const current = await effectiveMcpConnection(principal)
assert.equal(current.owner_id, actor.id); assert.equal(current.policy.version, metadata.policyVersion)
assert(hasPermission(current.owner_permissions, "mm:uptime:write") && hasPermission(current.policy.permissions, "mm:uptime:write"))
assert(ids.every(id => current.policy.scope.serverIds.includes(id))); assert(current.policy.scope.operationIds.includes("uptime.speed-test"))
if (!approved) assert(current.policy.mode === "autonomous" && current.policy.dangerousPolicy === "explicit-allow" && current.policy.autonomousDangerousOperationIds.includes("uptime.speed-test"))
await assertOriginalMcpTemporaryGrant(pool, principal.connectionId, principal.credentialId, grant)
} }
return { input, command, context, metadata, grantId, principal }
}
const compose = (token: unknown) => {
const observer = createBandwidthPeerObservationReader({ read: (peer, current) => observe("observer-original", current, () => provider.readPeer(token, peer, current)) })
const host = createBandwidthPeerExecutionHost({ coreSource: signed.core, nodeSource: signed.node, observer, readOriginal: (original, current) => observe("host-original", current, () => provider.readOriginal(original, current)),
verifyRemote: async (original, intent, evidence, current) => {
assert.equal(original, token); assert.deepEqual(intent.actualRemotePeer, { kind: "server", serverId: ids[1] })
assert.equal(evidence.sourceReceipt.canonicalNodeId, receipts[0].canonicalNodeId); assert.equal(evidence.remoteReceipt.canonicalNodeId, receipts[1].canonicalNodeId)
assert.equal(intent.nativeBody.address, (await observe("wire-context", current, () => provider.readSpeedContext(token, current))).address)
return { proof: f.mac("SYNTHETIC-OWNED-MCP-WIRE-MAPPING", { source: receipts[0].canonicalNodeId, remote: receipts[1].canonicalNodeId, address: intent.nativeBody.address, credentialServerId: intent.credentialServerId }), expiresAt: intent.expiresAt }
} })
return { host, observer }
}
for (const next of [{ name: "human", approved: true }, { name: "autonomous-probe-edit", approved: false }, { name: "human-probe-delete", approved: true }]) {
mode = next.name; await restoreProbe(); const owned = await prepare(next.approved), before = { nativePosts, pingPosts }, began = performance.now()
beginMeasurement()
expectedBody = { address: "198.51.100.2", user: users[1], password: "owned-localhost-only", protocol: "udp", direction: "receive", duration: "3s" }
beforeResponse = next.name.includes("edit") ? async () => { await application.query("UPDATE public.uptime_speed_probes SET duration_sec=4 WHERE id=$1", [probeId]) }
: next.name.includes("delete") ? async () => { await application.query("DELETE FROM public.uptime_speed_probes WHERE id=$1", [probeId]) } : undefined
await withVerifiedConfigurationChange(owned.context, async () => {
const scope = { deadlineAt: Date.now() + 60000 }; phase = "capture"; const token = await provider.capture(owned.input, scope)
phase = "compose"; const { host, observer } = compose(token)
try {
const beforeForgery = credentialPayloads
await assert.rejects(provider.readPeerAfterCompletion(token, { outcome: "complete" }, { kind: "server", serverId: ids[0] }, scope)); assert.equal(credentialPayloads, beforeForgery)
phase = "workflow"; const result = await createBandwidthSpeedWorkflow({ originals: provider, peerHost: host }).run(token, scope)
assert.deepEqual(result.raw, rawRows); assert.equal(result.txAvgMbps, 3); assert.equal(result.rxAvgMbps, 4)
assert.equal(result.afterBtPing.rttMs, 2); assert.equal(result.afterBtPing.lossPct, 25); assert.equal(result.afterBtPing.error, null)
} finally { observer.close() }
})
assert.equal(nativePosts, before.nativePosts + 1); assert.equal(pingPosts, before.pingPosts + 1); assert(pingDelay >= 2950); assert.deepEqual(nativeBody, expectedBody)
const history = (await application.query("SELECT status,probe_id,tx_avg_mbps,rx_avg_mbps,ping_rtt_ms,ping_loss_pct FROM public.uptime_speed_test_runs WHERE id=$1", [owned.command.runId])).rows
assert.equal(history.length, 1); assert.equal(history[0].status, "done"); assert.equal(history[0].probe_id, next.name === "human" ? probeId : null); assert.equal(Number(history[0].tx_avg_mbps), 3); assert.equal(history[0].ping_rtt_ms, 2)
const identity = createBandwidthSpeedRunIdentity(owned.command.runId), attempt = (await f.owner.query("SELECT caller_kind,state,resolution FROM mmapp_control.bandwidth_attempts WHERE attempt_id=$1", [identity.attemptId])).rows
assert.equal(attempt.length, 1); assert.equal(attempt[0].caller_kind, "mcp-speed"); assert.equal(attempt[0].state, "released"); assert.equal(attempt[0].resolution, "remote_completion")
assert.equal(Number((await f.owner.query("SELECT count(*) AS n FROM mmapp_control.bandwidth_node_occupancy")).rows[0].n), 0)
metrics.push({ case: mode, approved: next.approved, elapsedMs: Math.round(performance.now() - began), nativePosts: nativePosts - before.nativePosts, pingPosts: pingPosts - before.pingPosts, historyRows: history.length,
applicationSql: measurement.appSql, controlSql: measurement.controlSql, authorizerChecks: authorizerChecks - measurement.authorizersAtStart, sqlFamilies: measurement.families, sqlLatency: latencyReport() })
checks.push(mode + ": real sealed/current MCP component + actual v2 private host completion + native HTTP/3-second pause/ping/history; probe drift only clears association")
}
const historyAfterWorkflows = await historyCounts()
assert.equal(historyAfterWorkflows.speed, 3)
mode = "exact-private-receipt"; beforeResponse = undefined; await restoreProbe(); const receiptCase = await prepare(false)
beginMeasurement()
expectedBody = { address: "198.51.100.2", user: users[1], password: "owned-localhost-only", protocol: "udp", direction: "receive", duration: "3s" }
await withVerifiedConfigurationChange(receiptCase.context, async () => {
const scope = { deadlineAt: Date.now() + 60000 }, token = await provider.capture(receiptCase.input, scope), { host, observer } = compose(token)
try {
phase = "exact-host-receipt"; const receipt = await host.execute(token, scope)
assert.deepEqual(readBandwidthPeerCompletion(receipt, token), await provider.readOriginal(token, scope))
await application.query("DELETE FROM public.uptime_speed_probes WHERE id=$1", [probeId])
await assert.rejects(provider.readOriginal(token, scope))
assert.equal((await provider.readPeerAfterCompletion(token, receipt, { kind: "server", serverId: ids[0] }, scope)).endpoint.username, users[0]); completionReads++
const before = credentialPayloads
for (const copied of [{ ...receipt }, JSON.parse(JSON.stringify(receipt))]) await assert.rejects(provider.readPeerAfterCompletion(token, copied, { kind: "server", serverId: ids[0] }, scope))
await assert.rejects(provider.readPeerAfterCompletion({ ...token }, receipt, { kind: "server", serverId: ids[0] }, scope)); assert.equal(credentialPayloads, before)
} finally { observer.close() }
})
checks.push("actual exact private native+durable completion receipt permits probe-deleted post-completion source; copying/serializing receipt or changing private original refuses")
mode = "initial-probe-drift"; await restoreProbe(); const initial = await prepare(false), initialCounts = { credentialPayloads, nativeGets, nativePosts, pingPosts }
beginMeasurement()
beforeCredentials = async () => { await application.query("UPDATE public.uptime_speed_probes SET direction='both' WHERE id=$1", [probeId]) }
await withVerifiedConfigurationChange(initial.context, async () => { await assert.rejects(provider.capture(initial.input, { deadlineAt: Date.now() + 30000 })) })
assert.deepEqual({ credentialPayloads, nativeGets, nativePosts, pingPosts }, initialCounts)
checks.push("actual probe UPDATE after initial probe SELECT but at credential command returns zero projected payload before GET/POST")
for (const fault of ["grant", "owner-permission", "sealed-step"] as const) {
mode = fault; await restoreProbe(); const owned = await prepare(true)
beginMeasurement()
await withVerifiedConfigurationChange(owned.context, async () => {
const scope = { deadlineAt: Date.now() + 30000 }, token = await provider.capture(owned.input, scope), before = { credentialPayloads, nativeGets, nativePosts, pingPosts }
if (fault === "grant") { assert(owned.grantId); await application.query("UPDATE public.mcp_grants SET revoked_at=now() WHERE id=$1", [owned.grantId]) }
if (fault === "owner-permission") await application.query("UPDATE public.mcp_connections SET owner_permissions='[]'::jsonb WHERE id=$1", [owned.principal.connectionId])
if (fault === "sealed-step") await application.query("UPDATE public.mcp_operation_steps SET intended_state='{}'::jsonb WHERE operation_id=$1 AND step_index=0", [owned.metadata.operationId])
await assert.rejects(provider.readOriginal(token, scope)); assert.deepEqual({ credentialPayloads, nativeGets, nativePosts, pingPosts }, before)
})
}
checks.push("retained genuine component revalidates actual original grant revocation, owner permission loss and current sealed-step SQL drift before further credentials/native")
assert.deepEqual(await historyCounts(), historyAfterWorkflows)
assert.equal(protocolErrors, 0); assert(timeouts.some(value => value.path === "/rest/tool/bandwidth-test" && value.timeout === 30000)); assert(timeouts.some(value => value.path === "/rest/tool/ping" && value.timeout === 20000))
return { checks, metrics, nativeGets, nativePosts, pingPosts, credentialQueries, credentialPayloadRows: credentialPayloads, authorizerChecks, exactPositiveCompletionReads: completionReads,
actualApplicationAndControlSql: true, actualSealedPayloads: true, actualMcpConnectionTokenGrantPortalAuthorizer: true, genuineVerifiedChangeComponent: true,
actualPrivateCompletionReceipt: true, actualWorkflowHistory: true, publicMcpActionRegistered: false, publicMcpRunnerAcceptance: false,
syntheticEnrollmentQuiescence: true, syntheticWireMapping: true, productionMappingVerified: false, runtimeAllCallersActivated: false, realChrCalls: 0, automaticReplay: false }
} catch (error) {
const cause = error instanceof Error && error.cause ? error.cause : error
console.error("Owned MCP speed phase:", JSON.stringify({ phase, mode, nativeGets, nativePosts, pingPosts, credentialQueries, credentialPayloads, authorizerChecks,
elapsedMs: Math.round(performance.now() - measurement.began), applicationSql: measurement.appSql, controlSql: measurement.controlSql, sqlFamilies: measurement.families, sqlLatency: latencyReport(), underlyingFailures: measurement.failures,
name: cause instanceof Error ? cause.name : "unclassified", code: cause && typeof cause === "object" && "code" in cause ? String(cause.code).slice(0, 80) : undefined,
peerPhase: cause && typeof cause === "object" && "phase" in cause && typeof cause.phase === "string" && /^[a-z-]{1,80}$/.test(cause.phase) ? cause.phase : undefined }))
throw error
} finally {
beforeCredentials = undefined; pool.query = query; PgClient.prototype.query = clientQuery; ClientRequest.prototype.setTimeout = setTimeoutOriginal
for (const router of routers) { router.closeAllConnections(); if (router.listening) await new Promise<void>(yes => router.close(() => yes())) }
application.release(true); await f.close()
}
}