diff --git a/backend/src/modules/mcp/routing-community-scoped-acceptance.ts b/backend/src/modules/mcp/routing-community-scoped-acceptance.ts index 9c22baf8..25785015 100644 --- a/backend/src/modules/mcp/routing-community-scoped-acceptance.ts +++ b/backend/src/modules/mcp/routing-community-scoped-acceptance.ts @@ -32,6 +32,7 @@ import { createRoutingNetworkNativeSession } from "./routing-network-native-sess import { requireRecentPath } from "./path-verification.js" import { registerManagementChannel } from "./management.js" import { isSchedulerJobsPaused, pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../../services/scheduler-running.js" +import { hookConfigurationAudits } from "../../test/fixtures/configuration-audit-commit.js" type BrowserRoutingTransport = { call(tool: string, input: Record): Promise> @@ -229,10 +230,10 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options: const originalQuery = pool.query.bind(pool) let afterIntent: (() => Promise) | undefined let afterRecoveryJournalRead: ((rows: Array<{ recovery_operation_id: string; configuration_proof: string }>) => Promise) | undefined + // Intent audits commit on transaction clients, so that hook wraps pool.connect rather than pool.query. + const restoreAudits = hookConfigurationAudits({ afterIntentCommit: async () => { if (afterIntent) { const hook = afterIntent; afterIntent = undefined; await hook() } } }) pool.query = (async (...args: unknown[]) => { const result = await (originalQuery as (...args: unknown[]) => Promise)(...args) - const parameters = args[1] as unknown[] | undefined - if (typeof args[0] === "string" && args[0].includes("INSERT INTO mcp_audit") && parameters?.[1] === "configuration.intent" && afterIntent) { const hook = afterIntent; afterIntent = undefined; await hook() } if (typeof args[0] === "string" && args[0].includes(" AS step_result") && afterRecoveryJournalRead) { const hook = afterRecoveryJournalRead afterRecoveryJournalRead = undefined @@ -1983,7 +1984,7 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options: throw error } finally { try { - pool.query = originalQuery + pool.query = originalQuery; restoreAudits() if (persistentProfileIds.length) await pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=ANY($1::uuid[])", [persistentProfileIds]) if (connectionId) await setConnectionStatus(connectionId, "paused", writer) if (insertedServer) { await pool.query("DELETE FROM mcp_management_channels WHERE server_id=$1", [sid]); await pool.query("DELETE FROM servers WHERE id=$1", [sid]) } diff --git a/backend/src/modules/mcp/wireguard-import-acceptance.ts b/backend/src/modules/mcp/wireguard-import-acceptance.ts index 5f40c4d5..55865132 100644 --- a/backend/src/modules/mcp/wireguard-import-acceptance.ts +++ b/backend/src/modules/mcp/wireguard-import-acceptance.ts @@ -16,6 +16,7 @@ import { encryptSecret, fingerprint } from "./security.js" import { WIREGUARD_IMPORT_CONTENT_PURPOSE } from "./wireguard-import-actions.js" import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js" import wireguardRoutes from "../../routes/wireguard.js" +import { afterConfigurationIntentCommit } from "../../test/fixtures/configuration-audit-commit.js" type Rows = Record[]> /** Explicitly invoked by the isolated SQL acceptance harness. Network traffic @@ -226,51 +227,28 @@ export async function acceptWireguardImport(actor: AuthUser) { console.log("WireGuard import MCP phases: human-only native outcomes and exact generic VERIFIED checkpoint variants checked") const individual = plan.changes.objects.filter(object => object.kind === "wireguard_peer")[1] assert.ok(individual) - const lateProtection = randomUUID(), originalQuery = pool.query.bind(pool) - let protectedAfterIntent = false - pool.query = ((...args: unknown[]) => { - const sql = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text - const params = args[1] as unknown[] | undefined - const pending = (originalQuery as (...args: unknown[]) => Promise)(...args) - if (!protectedAfterIntent && sql?.startsWith("INSERT INTO mcp_audit") && params?.[1] === "configuration.intent" && String(params[3]).includes('"path":"/interface/wireguard"')) { - protectedAfterIntent = true - return pending.then(async value => { - // Omit serverId deliberately: the logical-object closure must catch - // this exact protected import peer after the durable native intent. - await originalQuery("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [lateProtection, { kind: individual.kind, id: individual.id, protection: "deny" }, actor.id]) - return value - }) - } - return pending - }) as typeof pool.query + const lateProtection = randomUUID() + // Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query. + // Omit serverId deliberately: the logical-object closure must catch + // this exact protected import peer after the durable native intent. + const late = afterConfigurationIntentCommit(payload => payload.path === "/interface/wireguard", () => pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [lateProtection, { kind: individual.kind, id: individual.id, protection: "deny" }, actor.id])) try { assert.equal((await wait((await applyPlan(principal, plan.planId, randomUUID())).id)).state, "unknown") - assert.equal(protectedAfterIntent, true); assert.equal(commands.length, 0) - } finally { pool.query = originalQuery as typeof pool.query; await pool.query("DELETE FROM mcp_protections WHERE id=$1", [lateProtection]) } + assert.equal(late.fired(), true); assert.equal(commands.length, 0) + } finally { late.restore(); await pool.query("DELETE FROM mcp_protections WHERE id=$1", [lateProtection]) } // A native ID is device-local. A different server's *3 protection must not // block this import; a new same-server protection after durable activation // intent must stop before the first PATCH, with the disabled prefix intact. for (const transport of ["rest", "mcp"]) { reset() const outsideProtection = randomUUID(), nativeProtection = randomUUID(), query = pool.query.bind(pool) - let insertedAfterPeerIntent = false + let late: ReturnType | undefined await query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [outsideProtection, { kind: "wireguard_peer", id: "*3", serverId: 142, protection: "deny" }, actor.id]) try { const nativePlan = transport === "mcp" ? await prepare() : undefined if (nativePlan) await approvePlan(nativePlan.planId, actor, true) - pool.query = ((...args: unknown[]) => { - const sql = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text - const params = args[1] as unknown[] | undefined - const pending = (query as (...args: unknown[]) => Promise)(...args) - if (!insertedAfterPeerIntent && sql?.startsWith("INSERT INTO mcp_audit") && params?.[1] === "configuration.intent" && String(params[3]).includes('"path":"/interface/wireguard/peers/*3"')) { - insertedAfterPeerIntent = true - return pending.then(async value => { - await query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [nativeProtection, { kind: "wireguard_peer", id: "*3", serverId: 141, protection: "deny" }, actor.id]) - return value - }) - } - return pending - }) as typeof pool.query + // Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query. + late = afterConfigurationIntentCommit(payload => payload.path === "/interface/wireguard/peers/*3", () => query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2,$3)", [nativeProtection, { kind: "wireguard_peer", id: "*3", serverId: 141, protection: "deny" }, actor.id])) if (nativePlan) { const idempotency = randomUUID(), operation = await applyPlan(principal, nativePlan.planId, idempotency) assert.equal((await wait(operation.id)).state, "unknown") @@ -282,14 +260,14 @@ export async function acceptWireguardImport(actor: AuthUser) { assert.equal(response.json().automaticReplay, false) assert.notEqual((await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: restInput })).statusCode, 200) } - assert.equal(insertedAfterPeerIntent, true, transport) + assert.equal(late.fired(), true, transport) assert.equal(commands.length, 4, "Four creations, no activation or replay after late native protection") assert.ok(commands.every(command => command.startsWith("PUT "))) assert.equal(rows["/interface/wireguard"][1].disabled, "true") assert.ok(rows["/interface/wireguard/peers"].every(row => row.disabled === "true")) assert.equal(rows["/ipv6/address"][0].disabled, "true") } finally { - pool.query = query as typeof pool.query + late?.restore() await query("DELETE FROM mcp_protections WHERE id=ANY($1::uuid[])", [[outsideProtection, nativeProtection]]) } } diff --git a/backend/src/test/fixtures/configuration-audit-commit.ts b/backend/src/test/fixtures/configuration-audit-commit.ts index 37fb4dbe..e0598fa0 100644 --- a/backend/src/test/fixtures/configuration-audit-commit.ts +++ b/backend/src/test/fixtures/configuration-audit-commit.ts @@ -6,9 +6,9 @@ type Payload = Record & { object?: { kind?: unknown } } * Configuration audits commit on transaction clients from pool.connect(), not via * pool.query, so fixtures that react to them must wrap pool.connect. * afterIntentCommit runs after the COMMIT that made a configuration.intent durable; - * beforeAcknowledgement may throw to simulate a lost configuration.acknowledged write. + * beforeIntent / beforeAcknowledgement may throw to simulate an unavailable or lost audit write. */ -export function hookConfigurationAudits(hooks: { afterIntentCommit?: (payload: Payload) => Promise | unknown; beforeAcknowledgement?: (payload: Payload) => void }) { +export function hookConfigurationAudits(hooks: { afterIntentCommit?: (payload: Payload) => Promise | unknown; beforeIntent?: (payload: Payload) => void; beforeAcknowledgement?: (payload: Payload) => void }) { const connect = pool.connect pool.connect = ((...connectArgs: unknown[]) => { if (connectArgs.length) return Reflect.apply(connect, pool, connectArgs) @@ -19,6 +19,7 @@ export function hookConfigurationAudits(hooks: { afterIntentCommit?: (payload: P const values = args[1] as unknown[] | undefined const action = typeof args[0] === "string" && args[0].startsWith("INSERT INTO mcp_audit") ? values?.[1] : undefined const payload = action ? JSON.parse(String(values?.[3])) as Payload : undefined + if (action === "configuration.intent") hooks.beforeIntent?.(payload!) if (action === "configuration.acknowledged") hooks.beforeAcknowledgement?.(payload!) const result = await Reflect.apply(target.query, target, args) if (action === "configuration.intent") intent = payload