fix(test): перевести оставшиеся перехваты аудита на транзакционный клиент

Устаревшие тесты, не дефект продукта. Аудиты configuration.intent и
configuration.acknowledged пишутся через requestAccountingWrite на клиенте
из pool.connect(), поэтому перехваты pool.query в Legacy OSPF, журнале
событий, IPsec peer update, IPsec native write и native conservation не
срабатывали. Фикстур configuration-audit-commit получил общий примитив
hookConfigurationAudits (после COMMIT намерения / перед подтверждением);
afterConfigurationIntentCommit и loseConfigurationAcknowledgement построены
на нём. Ожидаемые итоги (unknown/partial, без записи и повтора) не менялись;
перехват afterVerified в native conservation остаётся на pool.query, так как
runtime обновляет шаги через пул.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
DenozordecandClaude Opus 5.5 committed 2026-11-15 22:10:01 +07:00
1 parent 07aaa40bff
commit 73af143a53
6 files changed
+65 -76

No files matched your search

@@ -8,6 +8,7 @@ import type { AuthUser } from "../../lib/permissions.js"
import { ipsecPeerDeletePaths } from "../../services/ipsec-peer-delete.js"
import { approvePlan, applyPlan, invokeMcpTool } from "./runtime.js"
import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js"
import { hookConfigurationAudits } from "../../test/fixtures/configuration-audit-commit.js"
/** Owned temporary PostgreSQL + loopback HTTP acceptance. The fixture models
* native ACK/defaults and explicit scalar rename projections. It is not CHR
@@ -113,20 +114,15 @@ export async function acceptIpsecNativeWrite(actor: AuthUser) {
await approvePlan(stale.planId, actor, true); catalogs[profilePath]![0]!["dh-group"] = "modp3072"
assert.equal((await wait((await applyPlan(principal, stale.planId, randomUUID())).id)).state, "rejected"); assert.equal(puts, beforeStale)
reset(); const late = await prepare("peer"); await approvePlan(late.planId, actor, true)
pool.query = ((...args: unknown[]) => {
const sql = typeof args[0] === "string" ? args[0] : (args[0] as { text?: string })?.text ?? "", params = args[1] as unknown[] | undefined
const pending = (query as (...values: unknown[]) => Promise<unknown>)(...args)
if (afterIntent && sql.startsWith("INSERT INTO mcp_audit") && params?.[1] === "configuration.intent" && String(params?.[3]).includes('"method":"PUT"')) {
const mutate = afterIntent; afterIntent = undefined
return pending.then(value => { mutate(); return value })
}
return pending
}) as typeof pool.query
// Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query.
const restoreAudits = hookConfigurationAudits({ afterIntentCommit: payload => {
if (afterIntent && payload.method === "PUT") { const mutate = afterIntent; afterIntent = undefined; mutate() }
} })
afterIntent = () => { catalogs[profilePath]![0]!["dh-group"] = "modp4096" }
try {
const before = puts, stopped = await wait((await applyPlan(principal, late.planId, randomUUID())).id)
assert.notEqual(stopped.state, "applied"); assert.notEqual(stopped.verification, "passed"); assert.equal(afterIntent, undefined); assert.equal(puts, before)
} finally { pool.query = query as typeof pool.query }
} finally { restoreAudits() }
reset()
const certOnly = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Certificates without network access", mode: "approval", expiresAt: new Date(Date.now() + 600000).toISOString(), permissions: ["mm:certificates:write"], scope: { serverIds: [serverId], operationIds: ["ros.certificate.update"], allowGlobal: false } }), actor)
@@ -12,6 +12,7 @@ import { getEnabledIpsecServerById } from "../../services/ipsec-live.js"
import { ipsecPeerDeletePaths } from "../../services/ipsec-peer-delete.js"
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "./store.js"
import { invokeMcpTool, approvePlan, applyPlan } from "./runtime.js"
import { afterConfigurationIntentCommit } from "../../test/fixtures/configuration-audit-commit.js"
/** SQL/loopback acceptance only. The fixture models the EXPECTED named-reference
* projection; it does not prove RouterOS rename behavior or forwarding. Root
@@ -98,14 +99,10 @@ export async function acceptIpsecPeerUpdate(actor:AuthUser){
reset();let historyFailed=false
pool.query=((...args:unknown[])=>{const sql=typeof args[0]==="string"?args[0]:(args[0]as{text?:string})?.text??"";if(/^insert into "config_revisions"/i.test(sql)){historyFailed=true;return Promise.reject(Error("NEVER_HISTORY_PROVIDER"))}return(originalQuery as(...args:unknown[])=>unknown)(...args)})as typeof pool.query
try{const before:number=patches;result=await apply({...request,name:"history-failure"});assert.equal(result.state,"partial");assert.equal(historyFailed,true);assert.equal(patches,before+1);await applyPlan(principal,result.plan.planId,result.key);assert.equal(patches,before+1)}finally{pool.query=originalQuery as typeof pool.query}
reset();const late=await prepare(request);await approvePlan(late.planId,actor,true);let fenced=false
pool.query=((...args:unknown[])=>{
const sql=typeof args[0]==="string"?args[0]:(args[0]as{text?:string})?.text??"",params=args[1]as unknown[]|undefined
const pending=(originalQuery as(...args:unknown[])=>Promise<unknown>)(...args)
if(!fenced&&sql.startsWith("INSERT INTO mcp_audit")&&params?.[1]==="configuration.intent"&&String(params?.[3]).includes('"method":"PATCH"')){fenced=true;return pending.then(value=>{catalogs["/ip/ipsec/identity"][0].secret="NEVER_LATE_SOURCE";return value})}
return pending
})as typeof pool.query
try{const before:number=patches;assert.equal((await wait((await applyPlan(principal,late.planId,randomUUID())).id)).state,"unknown");assert.equal(fenced,true);assert.equal(patches,before)}finally{pool.query=originalQuery as typeof pool.query}
reset();const late=await prepare(request);await approvePlan(late.planId,actor,true)
// Audits commit on transaction clients, so the drift hook wraps pool.connect rather than pool.query.
const fence=afterConfigurationIntentCommit(payload=>payload.method==="PATCH",async()=>{catalogs["/ip/ipsec/identity"][0].secret="NEVER_LATE_SOURCE"})
try{const before:number=patches;assert.equal((await wait((await applyPlan(principal,late.planId,randomUUID())).id)).state,"unknown");assert.equal(fence.fired(),true);assert.equal(patches,before)}finally{fence.restore()}
reset();const stale=await prepare(request);await approvePlan(stale.planId,actor,true);catalogs["/ip/ipsec/identity"][0].secret="NEVER_STALE";const beforeStale=patches;assert.equal((await wait((await applyPlan(principal,stale.planId,randomUUID())).id)).state,"rejected");assert.equal(patches,beforeStale)
reset();const protection=randomUUID();await originalQuery("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,$3)",[protection,JSON.stringify({kind:"ipsec_identity",id:"*i1",serverId,protection:"deny"}),actor.id])
try{await assert.rejects(prepare(request));assert.equal((await rest.inject({method:"PATCH",url:`/api/ipsec/peers/${serverId}/*p1`,payload:request})).statusCode,409);assert.equal(patches,beforeStale)}finally{await originalQuery("DELETE FROM mcp_protections WHERE id=$1",[protection])}
@@ -13,6 +13,7 @@ import { readRosSnapshot } from "./resources.js"
import { approvePlan, applyPlan, invokeMcpTool } from "./runtime.js"
import { decryptSecret, encryptSecret } from "./security.js"
import { authenticateMcpToken, createMcpConnection, setConnectionStatus } from "./store.js"
import { hookConfigurationAudits } from "../../test/fixtures/configuration-audit-commit.js"
/** Owned SQL + loopback only. Models projected native configuration, not a CHR
* forwarding test, opaque-field proof, or proof of real native side effects. */
@@ -95,12 +96,13 @@ export async function acceptNativeConservation(actor: AuthUser) {
throw Error("Conservation operation remains live; never replay")
}
// Hooks run AFTER durable intent / verified-step SQL, not at plan creation.
pool.query = (async (...args: unknown[]) => {
// Intent audits commit on transaction clients, so that hook wraps pool.connect.
const restoreAudits = hookConfigurationAudits({ afterIntentCommit: async payload => {
if (payload.serverId === serverId && afterIntent) { const hook = afterIntent; afterIntent = undefined; await hook() }
} })
pool.query =(async (...args: unknown[]) => {
const value = await (query as (...values: unknown[]) => Promise<unknown>)(...args)
const sql = args[0], params = args[1] as unknown[] | undefined
if (typeof sql === "string" && sql.startsWith("INSERT INTO mcp_audit") && params?.[1] === "configuration.intent" && String(params?.[3]).includes(`"serverId":${serverId}`) && afterIntent) {
const hook = afterIntent; afterIntent = undefined; await hook()
}
if (typeof sql === "string" && sql.startsWith("UPDATE mcp_operation_steps SET state=$3") && params?.[2] === "verified" && afterVerified) {
const hook = afterVerified; afterVerified = undefined; await hook()
}
@@ -559,7 +561,7 @@ export async function acceptNativeConservation(actor: AuthUser) {
console.log("Native multi-catalog inverse SQL/HTTP: two route PATCHes plus singleton hash policy, exact reverse prefix, RPF/raw singleton, numeric zero, false and empty-comment originals preserved")
console.log("Native conservation SQL/HTTP: C/U/D and safe inverses; assigned-ID, membership, field and order failures never VERIFIED/replayed; honest two-step prefix stops before second intent; late source/dependency/protection/policy fence zero writes; stale operation revision refused. No CHR/opaque-field/forwarding claim.")
} finally {
pool.query = query as typeof pool.query
pool.query = query as typeof pool.query; restoreAudits()
if (connectionId) await setConnectionStatus(connectionId, "paused", actor)
await query("DELETE FROM mcp_protections WHERE object_ref->>'serverId'=$1", [String(serverId)])
await query("UPDATE servers SET enabled=false WHERE id=$1", [serverId])
+32 -30
View File
@@ -1,16 +1,30 @@
import { pool } from "../../db/index.js"
import type { PoolClient } from "pg"
type ClientQuery = (args: unknown[], run: () => Promise<unknown>) => Promise<unknown>
/** Configuration audits commit on transaction clients from pool.connect(), not via pool.query. */
function proxyClientQueries(perClient: () => ClientQuery) {
type Payload = Record<string, unknown> & { 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.
*/
export function hookConfigurationAudits(hooks: { afterIntentCommit?: (payload: Payload) => Promise<unknown> | unknown; beforeAcknowledgement?: (payload: Payload) => void }) {
const connect = pool.connect
pool.connect = ((...connectArgs: unknown[]) => {
if (connectArgs.length) return Reflect.apply(connect, pool, connectArgs)
return (Reflect.apply(connect, pool, []) as Promise<PoolClient>).then(client => {
const hook = perClient()
let intent: Payload | undefined
return new Proxy(client, { get(target, key) {
if (key === "query") return (...args: unknown[]) => hook(args, () => Reflect.apply(target.query, target, args))
if (key === "query") return async (...args: unknown[]) => {
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.acknowledged") hooks.beforeAcknowledgement?.(payload!)
const result = await Reflect.apply(target.query, target, args)
if (action === "configuration.intent") intent = payload
if (args[0] === "COMMIT" && intent) { const committed = intent; intent = undefined; await hooks.afterIntentCommit?.(committed) }
return result
}
const value = Reflect.get(target, key)
return typeof value === "function" ? value.bind(target) : value
} })
@@ -18,36 +32,24 @@ function proxyClientQueries(perClient: () => ClientQuery) {
}) as typeof pool.connect
return () => { pool.connect = connect }
}
const audit = (args: unknown[], action: string) => {
const values = args[1] as unknown[] | undefined
return typeof args[0] === "string" && args[0].startsWith("INSERT INTO mcp_audit") && values?.[1] === action ? JSON.parse(String(values[3])) : undefined
}
/** Trigger fixture drift after the intent is durable and before the native call. */
export function afterConfigurationIntentCommit(kind: string | ((payload: Record<string, unknown>) => boolean), action: () => Promise<unknown>) {
const matcher = (kind: string | ((payload: Payload) => boolean)) => typeof kind === "string" ? (payload: Payload) => payload.object?.kind === kind : kind
/** Trigger fixture drift once, after the matching intent is durable and before the write. */
export function afterConfigurationIntentCommit(kind: string | ((payload: Payload) => boolean), action: () => Promise<unknown>) {
let fired = false
const matches = typeof kind === "string" ? (payload: { object?: { kind?: unknown } }) => payload.object?.kind === kind : kind
const restore = proxyClientQueries(() => {
let intent = false
return async (args, run) => {
const result = await run()
const payload = audit(args, "configuration.intent")
if (payload && matches(payload)) intent = true
if (args[0] === "COMMIT" && intent && !fired) { fired = true; await action() }
return result
}
})
const matches = matcher(kind)
const restore = hookConfigurationAudits({ afterIntentCommit: async payload => { if (!fired && matches(payload)) { fired = true; await action() } } })
return { fired: () => fired, restore }
}
/** Reject the acknowledgement audit of the first `kind` write, as a lost SQL acknowledgement. */
export function loseConfigurationAcknowledgement(kind: string) {
let writeId: string | undefined, dropped = false
const restore = proxyClientQueries(() => async (args, run) => {
const intent = audit(args, "configuration.intent")
if (!writeId && intent?.object?.kind === kind) writeId = intent.writeId
if (!dropped && writeId && audit(args, "configuration.acknowledged")?.writeId === writeId) { dropped = true; throw Error("fixture lost acknowledgement") }
return run()
/** Reject the acknowledgement audit of the first matching write, as a lost SQL acknowledgement. */
export function loseConfigurationAcknowledgement(kind: string | ((payload: Payload) => boolean)) {
let writeId: unknown, dropped = false
const matches = matcher(kind)
const restore = hookConfigurationAudits({
afterIntentCommit: payload => { if (!writeId && matches(payload)) writeId = payload.writeId },
beforeAcknowledgement: payload => { if (!dropped && writeId && payload.writeId === writeId) { dropped = true; throw Error("fixture lost acknowledgement") } },
})
return { dropped: () => dropped, restore }
}
+7 -8
View File
@@ -12,20 +12,19 @@ import { invokeMcpTool, approvePlan, applyPlan, loadPlan } from "../modules/mcp/
import { decryptSecret } from "../modules/mcp/security.js"
import { appendClientEventRows, appendEvent, appendEvents, prepareEventRows } from "../modules/events/service/events-service.js"
import { PARTITION_WRITER_ADVISORY_KEY } from "../services/partition-write-transaction.js"
import { hookConfigurationAudits } from "./fixtures/configuration-audit-commit.js"
export async function verifyMcpEventsBatch(actor: AuthUser, app: FastifyInstance) {
const owner = { ...actor, id: "events-batch-owner", permissions: [...new Set([...actor.permissions, "mm:dashboard:read"])] }
const ids = (await pool.query("SELECT id FROM servers ORDER BY id")).rows.map(row => Number(row.id))
const issue = (serverIds = ids) => createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Event journal fixture", mode: "autonomous", permissions: ["mm:dashboard:read"], scope: { serverIds, operationIds: ["events.batch.append", "operations.global.reconcile"], allowGlobal: true }, expiresAt: new Date(Date.now() + 1800000).toISOString(), limits: { callsPerMinute: 240, mutationsPerHour: 100, serversPerPlan: 1000, objectsPerPlan: 10000 } }), owner)
const issued = await issue(), principal = await authenticateMcpToken(issued.token), allIds: string[] = [], protections: string[] = []
const originalQuery = pool.query.bind(pool)
let afterIntent: (() => Promise<void>) | undefined
let loseAcknowledgement = false
pool.query = (async (...args: unknown[]) => {
const result = await (originalQuery as (...args: unknown[]) => Promise<unknown>)(...args)
if (typeof args[0] === "string" && args[0].includes("INSERT INTO mcp_audit") && (args[1] as unknown[] | undefined)?.[1] === "configuration.intent" && afterIntent) { const hook = afterIntent; afterIntent = undefined; await hook() }
if (typeof args[0] === "string" && args[0].includes("INSERT INTO mcp_audit") && (args[1] as unknown[] | undefined)?.[1] === "configuration.acknowledged" && loseAcknowledgement) { loseAcknowledgement = false; throw Error("Owned acknowledgement loss") }
return result
}) as typeof pool.query
// Audits commit on transaction clients, so hooks wrap pool.connect rather than pool.query.
const restoreAudits = hookConfigurationAudits({
afterIntentCommit: async () => { if (afterIntent) { const hook = afterIntent; afterIntent = undefined; await hook() } },
beforeAcknowledgement: () => { if (loseAcknowledgement) { loseAcknowledgement = false; throw Error("Owned acknowledgement loss") } },
})
const event = { level: "warning" as const, eventType: " fixture." + randomUUID() + " ", sourceModule: "system" as const, title: " review title ", message: " review message ", entityType: " server ", entityId: " 1 ", payload: { zero: 0, enabled: false, token: "NEVER_EVENT_PAYLOAD_TOKEN", nested: { text: "fixture" } }, createdAt: "2026-10-24T03:00:00+03:00" }
const internal = { ...event, eventType: "owned-internal-" + randomUUID() }
const prepare = async () => {
@@ -144,7 +143,7 @@ export async function verifyMcpEventsBatch(actor: AuthUser, app: FastifyInstance
assert.ok(!JSON.stringify(checkpoints).includes("NEVER_EVENT_PAYLOAD_TOKEN")); assert.ok(!JSON.stringify(checkpoints).includes("review message"))
console.log("✓ Event batch SQL+REST: full fields/trim/time/payload parity, atomic stable UUID batch, human approval/full global scope, per-event object budget, JSON byte/depth bounds, exact VERIFIED read-only global/portal reconcile, cross-connection/narrow/original-action denial, lost acknowledgement unknown, tamper/no replay and after-intent pause/protection fences; journal entries only, no notifications")
} finally {
pool.query = originalQuery; await setConnectionStatus(issued.connection.id, "paused", owner)
restoreAudits(); await setConnectionStatus(issued.connection.id, "paused", owner)
await pool.query("DELETE FROM mcp_protections WHERE id=ANY($1::uuid[])", [protections])
await pool.query("DELETE FROM events WHERE id=ANY($1::text[])", [allIds])
await pool.query("DELETE FROM events WHERE event_type=$1", [internal.eventType])
+8 -15
View File
@@ -6,6 +6,7 @@ import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { createMcpConnection, authenticateMcpToken } from "../modules/mcp/store.js"
import { approvePlan, applyPlan, invokeMcpTool } from "../modules/mcp/runtime.js"
import type { AuthUser } from "../lib/permissions.js"
import { afterConfigurationIntentCommit } from "./fixtures/configuration-audit-commit.js"
interface Fixture {get:()=>Record<string,string>[];set:(rows:Record<string,string>[])=>void;reads:()=>number;writes:()=>number;resetWrites:(value:number)=>void;fault:(value:string)=>void}
export async function acceptLegacyOspfPlans(actor:AuthUser,fixture:Fixture){
@@ -73,25 +74,17 @@ export async function acceptLegacyOspfPlans(actor:AuthUser,fixture:Fixture){
await pool.query("DELETE FROM mcp_protections WHERE id=$1",[protection])
for(const mode of ["protection","pause"]){
const plan=await prepare();await approvePlan(plan.planId,actor,true)
let fired=false
pool.query=((...args:unknown[])=>{
const sql=typeof args[0]==="string"?args[0]:(args[0]as{text?:string})?.text,params=args[1]as unknown[]|undefined
const pending=(query as(...args:unknown[])=>Promise<unknown>)(...args)
if(!fired&&sql?.startsWith("INSERT INTO mcp_audit")&&params?.[1]==="configuration.intent"&&String(params?.[3]).includes("/routing/ospf/interface-template/")){
fired=true;return pending.then(async value=>{
if(mode==="pause")await query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"paused\"'::jsonb) WHERE id=$1",[issued.connection.id])
else await query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,$3)",[protection,JSON.stringify({kind:"ospf_template",id:original[0][".id"],serverId:1,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.
const late=afterConfigurationIntentCommit(payload=>String(payload.path).includes("/routing/ospf/interface-template/"),async()=>{
if(mode==="pause")await query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"paused\"'::jsonb) WHERE id=$1",[issued.connection.id])
else await query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,$3)",[protection,JSON.stringify({kind:"ospf_template",id:original[0][".id"],serverId:1,protection:"deny"}),actor.id])
})
try{
const before=fixture.writes(),operation=await applyPlan(principal,plan.planId,randomUUID())
assert.equal((await wait(operation.id)).state,"partial");assert.equal(fired,true);assert.equal(fixture.writes(),before)
assert.equal((await wait(operation.id)).state,"partial");assert.equal(late.fired(),true);assert.equal(fixture.writes(),before)
assert.equal((await query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1",[operation.id])).rows[0].result.nativeWrites,0)
}finally{
pool.query=query as typeof pool.query
late.restore()
await query("DELETE FROM mcp_protections WHERE id=$1",[protection])
await query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"active\"'::jsonb) WHERE id=$1",[issued.connection.id])
}