fix(test): исправить устаревшие проверки монолита MCP и добавить режим продолжения
Устаревшие тесты, не дефекты продукта: - Пауза во время списка шаблонов OSPF: план читает список шаблонов один раз (затем два print-запроса флагов, перед каждым повторная проверка доступа), поэтому второй итерации «пауза во время второго списка» не существует. Диагностический прогон подтвердил одну выборку списка; итерация 0 (пауза во время единственного списка → отказ UNAUTHORIZED) сохранена. - Отказ хранилища аудита перед нативной записью: аудит намерения пишется на транзакционном клиенте, перехват pool.query заменён hookConfigurationAudits с beforeIntent. Режим MCP_INTEGRATION_CONTINUE=1: помощник soft() оборачивает только самостоятельные приёмочные вызовы после блока OSPF (каждый восстанавливает свои фикстуры в finally), записывает ошибку и продолжает; в конце печатается список и выставляется exitCode=1. Встроенные проверки монолита и служебные вызовы (scheduler, ingest, refreshScheduler) не обёрнуты: их сбой искажает общее состояние для последующих шагов. Без переменной поведение прежнее. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
268640b9f1
commit
dfb73555a7
1 file changed
+40
-29
@@ -26,8 +26,16 @@ import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/cli
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"
|
||||
import type { AuthUser } from "../../lib/permissions.js"
|
||||
import { managedComment } from "../../managed-markers.js"
|
||||
import { hookConfigurationAudits } from "../../test/fixtures/configuration-audit-commit.js"
|
||||
import { compileManagedFilterRules } from "../../services/filter-rules-write-model.js"
|
||||
|
||||
// MCP_INTEGRATION_CONTINUE=1 records failures of self-contained acceptance helpers (each
|
||||
// restores its own fixtures in finally) and keeps going, to list every failure in one run.
|
||||
const softFailures: string[] = []
|
||||
const soft = async (name: string, check: () => Promise<unknown>) => {
|
||||
if (process.env.MCP_INTEGRATION_CONTINUE !== "1") return check()
|
||||
try { return await check() } catch (error) { softFailures.push(`${name}: ${error instanceof Error ? error.stack ?? error.message : String(error)}`) }
|
||||
}
|
||||
// One fixed authority deadline for the long integration suite; never renewed during the run.
|
||||
const fixtureAuthExpiresAt = Date.now() + 4 * 60 * 60 * 1000
|
||||
const actor: AuthUser = { id: "integration-owner", email: "test@example.invalid", name: "Test", apps: ["mm"], permissions: ["mm:settings:admin", "mm:certificates:write", "mm:network:admin", "mm:bgp:admin", "mm:servers:admin", "mm:filters:admin"], expiresAt: fixtureAuthExpiresAt }
|
||||
@@ -2622,7 +2630,9 @@ try {
|
||||
await assert.rejects(invokeMcpTool(graphPrincipal, "mm_ospf_optimizer_plan", { serverId: 1 }), (error: { code?: string; message?: string }) => error.code === "MEASUREMENT_UNKNOWN" && Boolean(error.message?.includes("use-bfd")), "Unknown BFD remains forbidden for a Full candidate")
|
||||
} finally { ospfAnalysisExtraNeighbors = [] }
|
||||
fixtureOspf["interface-template"] = structuredClone(costBaseline)
|
||||
for (const listsBeforePause of [0, 1]) {
|
||||
// The plan lists interface templates once (then two flag prints, each after an access recheck),
|
||||
// so a pause can only be committed during that single list.
|
||||
for (const listsBeforePause of [0]) {
|
||||
const readsBeforePause: number = ospfTemplateFlagReads
|
||||
ospfPauseOnTemplatesConnection = graphAccess.connection.id; ospfTemplateListsBeforePause = listsBeforePause
|
||||
try {
|
||||
@@ -2933,14 +2943,11 @@ try {
|
||||
} finally { await pool.query("DELETE FROM mcp_protections WHERE id=$1", [protectionId]) }
|
||||
const auditCount = (await pool.query("SELECT count(*)::int AS n FROM mcp_audit WHERE action='configuration.intent'")).rows[0].n
|
||||
assert.ok(auditCount > 0)
|
||||
const originalQuery = pool.query.bind(pool)
|
||||
// Storage outage must be observed before any native network request is made.
|
||||
pool.query = ((...args: unknown[]) => {
|
||||
if (typeof args[0] === "string" && args[0].startsWith("INSERT INTO mcp_audit")) return Promise.reject(new Error("test audit outage"))
|
||||
return (originalQuery as (...args: unknown[]) => unknown)(...args)
|
||||
}) as typeof pool.query
|
||||
// Intent audits commit on transaction clients, so the outage wraps pool.connect.
|
||||
const restoreAudits = hookConfigurationAudits({ beforeIntent: () => { throw new Error("test audit outage") } })
|
||||
try { await assert.rejects(nativeClient.post("/ip/settings/set", { "rp-filter": "strict" }), /audit outage/); await assert.rejects(updateServer(1, { name: "must-not-change" }), /audit outage/); assert.equal((await pool.query("SELECT name FROM servers WHERE id=1")).rows[0].name, nameBeforeGuard); assert.equal(writes, writesBeforeProtection) }
|
||||
finally { pool.query = originalQuery as typeof pool.query }
|
||||
finally { restoreAudits() }
|
||||
console.log("✓ Legacy native writes cannot bypass server protection or unavailable write-ahead audit")
|
||||
const { withConfigMutationLock } = await import("../../services/config-mutation-lock.js")
|
||||
let wake!: () => void, late!: Promise<void>, lateWrites = 0
|
||||
@@ -2966,30 +2973,30 @@ try {
|
||||
process.env.MCP_PUBLIC_URL = endpoint
|
||||
app = await buildApp({ startScheduler: false })
|
||||
await app.listen({ port: appPort, host: "127.0.0.1" })
|
||||
await (await import("../../test/users-profile-permissions.js")).verifyUsersProfilePermissions(app)
|
||||
await (await import("../../test/mcp-backup-download.js")).verifyMcpBackupDownload(actor,app)
|
||||
await (await import("../../test/mcp-database-backup.js")).verifyMcpDatabaseBackup(actor,app)
|
||||
await soft("verifyUsersProfilePermissions", async () => (await import("../../test/users-profile-permissions.js")).verifyUsersProfilePermissions(app))
|
||||
await soft("verifyMcpBackupDownload", async () => (await import("../../test/mcp-backup-download.js")).verifyMcpBackupDownload(actor,app))
|
||||
await soft("verifyMcpDatabaseBackup", async () => (await import("../../test/mcp-database-backup.js")).verifyMcpDatabaseBackup(actor,app))
|
||||
const fixtureScheduler = await import("../../services/scheduler-running.js")
|
||||
const fixtureSchedulerWasPaused = fixtureScheduler.isSchedulerJobsPaused()
|
||||
await fixtureScheduler.pauseSchedulerJobsAndWait()
|
||||
try {
|
||||
await (await import("./control-path-context-acceptance.js")).verifyMcpControlPathContext(actor)
|
||||
await (await import("./routing-community-scoped-acceptance.js")).acceptScopedRouteCommunitySwitch(actor)
|
||||
await (await import("../../test/mcp-terminal-diagnostics.js")).verifyMcpTerminalDiagnostics(actor, app)
|
||||
await (await import("../../test/mcp-events-batch.js")).verifyMcpEventsBatch(actor, app)
|
||||
await (await import("./wireguard-interface-update-acceptance.js")).acceptWireguardInterfaceUpdate(actor)
|
||||
await (await import("./wireguard-import-acceptance.js")).acceptWireguardImport(actor)
|
||||
await (await import("./wireguard-export-acceptance.js")).acceptWireguardExportMcp(actor, app)
|
||||
await (await import("./protection-scope-acceptance.js")).acceptProtectionRegistrationScope(actor)
|
||||
await soft("verifyMcpControlPathContext", async () => (await import("./control-path-context-acceptance.js")).verifyMcpControlPathContext(actor))
|
||||
await soft("acceptScopedRouteCommunitySwitch", async () => (await import("./routing-community-scoped-acceptance.js")).acceptScopedRouteCommunitySwitch(actor))
|
||||
await soft("verifyMcpTerminalDiagnostics", async () => (await import("../../test/mcp-terminal-diagnostics.js")).verifyMcpTerminalDiagnostics(actor, app))
|
||||
await soft("verifyMcpEventsBatch", async () => (await import("../../test/mcp-events-batch.js")).verifyMcpEventsBatch(actor, app))
|
||||
await soft("acceptWireguardInterfaceUpdate", async () => (await import("./wireguard-interface-update-acceptance.js")).acceptWireguardInterfaceUpdate(actor))
|
||||
await soft("acceptWireguardImport", async () => (await import("./wireguard-import-acceptance.js")).acceptWireguardImport(actor))
|
||||
await soft("acceptWireguardExportMcp", async () => (await import("./wireguard-export-acceptance.js")).acceptWireguardExportMcp(actor, app))
|
||||
await soft("acceptProtectionRegistrationScope", async () => (await import("./protection-scope-acceptance.js")).acceptProtectionRegistrationScope(actor))
|
||||
console.log("Routing controller CAS SQL:", await (await import("./routing-controller-cas-acceptance.js")).acceptRoutingControllerCas())
|
||||
await (await import("../../test/mcp-server-connection.js")).verifyMcpServerConnection(actor)
|
||||
await (await import("./ipsec-peer-delete-acceptance.js")).acceptIpsecPeerDeletion(actor)
|
||||
await (await import("./ipsec-user-delete-acceptance.js")).acceptIpsecUserDeletion(actor)
|
||||
await (await import("./ipsec-certificate-delete-acceptance.js")).acceptIpsecCertificateDeletion(actor)
|
||||
await (await import("./ipsec-peer-update-acceptance.js")).acceptIpsecPeerUpdate(actor)
|
||||
await (await import("./management-transport-acceptance.js")).acceptManagementTransport(actor)
|
||||
await (await import("../../test/mcp-flow-purge.js")).verifyMcpFlowPurge(actor)
|
||||
await (await import("./routing-community-context-compatibility-acceptance.js")).acceptRouteCommunityContextCompatibilityMcp(actor)
|
||||
await soft("verifyMcpServerConnection", async () => (await import("../../test/mcp-server-connection.js")).verifyMcpServerConnection(actor))
|
||||
await soft("acceptIpsecPeerDeletion", async () => (await import("./ipsec-peer-delete-acceptance.js")).acceptIpsecPeerDeletion(actor))
|
||||
await soft("acceptIpsecUserDeletion", async () => (await import("./ipsec-user-delete-acceptance.js")).acceptIpsecUserDeletion(actor))
|
||||
await soft("acceptIpsecCertificateDeletion", async () => (await import("./ipsec-certificate-delete-acceptance.js")).acceptIpsecCertificateDeletion(actor))
|
||||
await soft("acceptIpsecPeerUpdate", async () => (await import("./ipsec-peer-update-acceptance.js")).acceptIpsecPeerUpdate(actor))
|
||||
await soft("acceptManagementTransport", async () => (await import("./management-transport-acceptance.js")).acceptManagementTransport(actor))
|
||||
await soft("verifyMcpFlowPurge", async () => (await import("../../test/mcp-flow-purge.js")).verifyMcpFlowPurge(actor))
|
||||
await soft("acceptRouteCommunityContextCompatibilityMcp", async () => (await import("./routing-community-context-compatibility-acceptance.js")).acceptRouteCommunityContextCompatibilityMcp(actor))
|
||||
} finally { if (!fixtureSchedulerWasPaused) fixtureScheduler.resumeSchedulerJobs() }
|
||||
const client = new Client({ name: "integration", version: "1.0.0" })
|
||||
try {
|
||||
@@ -3065,7 +3072,7 @@ try {
|
||||
const requestId = new URL(authorization.headers.location!).searchParams.get("oauthRequest")!
|
||||
const { SignJWT } = await import("jose"), { env } = await import("../../config.js")
|
||||
const jwt = await new SignJWT({ sub: actor.id, apps: ["mm"], permissions: actor.permissions }).setProtectedHeader({ alg: "HS256" }).setIssuer(env.authIssuer).setExpirationTime(Math.floor(fixtureAuthExpiresAt / 1000)).sign(new TextEncoder().encode(env.jwtSecret))
|
||||
await (await import("../../test/mcp-host-files.js")).verifyMcpHostFiles(actor,app)
|
||||
await soft("verifyMcpHostFiles", async () => (await import("../../test/mcp-host-files.js")).verifyMcpHostFiles(actor,app))
|
||||
const readinessAccess = await createMcpConnection(mcpConnectionCreateSchema.parse({ ...input, name: "Actual readiness handshake", scope: { ...input.scope, operationIds: ["servers.list"] } }), actor)
|
||||
const readinessHeaders = { authorization: "Bearer " + jwt }
|
||||
const simulatorHeaders = { authorization: "Bearer " + await new SignJWT({ sub: "policy-preview-admin", apps: ["mm"], permissions: ["mm:mcp:admin"] })
|
||||
@@ -3874,8 +3881,8 @@ try {
|
||||
await invalidateMcpAccess()
|
||||
await assert.rejects(authenticateMcpToken(rotated.token))
|
||||
console.log("✓ Immediate pause and external-generation invalidation")
|
||||
await (await import("./native-conservation-acceptance.js")).acceptNativeConservation(actor)
|
||||
await (await import("./native-create-id-acceptance.js")).acceptNativeCreateId(actor)
|
||||
await soft("acceptNativeConservation", async () => (await import("./native-conservation-acceptance.js")).acceptNativeConservation(actor))
|
||||
await soft("acceptNativeCreateId", async () => (await import("./native-create-id-acceptance.js")).acceptNativeCreateId(actor))
|
||||
} finally {
|
||||
await (await import("../../services/scheduler.js")).stopSchedulerForDatabaseOperation()
|
||||
await (await import("../../services/traffic-flow-ingest.js")).stopTrafficFlowListenerForDatabaseOperation()
|
||||
@@ -3883,4 +3890,8 @@ try {
|
||||
await new Promise<void>((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
||||
await closePool()
|
||||
}
|
||||
if (softFailures.length) {
|
||||
console.error(`✗ ${softFailures.length} acceptance check(s) failed (MCP_INTEGRATION_CONTINUE=1):\n` + softFailures.map(line => " - " + line).join("\n"))
|
||||
process.exitCode = 1
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user