fix(test): перевести перехваты аудита WireGuard import и scoped routing на клиент

Устаревшие тесты, не дефект продукта. Как и в предыдущих исправлениях,
configuration.intent пишется через requestAccountingWrite на клиенте из
pool.connect(), поэтому перехваты pool.query в приёмках WireGuard import
(поздняя защита интерфейса/пира после намерения) и scoped route community
(afterIntent) не срабатывали. Они переведены на afterConfigurationIntentCommit
и hookConfigurationAudits; фикстур получил beforeIntent для имитации
недоступного аудита намерения. Перехват wireguard.import.checkpoint остаётся
на pool.query: этот аудит пишется через пул.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DenozordecandClaude Opus 5.5 committed 2026-11-15 22:37:53 +07:00
1 parent 84e34da4f9
commit 268640b9f1
3 files changed
+20 -40

No files matched your search

@@ -32,6 +32,7 @@ import { createRoutingNetworkNativeSession } from "./routing-network-native-sess
import { requireRecentPath } from "./path-verification.js" import { requireRecentPath } from "./path-verification.js"
import { registerManagementChannel } from "./management.js" import { registerManagementChannel } from "./management.js"
import { isSchedulerJobsPaused, pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../../services/scheduler-running.js" import { isSchedulerJobsPaused, pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../../services/scheduler-running.js"
import { hookConfigurationAudits } from "../../test/fixtures/configuration-audit-commit.js"
type BrowserRoutingTransport = { type BrowserRoutingTransport = {
call(tool: string, input: Record<string, unknown>): Promise<Record<string, unknown>> call(tool: string, input: Record<string, unknown>): Promise<Record<string, unknown>>
@@ -229,10 +230,10 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
const originalQuery = pool.query.bind(pool) const originalQuery = pool.query.bind(pool)
let afterIntent: (() => Promise<void>) | undefined let afterIntent: (() => Promise<void>) | undefined
let afterRecoveryJournalRead: ((rows: Array<{ recovery_operation_id: string; configuration_proof: string }>) => Promise<void>) | undefined let afterRecoveryJournalRead: ((rows: Array<{ recovery_operation_id: string; configuration_proof: string }>) => Promise<void>) | 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[]) => { pool.query = (async (...args: unknown[]) => {
const result = await (originalQuery as (...args: unknown[]) => Promise<unknown>)(...args) const result = await (originalQuery as (...args: unknown[]) => Promise<unknown>)(...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) { if (typeof args[0] === "string" && args[0].includes(" AS step_result") && afterRecoveryJournalRead) {
const hook = afterRecoveryJournalRead const hook = afterRecoveryJournalRead
afterRecoveryJournalRead = undefined afterRecoveryJournalRead = undefined
@@ -1983,7 +1984,7 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
throw error throw error
} finally { } finally {
try { 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 (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 (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]) } 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]) }
@@ -16,6 +16,7 @@ import { encryptSecret, fingerprint } from "./security.js"
import { WIREGUARD_IMPORT_CONTENT_PURPOSE } from "./wireguard-import-actions.js" import { WIREGUARD_IMPORT_CONTENT_PURPOSE } from "./wireguard-import-actions.js"
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js" import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
import wireguardRoutes from "../../routes/wireguard.js" import wireguardRoutes from "../../routes/wireguard.js"
import { afterConfigurationIntentCommit } from "../../test/fixtures/configuration-audit-commit.js"
type Rows = Record<string, Record<string, string>[]> type Rows = Record<string, Record<string, string>[]>
/** Explicitly invoked by the isolated SQL acceptance harness. Network traffic /** 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") 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] const individual = plan.changes.objects.filter(object => object.kind === "wireguard_peer")[1]
assert.ok(individual) assert.ok(individual)
const lateProtection = randomUUID(), originalQuery = pool.query.bind(pool) const lateProtection = randomUUID()
let protectedAfterIntent = false // Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query.
pool.query = ((...args: unknown[]) => { // Omit serverId deliberately: the logical-object closure must catch
const sql = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text // this exact protected import peer after the durable native intent.
const params = args[1] as unknown[] | undefined 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]))
const pending = (originalQuery as (...args: unknown[]) => Promise<unknown>)(...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
try { try {
assert.equal((await wait((await applyPlan(principal, plan.planId, randomUUID())).id)).state, "unknown") assert.equal((await wait((await applyPlan(principal, plan.planId, randomUUID())).id)).state, "unknown")
assert.equal(protectedAfterIntent, true); assert.equal(commands.length, 0) assert.equal(late.fired(), 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]) } } 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 // 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 // block this import; a new same-server protection after durable activation
// intent must stop before the first PATCH, with the disabled prefix intact. // intent must stop before the first PATCH, with the disabled prefix intact.
for (const transport of ["rest", "mcp"]) { for (const transport of ["rest", "mcp"]) {
reset() reset()
const outsideProtection = randomUUID(), nativeProtection = randomUUID(), query = pool.query.bind(pool) const outsideProtection = randomUUID(), nativeProtection = randomUUID(), query = pool.query.bind(pool)
let insertedAfterPeerIntent = false let late: ReturnType<typeof afterConfigurationIntentCommit> | 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]) 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 { try {
const nativePlan = transport === "mcp" ? await prepare() : undefined const nativePlan = transport === "mcp" ? await prepare() : undefined
if (nativePlan) await approvePlan(nativePlan.planId, actor, true) if (nativePlan) await approvePlan(nativePlan.planId, actor, true)
pool.query = ((...args: unknown[]) => { // Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query.
const sql = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text 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]))
const params = args[1] as unknown[] | undefined
const pending = (query as (...args: unknown[]) => Promise<unknown>)(...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
if (nativePlan) { if (nativePlan) {
const idempotency = randomUUID(), operation = await applyPlan(principal, nativePlan.planId, idempotency) const idempotency = randomUUID(), operation = await applyPlan(principal, nativePlan.planId, idempotency)
assert.equal((await wait(operation.id)).state, "unknown") 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.equal(response.json().automaticReplay, false)
assert.notEqual((await rest.inject({ method: "POST", url: "/api/wireguard/import", payload: restInput })).statusCode, 200) 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.equal(commands.length, 4, "Four creations, no activation or replay after late native protection")
assert.ok(commands.every(command => command.startsWith("PUT "))) assert.ok(commands.every(command => command.startsWith("PUT ")))
assert.equal(rows["/interface/wireguard"][1].disabled, "true") assert.equal(rows["/interface/wireguard"][1].disabled, "true")
assert.ok(rows["/interface/wireguard/peers"].every(row => row.disabled === "true")) assert.ok(rows["/interface/wireguard/peers"].every(row => row.disabled === "true"))
assert.equal(rows["/ipv6/address"][0].disabled, "true") assert.equal(rows["/ipv6/address"][0].disabled, "true")
} finally { } finally {
pool.query = query as typeof pool.query late?.restore()
await query("DELETE FROM mcp_protections WHERE id=ANY($1::uuid[])", [[outsideProtection, nativeProtection]]) await query("DELETE FROM mcp_protections WHERE id=ANY($1::uuid[])", [[outsideProtection, nativeProtection]])
} }
} }
+3 -2
View File
@@ -6,9 +6,9 @@ type Payload = Record<string, unknown> & { object?: { kind?: unknown } }
* Configuration audits commit on transaction clients from pool.connect(), not via * Configuration audits commit on transaction clients from pool.connect(), not via
* pool.query, so fixtures that react to them must wrap pool.connect. * pool.query, so fixtures that react to them must wrap pool.connect.
* afterIntentCommit runs after the COMMIT that made a configuration.intent durable; * 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> | unknown; beforeAcknowledgement?: (payload: Payload) => void }) { export function hookConfigurationAudits(hooks: { afterIntentCommit?: (payload: Payload) => Promise<unknown> | unknown; beforeIntent?: (payload: Payload) => void; beforeAcknowledgement?: (payload: Payload) => void }) {
const connect = pool.connect const connect = pool.connect
pool.connect = ((...connectArgs: unknown[]) => { pool.connect = ((...connectArgs: unknown[]) => {
if (connectArgs.length) return Reflect.apply(connect, pool, connectArgs) 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 values = args[1] as unknown[] | undefined
const action = typeof args[0] === "string" && args[0].startsWith("INSERT INTO mcp_audit") ? values?.[1] : 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 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!) if (action === "configuration.acknowledged") hooks.beforeAcknowledgement?.(payload!)
const result = await Reflect.apply(target.query, target, args) const result = await Reflect.apply(target.query, target, args)
if (action === "configuration.intent") intent = payload if (action === "configuration.intent") intent = payload