fix(test): перехватывать аудит GeoIP на транзакционном клиенте
Устаревший тест, не дефект продукта. Аудиты configuration.intent и configuration.acknowledged пишутся через requestAccountingWrite на клиенте из pool.connect(), поэтому перехват pool.query в сценариях поздней отмены доступа и потерянного подтверждения никогда не срабатывал (revoked=false). Общий фикстур configuration-audit-commit получил помощник loseConfigurationAcknowledgement; тест GeoIP использует его и afterConfigurationIntentCommit. Ожидания продукта (нет повторного запроса, итог unknown при потере подтверждения) не менялись. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c70e55d5d4
commit
95b9d1cd52
2 files changed
+45
-31
No files matched your search
+37
-12
@@ -1,26 +1,51 @@
|
||||
import { pool } from "../../db/index.js"
|
||||
import type { PoolClient } from "pg"
|
||||
|
||||
/** Trigger fixture drift after the intent is durable and before the native call. */
|
||||
export function afterConfigurationIntentCommit(kind: string, action: () => Promise<unknown>) {
|
||||
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) {
|
||||
const connect = pool.connect
|
||||
let fired = false
|
||||
pool.connect = ((...connectArgs: unknown[]) => {
|
||||
if (connectArgs.length) return Reflect.apply(connect, pool, connectArgs)
|
||||
return (Reflect.apply(connect, pool, []) as Promise<PoolClient>).then(client => {
|
||||
let intent = false
|
||||
const hook = perClient()
|
||||
return new Proxy(client, { get(target, key) {
|
||||
if (key === "query") return async (...args: unknown[]) => {
|
||||
const result = await Reflect.apply(target.query, target, args)
|
||||
const sql = args[0], values = args[1] as unknown[] | undefined
|
||||
if (typeof sql === "string" && sql.startsWith("INSERT INTO mcp_audit") && values?.[1] === "configuration.intent" && JSON.parse(String(values[3])).object?.kind === kind) intent = true
|
||||
if (sql === "COMMIT" && intent && !fired) { fired = true; await action() }
|
||||
return result
|
||||
}
|
||||
if (key === "query") return (...args: unknown[]) => hook(args, () => Reflect.apply(target.query, target, args))
|
||||
const value = Reflect.get(target, key)
|
||||
return typeof value === "function" ? value.bind(target) : value
|
||||
} })
|
||||
})
|
||||
}) as typeof pool.connect
|
||||
return { fired: () => fired, restore() { pool.connect = 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, action: () => Promise<unknown>) {
|
||||
let fired = false
|
||||
const restore = proxyClientQueries(() => {
|
||||
let intent = false
|
||||
return async (args, run) => {
|
||||
const result = await run()
|
||||
if (audit(args, "configuration.intent")?.object?.kind === kind) intent = true
|
||||
if (args[0] === "COMMIT" && intent && !fired) { fired = true; await action() }
|
||||
return result
|
||||
}
|
||||
})
|
||||
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()
|
||||
})
|
||||
return { dropped: () => dropped, restore }
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { setGeoipFetchForTests, setGeoipValidateForTests, resetGeoipUpdateForTes
|
||||
import { resetGeoipForTests, GEOIP_COUNTRY_FILE, GEOIP_ASN_FILE } from "../services/traffic-flow-geoip.js"
|
||||
import { updateGeoipManually } from "../services/geoip-manual-update.js"
|
||||
import geoipRoutes from "../routes/geoip.js"
|
||||
import { afterConfigurationIntentCommit, loseConfigurationAcknowledgement } from "./fixtures/configuration-audit-commit.js"
|
||||
|
||||
/** Isolated real HTTP/file/SQL acceptance. No real mirror or RouterOS traffic. */
|
||||
export async function verifyMcpGeoipUpdate(actor:AuthUser){
|
||||
@@ -78,27 +79,15 @@ export async function verifyMcpGeoipUpdate(actor:AuthUser){
|
||||
await pool.query("UPDATE geoip_settings SET etags_json=$1::jsonb,country_build_at=$2 WHERE id=1",[JSON.stringify(beforeDrift.etags_json),beforeDrift.country_build_at])
|
||||
}
|
||||
mode="normal"
|
||||
const late=await prepare();await approvePlan(late.planId,owner,true);let revoked=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 work=(originalQuery as(...args:unknown[])=>Promise<unknown>)(...args)
|
||||
if(!revoked&&sql?.startsWith("INSERT INTO mcp_audit")&¶ms?.[1]==="configuration.intent"&&String(params?.[3]).includes('"kind":"geoip-update"')){revoked=true;return work.then(async value=>{await setConnectionStatus(issued.connection.id,"paused",owner);return value})}
|
||||
return work
|
||||
})as typeof pool.query
|
||||
const late=await prepare();await approvePlan(late.planId,owner,true)
|
||||
// Audits commit on transaction clients, so hooks wrap pool.connect rather than pool.query.
|
||||
const revoke=afterConfigurationIntentCommit("geoip-update",()=>setConnectionStatus(issued.connection.id,"paused",owner))
|
||||
const beforeLate=calls
|
||||
try{await wait((await applyPlan(principal,late.planId,randomUUID())).id);assert.equal(revoked,true);assert.equal(calls,beforeLate)}finally{pool.query=originalQuery as typeof pool.query;await setConnectionStatus(issued.connection.id,"active",owner)}
|
||||
const unknown=await prepare();await approvePlan(unknown.planId,owner,true);let dropped=false,targetWriteId:string|undefined
|
||||
pool.query=((...args:unknown[])=>{
|
||||
const sql=typeof args[0]==="string"?args[0]:(args[0]as{text?:string})?.text,params=args[1]as unknown[]|undefined
|
||||
if(sql?.startsWith("INSERT INTO mcp_audit")){
|
||||
const payload=JSON.parse(String(params?.[3]??"{}"))
|
||||
if(params?.[1]==="configuration.intent"&&payload.object?.kind==="geoip-update")targetWriteId=payload.writeId
|
||||
if(!dropped&&targetWriteId&¶ms?.[1]==="configuration.acknowledged"&&payload.writeId===targetWriteId){dropped=true;return Promise.reject(Error("fixture lost acknowledgement"))}
|
||||
}
|
||||
return (originalQuery as(...args:unknown[])=>Promise<unknown>)(...args)
|
||||
})as typeof pool.query
|
||||
try{await wait((await applyPlan(principal,late.planId,randomUUID())).id);assert.equal(revoke.fired(),true);assert.equal(calls,beforeLate)}finally{revoke.restore();await setConnectionStatus(issued.connection.id,"active",owner)}
|
||||
const unknown=await prepare();await approvePlan(unknown.planId,owner,true)
|
||||
const lost=loseConfigurationAcknowledgement("geoip-update")
|
||||
const key=randomUUID();let operationId=""
|
||||
try{const op=await applyPlan(principal,unknown.planId,key);operationId=op.id;assert.equal((await wait(op.id)).state,"unknown");assert.equal(dropped,true)}finally{pool.query=originalQuery as typeof pool.query}
|
||||
try{const op=await applyPlan(principal,unknown.planId,key);operationId=op.id;assert.equal((await wait(op.id)).state,"unknown");assert.equal(lost.dropped(),true)}finally{lost.restore()}
|
||||
const beforeReplay=calls;await applyPlan(principal,unknown.planId,key);assert.equal(calls,beforeReplay)
|
||||
const sealed=JSON.parse(await decryptSecret((await loadPlan(unknown.planId)).evidence.sealed)),service=findMcpService("geoip.update")!
|
||||
assert.deepEqual(await service.reconcile!(sealed.steps[0].input,async()=>{}),{matchesDesiredState:false,matchesOriginalState:false});assert.equal(calls,beforeReplay)
|
||||
|
||||
Reference in new issue
Block a user