fix(mcp): обновить снимок приёмки маршрутизации и базы данных
This commit is contained in:
1 parent
bf3d50e1ff
commit
6a286a1f66
79 files changed
+10015
-109
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
|
||||
import type { RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||
import { nativeBgpRows, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
||||
import { stableBgpPolicyRow } from "../../services/bgp-filter-binding-model.js"
|
||||
@@ -56,7 +57,7 @@ export async function readControlPathContext(profile: RouteAiProfile, candidateI
|
||||
return matching[0]
|
||||
}
|
||||
const sourceId = profile.serverId, table = unique(await get(sourceId, "/routing/table"), profile.probeVrf)
|
||||
if (![true, "true", "yes"].includes(table.fib as string | boolean) || [true, "true", "yes"].includes(table.disabled as string | boolean) || [true, "true", "yes"].includes(table.invalid as string | boolean)) throw new McpError("STATE_UNAVAILABLE", "FIB probe VRF контрольного пути не подтверждён", 409)
|
||||
if (!isConfirmedRoutingFibTable(table)) throw new McpError("STATE_UNAVAILABLE", "FIB probe VRF контрольного пути не подтверждён", 409)
|
||||
const vrfs = await get(sourceId, "/ip/vrf"), effectiveVrfs: NativeBgpRow[] = []
|
||||
await enabled(sourceId, "/ip/vrf", unique(vrfs, profile.probeVrf))
|
||||
for (const row of vrfs) effectiveVrfs.push([true, "true", "yes"].includes(row.disabled as string | boolean) ? row : await enabled(sourceId, "/ip/vrf", row))
|
||||
|
||||
@@ -31,6 +31,15 @@ const verifyData = process.env.MMAPP_OWN_TERMINAL_DATA_EQUIVALENCE === "true"
|
||||
let dataExpectation: Awaited<ReturnType<typeof import("./database-restore-data-equivalence.sql-helper.js")["prepareOwnedRestoreDataExpectation"]>> | undefined
|
||||
const originalConnect = pool.connect
|
||||
let migrationCaptures = 0
|
||||
async function waitForDatabaseRetirement() {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
try {
|
||||
await Promise.race([sharedDatabaseGate.whenOpen(), new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(Error("Terminal restore did not retire its database admission")), 10000)
|
||||
})])
|
||||
} finally { clearTimeout(timer) }
|
||||
}
|
||||
|
||||
try {
|
||||
// Every owned restore profile archives inert domain collectors, not only the
|
||||
// data-equivalence profile. Otherwise restart can launch unrelated downloads
|
||||
@@ -138,6 +147,10 @@ try {
|
||||
await assert.rejects(assertPortalClaimsCurrent(revokedOwner))
|
||||
await assert.rejects(authenticateMcpToken(issued.token))
|
||||
await assert.rejects(readRestoreReceipt(operation.id, { ...actor, permissions: ["mm:mcp:read"] }))
|
||||
// The applied receipt is durable before the terminal callback releases its
|
||||
// last SQL lease/exclusive admission. Await that existing owner, rather than
|
||||
// racing its cleanup with the stale-callback/no-replay assertion below.
|
||||
await waitForDatabaseRetirement()
|
||||
// A stale callback or process replay cannot invoke pg_restore a second time.
|
||||
await pool.query("UPDATE mcp_restore_acceptance_marker SET value='after-receipt'")
|
||||
await executeMcpDatabaseRestore(operation.id, principal)
|
||||
@@ -165,6 +178,7 @@ try {
|
||||
await delay(100)
|
||||
}
|
||||
assert.equal(receipt.state, "blocked", JSON.stringify(receipt))
|
||||
await waitForDatabaseRetirement()
|
||||
assert.equal(await accessGeneration(), generationBeforeCorruption)
|
||||
assert.equal((await pool.query("SELECT value FROM mcp_restore_acceptance_marker")).rows[0].value, "after-receipt")
|
||||
console.log("✓ Tampered archive is blocked before data replacement")
|
||||
|
||||
@@ -5,7 +5,7 @@ import { z } from "zod"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { hasPermission, type AuthUser } from "../../lib/permissions.js"
|
||||
import { validateSystemDatabaseRestoreArchive } from "../../services/system-database-restore-execution.js"
|
||||
import { restoreSystemDatabaseBackup, assertSystemDatabaseRestoreTools } from "../../services/system-database-backup.js"
|
||||
import { restoreSystemDatabaseBackup, assertSystemDatabaseRestoreTools, withSystemDatabaseRestoreAdmission } from "../../services/system-database-backup.js"
|
||||
import { withVerifiedConfigurationChange } from "../../services/config-mutation-policy.js"
|
||||
import { accessGeneration, decryptBinary, encryptBinary, decryptSecret, McpError, mcpStateDirectory } from "./security.js"
|
||||
import { audit, validatePrincipal, type McpPrincipal } from "./store.js"
|
||||
@@ -14,6 +14,7 @@ import type { add } from "./actions.js"
|
||||
import type { ChangeEvidence } from "./action-types.js"
|
||||
import { withApplicationMutationLock } from "../../services/config-mutation-lock.js"
|
||||
import {assertOriginalMcpTemporaryGrant,type OriginalServiceGrant} from "./temporary-grant-origin.js"
|
||||
import {reconcileRestoreReceiptAudit,inspectRestoreReceiptAudit} from "../../services/database-restore-audit.js"
|
||||
|
||||
export const MAX_RESTORE_ARCHIVE_BYTES = 64 * 1024 * 1024
|
||||
const metadataSchema = z.object({ id: z.string().uuid(), ownerId: z.string().min(1), sha256: z.string().regex(/^[a-f0-9]{64}$/), sizeBytes: z.number().int().positive().max(MAX_RESTORE_ARCHIVE_BYTES), generation: z.string(), expiresAt: z.string().datetime(), createdAt: z.string().datetime() }).strict()
|
||||
@@ -76,6 +77,10 @@ export async function readRestoreReceipt(id: string, actor: AuthUser) {
|
||||
try { return JSON.parse(await readFile(filename(id, ".receipt.json"), "utf8")) as Record<string, unknown> }
|
||||
catch { throw new McpError("NOT_FOUND", "Внешняя квитанция восстановления не найдена", 404) }
|
||||
}
|
||||
export async function readRestoreReceiptAuditStatus(id:string,actor:AuthUser){
|
||||
await readRestoreReceipt(id,actor)
|
||||
return inspectRestoreReceiptAudit(pool,mcpStateDirectory(),id)
|
||||
}
|
||||
export function registerDatabaseRestore(register: typeof add) {
|
||||
register("database.restore", "mm_database_restore_plan", "Восстановить БД из загруженного человеком архива", "settings", "mm:settings:admin", "write", "global", z.object({ archiveRef: z.string().uuid(), expectedSha256: z.string().regex(/^[a-f0-9]{64}$/) }).strict(), {
|
||||
prepare: async (input, context) => {
|
||||
@@ -91,15 +96,17 @@ export function registerDatabaseRestore(register: typeof add) {
|
||||
}
|
||||
/** This terminal operation must never hold a database-request admission while asking for an exclusive restore. */
|
||||
export async function executeMcpDatabaseRestore(operationId: string, principal: McpPrincipal,originalGrant?:OriginalServiceGrant) {
|
||||
const lease = await pool.connect()
|
||||
let locked = false, unsafe = false
|
||||
try {
|
||||
locked = (await lease.query<{ locked: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS locked", ["mcp-operation:" + operationId])).rows[0].locked
|
||||
if (locked) await executeRestore(operationId, principal,originalGrant)
|
||||
} finally {
|
||||
if (locked) try { await lease.query("SELECT pg_advisory_unlock(hashtextextended($1,0))", ["mcp-operation:" + operationId]) } catch { unsafe = true }
|
||||
lease.release(unsafe)
|
||||
}
|
||||
return withSystemDatabaseRestoreAdmission(async () => {
|
||||
const lease = await pool.connect()
|
||||
let locked = false, unsafe = false
|
||||
try {
|
||||
locked = (await lease.query<{ locked: boolean }>("SELECT pg_try_advisory_lock(hashtextextended($1,0)) AS locked", ["mcp-operation:" + operationId])).rows[0].locked
|
||||
if (locked) await executeRestore(operationId, principal,originalGrant)
|
||||
} finally {
|
||||
if (locked) try { await lease.query("SELECT pg_advisory_unlock(hashtextextended($1,0))", ["mcp-operation:" + operationId]) } catch { unsafe = true }
|
||||
lease.release(unsafe)
|
||||
}
|
||||
})
|
||||
}
|
||||
async function executeRestore(operationId: string, principal: McpPrincipal,originalGrant?:OriginalServiceGrant) {
|
||||
const { loadPlan } = await import("./runtime.js")
|
||||
@@ -110,7 +117,7 @@ async function executeRestore(operationId: string, principal: McpPrincipal,origi
|
||||
let receipt: Record<string, unknown> = { operationId, archiveRef: payload.archiveRef, state: "running", startedAt: new Date().toISOString(), automaticRetry: false }
|
||||
try { await durableWrite(filename(operationId, ".receipt.json"), JSON.stringify(receipt), true) }
|
||||
catch (error) { if (error instanceof Error && "code" in error && error.code === "EEXIST") return; throw error }
|
||||
let attempted = false, stage = "authority"
|
||||
let attempted = false, stage = "authority", restoreActorId:string|undefined
|
||||
const assertAuthority = async () => {
|
||||
await assertOriginalMcpTemporaryGrant(pool,principal.connectionId,principal.credentialId,originalGrant)
|
||||
const connection = await validatePrincipal(principal)
|
||||
@@ -124,6 +131,7 @@ async function executeRestore(operationId: string, principal: McpPrincipal,origi
|
||||
}
|
||||
try {
|
||||
const { connection, ids } = await assertAuthority(), source = await archive(payload.archiveRef, connection.owner_id)
|
||||
restoreActorId=connection.owner_id
|
||||
stage = "archive-read"
|
||||
if (source.sha256 !== payload.expectedSha256) throw new McpError("STATE_CONFLICT", "Архив подменён", 409)
|
||||
const buffer = await decryptBinary(await readFile(filename(source.id, ".archive.bin")))
|
||||
@@ -139,7 +147,6 @@ async function executeRestore(operationId: string, principal: McpPrincipal,origi
|
||||
receipt = { ...receipt, state: "applied", finishedAt: new Date().toISOString(), accessRevoked: true, warnings: Object.keys(outcome).filter(key => key.endsWith("Error") && outcome[key as keyof typeof outcome]) }
|
||||
stage = "receipt-publish"
|
||||
await durableWrite(filename(operationId, ".receipt.json"), JSON.stringify(receipt))
|
||||
await audit(pool, connection.owner_id, "database.restore.receipt", null, receipt).catch(() => {})
|
||||
} catch (error) {
|
||||
// The isolated destructive acceptance runner can print bounded diagnostics
|
||||
// without archive SQL, server credentials, or arbitrary error text.
|
||||
@@ -154,4 +161,9 @@ async function executeRestore(operationId: string, principal: McpPrincipal,origi
|
||||
await durableWrite(filename(operationId, ".receipt.json"), JSON.stringify(receipt))
|
||||
if (!attempted) await pool.query("UPDATE mcp_operations SET state='rejected',error_code=$2,finished_at=now() WHERE id=$1", [operationId, receipt.errorCode]).catch(() => {})
|
||||
}
|
||||
// Audit failure is a separate pending/unconfirmed import AFTER durable
|
||||
// applied receipt publication. It must never relabel confirmed restore.
|
||||
if(receipt.state==="applied"){
|
||||
try{await reconcileRestoreReceiptAudit(pool,mcpStateDirectory(),operationId,restoreActorId)}catch{/* Startup reconciles the existing external receipt; never replay restore. */}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { performance } from "node:perf_hooks"
|
||||
import type { QueryConfig, PoolClient } from "pg"
|
||||
import { mcpTemporaryGrantSchema, type McpObjectRef } from "@mmapp/contracts/mcp"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { sharedDatabaseGate } from "../../services/shared-database-gate.js"
|
||||
import { assertNoConfigurationLockContext } from "../../services/config-mutation-lock.js"
|
||||
import { assertNoOperationConfigurationLockContext } from "../../services/operation-config-lock-lease.js"
|
||||
import { validatePrincipal, audit, type McpPrincipal, type StoredOperation } from "./store.js"
|
||||
@@ -200,7 +201,10 @@ async function interrupt(entry: Admission) {
|
||||
const stopped = new Promise<never>((_yes, no) => { timeout = setTimeout(() => { retired = true; client?.release(true); client = undefined; no(Error("Operation root cleanup deadline")) }, 2500) })
|
||||
const work = async () => {
|
||||
const owned = await connect
|
||||
const query = (text: string, values: unknown[] = []) => owned.query({ text, values, query_timeout: Math.max(1, Math.min(1000, deadline - Date.now())) } as QueryConfig)
|
||||
const query = (text: string, values: unknown[] = []) => {
|
||||
if (retired || Date.now() >= deadline || !sharedDatabaseGate.hasActiveAdmission()) throw Error("Late cleanup SQL")
|
||||
return owned.query({ text, values, query_timeout: Math.max(1, Math.min(1000, deadline - Date.now())) } as QueryConfig)
|
||||
}
|
||||
if ((await query("BEGIN")).command !== "BEGIN") throw Error("No cleanup BEGIN ACK")
|
||||
const result = await query(`UPDATE public.mcp_operations SET state='unknown',verification='inconclusive',error_code='PROCESS_INTERRUPTED',
|
||||
result=jsonb_build_object('needsReview',true,'automaticRetry',false),finished_at=now() WHERE id=$1 AND plan_id=$2 AND connection_id=$3
|
||||
@@ -217,11 +221,21 @@ async function interrupt(entry: Admission) {
|
||||
try { await Promise.race([work(), stopped]) } catch { console.error("MCP operation root cleanup deferred", { operationId: entry.operationId, retryAllowed: false }) }
|
||||
finally { retired = true; clearTimeout(timeout); if (client) { client.release(!safe); client = undefined } }
|
||||
}
|
||||
/** Cleanup SQL owns a live request/exclusive admission. Waiting for repair is
|
||||
* detached from runner slots; only admission is retried, never native work. */
|
||||
async function interruptWithinDatabaseAdmission(entry: Admission): Promise<void> {
|
||||
if (sharedDatabaseGate.hasActiveAdmission()) return sharedDatabaseGate.withinAdmission(() => interrupt(entry))
|
||||
if (!sharedDatabaseGate.isPaused()) return sharedDatabaseGate.request(() => interrupt(entry))
|
||||
void (async () => {
|
||||
while (sharedDatabaseGate.isPaused()) await sharedDatabaseGate.whenOpen()
|
||||
await sharedDatabaseGate.request(() => interrupt(entry))
|
||||
})().catch(() => console.error("MCP operation root cleanup deferred", { operationId: entry.operationId, retryAllowed: false }))
|
||||
}
|
||||
/** Aborted admission/queue ownership only. A serialized/foreign cap is inert. */
|
||||
export async function retireMcpOperationAdmission(admission: unknown): Promise<void> {
|
||||
const entry = admission && typeof admission === "object" ? admissions.get(admission) : undefined
|
||||
if (!entry) return
|
||||
admissions.delete(admission as object); await interrupt(entry)
|
||||
admissions.delete(admission as object); await interruptWithinDatabaseAdmission(entry)
|
||||
}
|
||||
/** Called exactly by the ordinary runtime before its first pool checkout/lock.
|
||||
* The callback is fixed runner code; callers supply no metadata/authorizer. */
|
||||
@@ -270,7 +284,7 @@ export async function withMcpOperationExecutionOrigin(admission: unknown, work:
|
||||
await roots.run(entry, work)
|
||||
} finally {
|
||||
if (entry) { entry.active = false; clearTimeout(entry.timer); entry.controller.abort() }
|
||||
if (interruptOwn) await interrupt(admitted)
|
||||
if (interruptOwn) await interruptWithinDatabaseAdmission(admitted)
|
||||
}
|
||||
}
|
||||
export async function captureMcpOperationExecutionOrigin(): Promise<McpOperationExecutionOrigin> {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isConfirmedRoutingFibTable } from "../../services/routing-table-fib.js"
|
||||
import { prepareOriginalEffectSelection } from "./routing-original-effects.js"
|
||||
import type { RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { nativeBgpRows, bgpTemplateReferences, type NativeBgpRow } from "../../services/bgp-export-model.js"
|
||||
@@ -96,7 +98,7 @@ async function readContext(profile: RouteAiProfile, options: RouteContextOptions
|
||||
}
|
||||
const sourceId = profile.serverId, tables = await get(sourceId, "/routing/table"), vrfs = await get(sourceId, "/ip/vrf")
|
||||
const table = unique(tables, profile.table)
|
||||
if (![true, "true", "yes"].includes(table.fib as string | boolean) || [true, "true", "yes"].includes(table.disabled as string | boolean) || [true, "true", "yes"].includes(table.invalid as string | boolean)) throw new McpError("STATE_UNAVAILABLE", "FIB таблицы назначения не подтверждён", 409)
|
||||
if (!isConfirmedRoutingFibTable(table)) throw new McpError("STATE_UNAVAILABLE", "FIB таблицы назначения не подтверждён", 409)
|
||||
await enabled(sourceId, "/ip/vrf", unique(vrfs, profile.probeVrf))
|
||||
// Keep ordered VRF membership (first matching row wins), never equate an
|
||||
// arbitrary policy table with the diagnostic VRF's same-name table.
|
||||
@@ -140,7 +142,7 @@ async function readContext(profile: RouteAiProfile, options: RouteContextOptions
|
||||
for (const property of ["vrf", "routing-table"]) if (!values[property] && instance) values[property] = bgpFilterName(await post(sourceId, "/routing/bgp/instance/get", { ".id": instance[".id"], "value-name": property }))
|
||||
if (!values.vrf || !values["routing-table"] || !values.afi || values["input.filter"] === null) throw new McpError("STATE_UNAVAILABLE", "Не подтверждены effective BGP table/VRF/AFI/input binding", 409)
|
||||
const boundTable = unique(tables, values["routing-table"])
|
||||
if (![true, "true", "yes"].includes(boundTable.fib as string | boolean) || [true, "true", "yes"].includes(boundTable.disabled as string | boolean) || [true, "true", "yes"].includes(boundTable.invalid as string | boolean)) throw new McpError("STATE_UNAVAILABLE", "FIB BGP таблицы не подтверждён", 409)
|
||||
if (!isConfirmedRoutingFibTable(boundTable)) throw new McpError("STATE_UNAVAILABLE", "FIB BGP таблицы не подтверждён", 409)
|
||||
await enabled(sourceId, "/ip/vrf", unique(vrfs, values.vrf))
|
||||
bindings.push({ connectionId: connection[".id"], instance: instance ? String(instance.name) : null, vrf: values.vrf, table: values["routing-table"]!, afi: values.afi, inputChain: values["input.filter"]!, outputChain: values["output.filter-chain"] ?? "" })
|
||||
}
|
||||
@@ -177,7 +179,7 @@ async function readContext(profile: RouteAiProfile, options: RouteContextOptions
|
||||
let gateway: ReturnType<typeof routeGatewayContext>
|
||||
try { gateway = routeGatewayContext(candidate.gateway) } catch { throw new McpError("STATE_UNAVAILABLE", "Gateway кандидата не подтверждён", 409) }
|
||||
const resolver = unique(tables, gateway.resolverTable)
|
||||
if (![true, "true", "yes"].includes(resolver.fib as string | boolean) || [true, "true", "yes"].includes(resolver.disabled as string | boolean) || [true, "true", "yes"].includes(resolver.invalid as string | boolean)) throw new McpError("STATE_UNAVAILABLE", "FIB resolver таблицы не подтверждён", 409)
|
||||
if (!isConfirmedRoutingFibTable(resolver)) throw new McpError("STATE_UNAVAILABLE", "FIB resolver таблицы не подтверждён", 409)
|
||||
if (unavailableIds.includes(candidate.jumpHostId) || unavailableIds.includes(candidate.exitNodeId)) throw new McpError("DEVICE_UNAVAILABLE", "Источник кандидата отсутствует или отключён", 409)
|
||||
} catch (error) { unavailableCandidate(candidate.id, error) }
|
||||
}
|
||||
@@ -250,6 +252,14 @@ async function readContext(profile: RouteAiProfile, options: RouteContextOptions
|
||||
nativeRuleId: selected && current ? filters.find(row => row.chain === selected.inputChain)![".id"] : null, ownedCompilerRecognized: !!current,
|
||||
sharedConnectionIds, bindings, disabledConnectionIds: disabledBindings.map(binding => binding.connectionId), externalReferences, executionAvailable: reason === null, executionReason: reason, scopedExecutionAvailable: scopedReason === null, scopedExecutionReason: scopedReason, targetRuleProof, dependencyProof, sourceProofs: sources.expected }
|
||||
return { before, clients, fence, probeEndpoints, ownedTarget,
|
||||
captureOriginalEffectSelection: async (candidateId: string) => {
|
||||
try {
|
||||
const routes = await get(sourceId, "/routing/route"), sessions = await get(sourceId, "/routing/bgp/session")
|
||||
await fence()
|
||||
return prepareOriginalEffectSelection(profile, candidateId, selected, { routes, connections, sessions,
|
||||
candidate: candidateRows.get(candidateId), probe: probeEndpoints.get(candidateId) })
|
||||
} catch { await fence(); return { status: "unknown" as const, reason: "prepared-effect-catalogue-unavailable" } }
|
||||
},
|
||||
signEvidence: (value: unknown) => sign(pathProofTag("community") + fingerprint({ dependencyProof, targetRuleProof, value })),
|
||||
verifyEvidence: (value: unknown, proof: unknown) => typeof proof === "string" && constantEqual(sign(pathProofTag("community") + fingerprint({ dependencyProof, targetRuleProof, value })), proof),
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { createRoutingReservationStore } from "./routing-reservation-store.js"
|
||||
import { observeCommittedScopedCheckpoint } from "../../test/committed-scoped-checkpoint-observer.js"
|
||||
import { prepareRoutingControllerBaseline } from "./routing-controller-baseline.js"
|
||||
import { prepareRoutingControllerBaseline, advanceRoutingControllerBaseline } from "./routing-controller-baseline.js"
|
||||
import { loadScopedConfigurationPacket, loadScopedNetworkCheckpoint } from "./routing-community-scoped-checkpoint.js"
|
||||
import { assertScopedCommunityRequest } from "./routing-community-scoped-request.js"
|
||||
import { originalEffectReportSchema, originalEffectSelectionSchema } from "./routing-original-effects.js"
|
||||
import { tickRoutingProfiles } from "./routing-profiles.js"
|
||||
import { saveControllerProfileCas } from "./routing-controller-fence.js"
|
||||
import { withApplicationMutationLock, withConfigMutationLock } from "../../services/config-mutation-lock.js"
|
||||
import { performance } from "node:perf_hooks"
|
||||
@@ -31,7 +35,7 @@ import { registerManagementChannel } from "./management.js"
|
||||
import { isSchedulerJobsPaused, pauseSchedulerJobsAndWait, resumeSchedulerJobs } from "../../services/scheduler-running.js"
|
||||
|
||||
/** Disposable SQL + loopback HTTP only. Does not access or configure CHR. */
|
||||
export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options: { originalCredentialRevocationOnly?: boolean; forwardRoundsOnly?: boolean; manualInverseChargeOnly?: boolean; manualInverseChargeCase?: "positive" | "quota" | "concurrent" | "unknown" | "revoked" | "nonpersistent" } = {}) {
|
||||
export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options: { originalEffectsOnly?: boolean; originalCredentialRevocationOnly?: boolean; forwardRoundsOnly?: boolean; manualInverseChargeOnly?: boolean; manualInverseChargeCase?: "positive" | "quota" | "concurrent" | "unknown" | "revoked" | "nonpersistent" | "mixed-forward" } = {}) {
|
||||
const sid = 131, writer: AuthUser = { ...actor, permissions: [...new Set([...actor.permissions, "mm:filters:write"])] }
|
||||
const initial = compileManagedFilterRules([{ community: "65000:10", gateway: "192.0.2.1", outIface: "", action: "route", description: "" }, { community: "65000:20", gateway: "192.0.2.5", outIface: "", action: "route", description: "" }])
|
||||
const filters = ["a", "b"].map(key => ({ ".id": "*f" + key, chain: "custom-" + key, rule: initial, disabled: "false", comment: managedComment("NEVER_SCOPED_COMMENT_" + key), opaque: "NEVER_SCOPED_OPAQUE" }))
|
||||
@@ -42,6 +46,22 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
|
||||
let forwardRoundBulk = 0, afterRoundLogRead: (() => Promise<void>) | undefined
|
||||
let primaryDown = false, primaryControlRequests = 0, pendingInversePost = false, inversePostChecks = 0
|
||||
const observedVrfs = new Set<string>()
|
||||
// Only this separately selected SQL/localhost phase changes its wire data.
|
||||
// These are declared synthetic RouterOS responses, never actual CHR facts.
|
||||
let originalEffectCase: "transition" | "no-op" | "ambiguous" = "transition"
|
||||
const originalEffectWire: Array<{ method: string; path: string; afterPatch: boolean }> = []
|
||||
const originalEffectChanged = () => originalEffectCase === "no-op" || filters[0].rule !== initial
|
||||
const effectRoutes = () => {
|
||||
const changed = originalEffectChanged()
|
||||
const row = { ".id": "*effect1", afi: "ip4", "routing-table": "tenant-a", "dst-address": "203.0.113.0/24",
|
||||
bgp: "true", connect: "false", static: "false", active: "true", contribution: "active", ecmp: "false",
|
||||
disabled: "false", filtered: "false", unreachable: "false", blackhole: "false", "bgp.communities": "65000:10",
|
||||
gateway: changed ? "192.0.2.9" : "192.0.2.1", "immediate-gw": (changed ? "203.0.113.9" : "203.0.113.1") + "%wan-a" }
|
||||
return originalEffectCase === "ambiguous" ? [row, { ...row, ".id": "*effect2" }] : [row]
|
||||
}
|
||||
const effectConnection = { ".id": "*ca", name: "peer-a", instance: "default", vrf: "main", "routing-table": "tenant-a", afi: "ip",
|
||||
"input.filter": "custom-a", "output.filter-chain": "", templates: "", disabled: "false", "use-bfd": "false",
|
||||
"local.address": "198.18.0.1", "remote.address": "198.18.0.2", "remote.as": "65001" }
|
||||
const collections = (path: string): Record<string, unknown>[] => ({
|
||||
"/system/resource": [{ version: "7.20.1" }],
|
||||
...Object.fromEntries(["/routing/route", "/routing/bgp/session", "/routing/bfd/session", "/log"].map(resource => [resource,
|
||||
@@ -54,12 +74,25 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
|
||||
"/ip/route": [1, 9].map(value => ({ ".id": "*r" + value, "dst-address": "192.0.2." + value + "/32", "routing-table": "main", disabled: "false", comment: managedComment("recursive"), opaque: "NEVER_SCOPED_ROUTE" })),
|
||||
"/interface": ["wan-a", "wan-b", "hop", "target"].map((name, index) => ({ ".id": "*if" + index, name, disabled: "false", running: "true" })),
|
||||
"/ip/address": ["wan-a", "wan-b", "hop", "target"].map((name, index) => ({ ".id": "*ad" + index, interface: name, address: "198.51.100." + (index + 1) + "/32", disabled: "false", invalid: "false" })),
|
||||
...(options.originalEffectsOnly ? {
|
||||
"/routing/table": ["main", "tenant-a", "tenant-b", "probe-a", "probe-b"].map((name, index) => ({ ".id": "*t" + index, name, fib: "", disabled: "false", invalid: "false" })),
|
||||
"/routing/route": effectRoutes(), "/routing/bgp/connection": [effectConnection],
|
||||
"/routing/bgp/session": [{ ...effectConnection, ".id": "*sa", "local.afi": "ip", "remote.afi": "ip", established: "true" }],
|
||||
"/routing/bfd/session": [], "/log": [{ ".id": "*l1", topics: "bgp,route,info", message: "Declared synthetic localhost effect observation; interval coverage unknown" }],
|
||||
"/ip/route": [1, 9].map(value => ({ ".id": "*r" + value, "dst-address": "192.0.2." + value + "/32", "routing-table": "main", disabled: "false",
|
||||
"immediate-gw": "203.0.113." + value + "%wan-a", comment: managedComment("recursive"), opaque: "NEVER_SCOPED_ROUTE" })),
|
||||
} : {}),
|
||||
} as Record<string, Record<string, unknown>[]>)[path] ?? []
|
||||
let requestFailure: { error: unknown } | undefined
|
||||
const handler: RequestListener = async (req, res) => {
|
||||
requests++; res.setHeader("content-type", "application/json")
|
||||
if (options.originalEffectsOnly) {
|
||||
assert.equal(req.socket.localAddress, "127.0.0.1")
|
||||
assert.equal(req.headers.authorization, "Basic " + Buffer.from("admin:NEVER_SCOPED_PASSWORD").toString("base64"))
|
||||
}
|
||||
let raw = ""; for await (const chunk of req) raw += chunk
|
||||
const args = raw ? JSON.parse(raw) : {}, path = decodeURIComponent((req.url ?? "").replace(/^\/rest/, ""))
|
||||
if (options.originalEffectsOnly) originalEffectWire.push({ method: req.method ?? "", path, afterPatch: filters[0].rule !== initial })
|
||||
if (req.socket.localAddress === "127.0.0.1") {
|
||||
if (/^\/(routing|tool)\//.test(path) || path === "/system/license") primaryControlRequests++
|
||||
if (primaryDown) { req.socket.destroy(); return }
|
||||
@@ -203,6 +236,111 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
|
||||
return { id, version: 1 }
|
||||
}
|
||||
const disablePersistent = (id: string) => pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=$1", [id])
|
||||
if (options.originalEffectsOnly) {
|
||||
const cases: Array<Record<string, unknown>> = []
|
||||
for (const effectCase of ["transition", "no-op", "ambiguous"] as const) {
|
||||
reset(); await refresh(); originalEffectCase = effectCase
|
||||
const config = profile("a")
|
||||
for (const candidate of config.candidates) candidate.controlProbe!.sourceAddress = "198.51.100.1"
|
||||
assert.equal(config.autoRecovery, false)
|
||||
// The baseline and persistent authority are issued by the SAME actual
|
||||
// fixed readers/CAS used by existing tests, not hand-written proofs.
|
||||
const persistent = await persistentFixture(config)
|
||||
try {
|
||||
const { plan, input } = await prepare("a", persistent, config)
|
||||
const sealedSelection = originalEffectSelectionSchema.parse(input.originalEffectSelection)
|
||||
assert.equal(sealedSelection.status, effectCase === "ambiguous" ? "unknown" : "prepared")
|
||||
const storedPlan = await loadPlan(plan.planId)
|
||||
assert.equal(storedPlan.approved_by, writer.id)
|
||||
assert(!JSON.stringify(await publicPlan(storedPlan)).includes("originalEffectSelection"))
|
||||
const beforeWrites = writes, wireStart = originalEffectWire.length
|
||||
const operation = await execute(plan.planId)
|
||||
assert.equal(operation.state, "applied", "Optional effect unknown must preserve genuine manual configuration/probe acceptance")
|
||||
assert.equal(writes - beforeWrites, 1)
|
||||
const rows: Array<{ created_at: Date; state: string; operation_id: string; operation_version: number; step_state: string;
|
||||
result: { configurationVerified: boolean; controlProbeVerified: boolean; originalEffects: unknown } }> = (await pool.query(`SELECT o.created_at,o.state,p.operation_id,p.operation_version,s.state AS step_state,s.result
|
||||
FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id JOIN mcp_operation_steps s ON s.operation_id=o.id
|
||||
WHERE o.id=$1 AND o.connection_id=$2 AND o.plan_id=$3 AND s.step_index=0`, [operation.id, connectionId, plan.planId])).rows
|
||||
assert.equal(rows.length, 1); assert.equal(rows[0].operation_id, "routing.community.switch")
|
||||
assert.equal(rows[0].state, "applied"); assert.equal(rows[0].step_state, "verified")
|
||||
assert.equal(rows[0].result.configurationVerified, true); assert.equal(rows[0].result.controlProbeVerified, true)
|
||||
const report = originalEffectReportSchema.parse(rows[0].result.originalEffects)
|
||||
const requestSeal = await assertScopedCommunityRequest(input)
|
||||
const configuration = await loadScopedConfigurationPacket(input, requestSeal, { operationId: operation.id, stepIndex: 0 })
|
||||
assert(configuration); assert.equal(configuration.packet.operationId, operation.id)
|
||||
assert.equal(configuration.packet.revision, 2); assert.equal(configuration.packet.phase, "CONFIG_APPLIED")
|
||||
const network = await loadScopedNetworkCheckpoint(input, requestSeal)
|
||||
assert(network); assert.equal(network.status, "passed"); assert.deepEqual(network.originalEffects, report)
|
||||
const runningWire = originalEffectWire.slice(wireStart)
|
||||
const ribBefore = runningWire.filter(row => row.method === "GET" && row.path === "/routing/route" && !row.afterPatch).length
|
||||
const ribAfter = runningWire.filter(row => row.method === "GET" && row.path === "/routing/route" && row.afterPatch).length
|
||||
console.log("Owned original effect diagnostic:", JSON.stringify({ case: effectCase, state: operation.state,
|
||||
status: report.status, reason: report.reason, rounds: report.rounds.length, budget: report.budget ?? null,
|
||||
ribBefore, ribAfter, runtimeNativeRequests: runningWire.length, lastNativePaths: runningWire.slice(-8).map(row => row.path) }))
|
||||
assert.equal(ribBefore, effectCase === "ambiguous" ? 0 : 1)
|
||||
assert.equal(ribAfter, effectCase === "ambiguous" ? 0 : 2)
|
||||
assert.equal(report.status, effectCase === "transition" ? "observed-expected" : "unknown")
|
||||
assert.equal(report.switchEffectObserved, effectCase === "transition")
|
||||
assert.equal(report.logCoverage, "unknown"); assert.equal(report.routeOriginVerified, false)
|
||||
assert.equal(report.forwardingVerified, false); assert.equal(report.semanticProof, false); assert.equal(report.autoRecoveryAllowed, false)
|
||||
if (sealedSelection.status === "prepared") {
|
||||
assert.equal(report.selectionIdentity, fingerprint(sealedSelection)); assert.equal(report.rounds.length, 2)
|
||||
assert(report.budget && report.budget.calls > 18 && report.budget.calls <= 256)
|
||||
assert(report.budget.bytes > 0 && report.budget.bytes <= 8 * 1048576)
|
||||
assert(report.budget.rows > 0 && report.budget.rows <= 10000)
|
||||
assert(report.budget.deadline <= rows[0].created_at.getTime() + 105000, "Original120s horizon is narrowed by15s publication reserve")
|
||||
assert(report.rounds.every(round => Date.parse(round.observedAt) < report.budget!.deadline && round.controlProbe === "passed" && round.bgp === "observed-expected" && round.bfd === "not-configured"))
|
||||
assert.deepEqual(report.transition?.changedPrefixes, effectCase === "transition" ? ["203.0.113.0/24"] : [])
|
||||
assert.equal(report.transitionAttribution, "unproven")
|
||||
}
|
||||
const row = (await pool.query("SELECT state,grant_expires_at FROM mcp_routing_profiles WHERE id=$1 AND version=1", [persistent.id])).rows[0]
|
||||
assert(row?.state.baseline)
|
||||
const advance = () => advanceRoutingControllerBaseline(row.state.baseline, persistent.id, 1, config, row.grant_expires_at.toISOString(),
|
||||
{ principal, connection: principalConnection }, plan.planId, operation.id)
|
||||
const principalConnection = await effectiveMcpConnection(principal), beforeAdvanceReads = requests
|
||||
if (effectCase === "transition") {
|
||||
const advanced = await advance(); assert.equal(advanced.packet.candidateId, "b")
|
||||
assert.equal(advanced.packet.transition?.operationId, operation.id); assert.equal(advanced.packet.transition?.checkpointProof, configuration.checkpointProof)
|
||||
} else {
|
||||
await assert.rejects(advance, (error: unknown) => error instanceof McpError && error.code === "STATE_CONFLICT")
|
||||
assert.equal(requests, beforeAdvanceReads, "Unknown/no-transition effect gate refuses before another native context read")
|
||||
}
|
||||
// Check actual HMAC loading, not only a caller-visible result object.
|
||||
if (effectCase === "transition") {
|
||||
const audit: Array<{ id: string; payload: Record<string, unknown> }> = (await pool.query("SELECT id,payload FROM mcp_audit WHERE connection_id=$1 AND action='routing.scoped.network-check' AND payload->>'receiptId'=$2", [connectionId, input.receiptId])).rows
|
||||
assert.equal(audit.length, 1)
|
||||
try {
|
||||
await pool.query("UPDATE mcp_audit SET payload=jsonb_set(payload,'{originalEffects,switchEffectObserved}','false'::jsonb) WHERE id=$1", [audit[0].id])
|
||||
assert.equal(await loadScopedNetworkCheckpoint(input, requestSeal), null, "Modified effect vector cannot reuse its original network HMAC")
|
||||
} finally { await pool.query("UPDATE mcp_audit SET payload=$2::jsonb WHERE id=$1", [audit[0].id, JSON.stringify(audit[0].payload)]) }
|
||||
assert.deepEqual((await loadScopedNetworkCheckpoint(input, requestSeal))?.originalEffects, report)
|
||||
}
|
||||
const repeatReads = requests
|
||||
const repeated = await applyPlan(principal, plan.planId, randomUUID())
|
||||
assert.equal(repeated.id, operation.id, "Completed plan returns its original operation without replay")
|
||||
assert.equal(repeated.state, "applied")
|
||||
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM mcp_operations WHERE plan_id=$1", [plan.planId])).rows[0].n), 1)
|
||||
assert.equal(writes - beforeWrites, 1); assert.equal(requests, repeatReads, "Completed approved plan cannot repeat native work")
|
||||
// Preserve the existing scoped-controller activation guard. A real
|
||||
// tick pauses HERE before effect dispatch; never call this an
|
||||
// effect-triggered scheduler pause or enable that unsupported lane.
|
||||
await tickRoutingProfiles()
|
||||
const paused = (await pool.query("SELECT enabled,state FROM mcp_routing_profiles WHERE id=$1", [persistent.id])).rows[0]
|
||||
assert.equal(paused.enabled, false); assert.equal(typeof paused.state.pausedReason, "string")
|
||||
assert.deepEqual(paused.state.baseline, row.state.baseline)
|
||||
cases.push({ case: effectCase, manualState: operation.state, configurationCheckpoint: true, actualPrivateExecutionOrigin: true,
|
||||
effectStatus: report.status, observedFibTransition: report.switchEffectObserved, nativeRibBefore: ribBefore, nativeRibAfter: ribAfter,
|
||||
sharedBudget: report.budget ?? null, effectBaselineAdvanceAccepted: effectCase === "transition", effectGateNativeReads: effectCase === "transition" ? "fresh-native-checked" : 0,
|
||||
actualTickPausedByExistingScopedGuard: true, tickEffectPauseAccepted: false, publicManualRevision2EffectOwnerAccepted: false })
|
||||
} finally { await disablePersistent(persistent.id) }
|
||||
}
|
||||
assert.deepEqual((await pool.query("SELECT * FROM filter_rules WHERE server_id=$1 ORDER BY id", [sid])).rows, dbBefore)
|
||||
const result = { accepted: true, cases, persistentAuthorityCases: 0, realMcpDispatcher: true, realSql: true, routerOsTransport: "declared-synthetic-localhost-http",
|
||||
genuineApprovedRunningOrigin: true, actualConfigurationCheckpoint: true, signedEffectTamperRejected: true,
|
||||
originalAutoRecoveryEnabled: false, fullRoutingAccepted: false, scopedControllerEnabled: false, nativeChrAccepted: false, forwardingVerified: false }
|
||||
console.log("Original effect SQL/runtime component:", JSON.stringify(result))
|
||||
return result
|
||||
}
|
||||
const assertOriginalCredentialRevocation = async () => {
|
||||
console.log(JSON.stringify({stage:'original-credential-revocation:init'}))
|
||||
reset(); await refresh()
|
||||
@@ -260,6 +398,7 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
|
||||
const id = randomUUID(), current = await effectiveMcpConnection(principal), config = profile("a")
|
||||
assert.equal(config.autoRecovery, false)
|
||||
if (chargeCase === "quota") config.maxSwitchesPerHour = 1
|
||||
if (chargeCase === "mixed-forward") config.maxSwitchesPerHour = 2
|
||||
const expiry = new Date(Math.min(Date.now() + 600000, current.owner_valid_until.getTime(), Date.parse(principal.credentialExpiresAt), Date.parse(current.policy.expiresAt)))
|
||||
await withApplicationMutationLock(() => withConfigMutationLock([sid], async () => {
|
||||
const baseline = await prepareRoutingControllerBaseline(id, 1, config, expiry.toISOString(), { principal, connection: current })
|
||||
@@ -292,6 +431,10 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
|
||||
}
|
||||
console.log(JSON.stringify({stage:"manual-inverse:forward-prepare",chargeCase}))
|
||||
const { plan, input } = await prepare("a", persistent ? { id, version: 1 } : undefined, config)
|
||||
// Prepare the competing forward while the ORIGINAL native baseline is
|
||||
// current. Admission must charge it even if execution later refuses the
|
||||
// changed network state. No invented request/authority or reserved lane.
|
||||
const competingForward = chargeCase === "mixed-forward" ? await prepare("a", { id, version: 1 }, config) : undefined
|
||||
// Existing known partial configuration path: genuine committed CONFIG_APPLIED,
|
||||
// then failed control probe, then genuine manual inverse positive to A.
|
||||
mode = "post-failed"
|
||||
@@ -348,6 +491,54 @@ export async function acceptScopedRouteCommunitySwitch(actor: AuthUser, options:
|
||||
await assert.rejects(applyPlan(principal, recovery.planId, randomUUID()))
|
||||
assert.deepEqual(await snapshot(), afterForward, "No approval means no debit/charge/native write")
|
||||
await approvePlan(recovery.planId, writer, true)
|
||||
if (chargeCase === "mixed-forward") {
|
||||
assert(competingForward)
|
||||
const attempts = [
|
||||
{ lane: "forward", planId: competingForward.plan.planId, key: randomUUID(), cost: 2 },
|
||||
{ lane: "manual-inverse", planId: recovery.planId, key: randomUUID(), cost: 1 },
|
||||
] as const
|
||||
const initialPlans = await Promise.all(attempts.map(attempt => loadPlan(attempt.planId)))
|
||||
assert(initialPlans.every(value => value.state === "approved"))
|
||||
const admitted = await Promise.allSettled(attempts.map(attempt => applyPlan(principal, attempt.planId, attempt.key)))
|
||||
const winners = admitted.flatMap((value, index) => value.status === "fulfilled" ? [index] : [])
|
||||
assert.equal(winners.length, 1, "Two writer lanes must compete for the same last profile slot")
|
||||
const winnerIndex = winners[0], loserIndex = 1 - winnerIndex
|
||||
const winner = admitted[winnerIndex], loser = admitted[loserIndex]
|
||||
assert(winner.status === "fulfilled" && loser.status === "rejected")
|
||||
assert(loser.reason instanceof McpError && loser.reason.code === "STATE_CONFLICT", "The losing lane must fail profile admission")
|
||||
assert.equal(fingerprint(await loadPlan(attempts[loserIndex].planId)), fingerprint(initialPlans[loserIndex]), "Losing plan is completely unchanged")
|
||||
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_operations WHERE plan_id=$1", [attempts[loserIndex].planId])).rows[0].n), 0)
|
||||
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_forward_charges WHERE source_plan_id=$1", [attempts[loserIndex].planId])).rows[0].n), 0)
|
||||
assert.equal(Number((await pool.query("SELECT count(*)::int AS n FROM mcp_routing_manual_inverse_charges WHERE recovery_plan_id=$1", [attempts[loserIndex].planId])).rows[0].n), 0)
|
||||
const deadline = Date.now() + 140000
|
||||
let terminalState = "pending"
|
||||
while (["pending", "running"].includes(terminalState) && Date.now() < deadline) {
|
||||
terminalState = (await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [winner.value.id])).rows[0].state
|
||||
if (["pending", "running"].includes(terminalState)) await delay(20)
|
||||
}
|
||||
assert(!["pending", "running"].includes(terminalState), "Winner must retire before fixture cleanup")
|
||||
if (requestFailure) throw requestFailure.error
|
||||
snapshotStage = "mixed-writer-terminal"
|
||||
const afterMixed = await snapshot()
|
||||
assert.equal(afterMixed.total, 2)
|
||||
assert.equal(afterMixed.forward, winnerIndex === 0 ? 2 : 1)
|
||||
assert.equal(afterMixed.manualInverse, winnerIndex === 1 ? 1 : 0)
|
||||
assert.equal(afterMixed.reserved, 0); assert.equal(afterMixed.legacy, 0)
|
||||
assert.equal(afterMixed.generic, afterForward.generic + attempts[winnerIndex].cost, "Losing writer cannot debit generic quota")
|
||||
if (winnerIndex === 1) {
|
||||
const charges = (await pool.query("SELECT source_operation_id,source_step_index,recovery_operation_id FROM mcp_routing_manual_inverse_charges WHERE recovery_operation_id=$1", [winner.value.id])).rows
|
||||
assert.equal(charges.length, 1); assert.equal(charges[0].source_operation_id, source.id)
|
||||
assert.equal(charges[0].source_step_index, 0); assert.equal(charges[0].recovery_operation_id, winner.value.id)
|
||||
assert.equal(terminalState, "applied"); assert.equal(afterMixed.writes, 2)
|
||||
}
|
||||
const beforeReplay = fingerprint(await snapshot())
|
||||
assert.equal((await applyPlan(principal, attempts[winnerIndex].planId, attempts[winnerIndex].key)).id, winner.value.id)
|
||||
await delay(30)
|
||||
assert.equal(fingerprint(await snapshot()), beforeReplay, "Same-key observation cannot recharge or replay either lane")
|
||||
return { accepted: true, mixedWriterAdmission: true, winnerLane: attempts[winnerIndex].lane, before, afterForward, afterMixed,
|
||||
exactlyOneAdmission: true, losingPlanOperationChargeAndGenericRollback: true, sameKeyReplayUnchanged: true,
|
||||
realSql: true, allWriterLedgerComplete: false, reservedDispatchEnabled: false, autoRecoveryEnabled: false }
|
||||
}
|
||||
console.log(JSON.stringify({ stage: "manual-inverse:human-recovery-apply" }))
|
||||
if (chargeCase === "quota" || chargeCase === "revoked") {
|
||||
if (chargeCase === "revoked") await pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=$1", [id])
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { originalEffectReportSchema, type OriginalEffectReport } from "./routing-original-effects.js"
|
||||
import { z } from "zod"
|
||||
import type { PoolClient } from "pg"
|
||||
import { pool } from "../../db/index.js"
|
||||
@@ -19,7 +20,7 @@ const checkpointSchema = z.union([manualCheckpointSchema, manualCheckpointSchema
|
||||
export type ScopedConfigurationPacket = z.infer<typeof checkpointSchema>
|
||||
type Checkpoint = ScopedConfigurationPacket
|
||||
const networkSchema = z.object({ receiptId: z.string().uuid(), requestSeal: proof, configurationCheckpointProof: proof,
|
||||
check: z.object({ id: z.string().uuid(), candidateId: z.string(), status: z.enum(["passed", "failed"]), observedAt: z.string().datetime() }).strict(), networkSeal: proof }).strict()
|
||||
check: z.object({ id: z.string().uuid(), candidateId: z.string(), status: z.enum(["passed", "failed"]), observedAt: z.string().datetime() }).strict(), originalEffects: originalEffectReportSchema.optional(), networkSeal: proof }).strict()
|
||||
const intended = (input: Record<string, unknown>) => JSON.stringify(redact({ kind: "service", service: "routing.community.scoped", input }))
|
||||
const connection = (input: Record<string, unknown>) => z.object({ connectionId: z.string().uuid() }).parse(input.principal).connectionId
|
||||
const seal = (value: Checkpoint) => privateSecretFingerprint(fingerprint(value), `route-ai-scoped-config-checkpoint-v${value.revision}`)
|
||||
@@ -72,12 +73,13 @@ export async function loadScopedConfigurationCheckpoint(input: Record<string, un
|
||||
return value ? { checkpointProof: value.checkpointProof, observedAt: value.observedAt } : null
|
||||
}
|
||||
|
||||
export async function saveScopedNetworkCheckpoint(input: Record<string, unknown>, requestSeal: string, check: { id: string; candidateId: string; status: "passed" | "failed"; observedAt: string }) {
|
||||
export async function saveScopedNetworkCheckpoint(input: Record<string, unknown>, requestSeal: string, check: { id: string; candidateId: string; status: "passed" | "failed"; observedAt: string }, originalEffects?: OriginalEffectReport) {
|
||||
await assertPersistentScopedProfileAuthority(input)
|
||||
const configuration = await loadScopedConfigurationCheckpoint(input, requestSeal)
|
||||
if (!configuration) throw new McpError("STATE_CONFLICT", "Нет подтверждённого CONFIG_APPLIED", 409)
|
||||
const packet = { receiptId: input.receiptId, requestSeal, configurationCheckpointProof: configuration.checkpointProof,
|
||||
check: { id: check.id, candidateId: check.candidateId, status: check.status, observedAt: check.observedAt } }
|
||||
check: { id: check.id, candidateId: check.candidateId, status: check.status, observedAt: check.observedAt },
|
||||
...(originalEffects === undefined ? {} : { originalEffects: originalEffectReportSchema.parse(originalEffects) }) }
|
||||
const networkSeal = await privateSecretFingerprint(fingerprint(packet), "route-ai-scoped-network-checkpoint-v1")
|
||||
await assertPersistentScopedProfileAuthority(input)
|
||||
await audit(pool, String(input.ownerId), "routing.scoped.network-check", connection(input), { ...packet, networkSeal })
|
||||
@@ -92,5 +94,5 @@ export async function loadScopedNetworkCheckpoint(input: Record<string, unknown>
|
||||
if (!parsed.success) return null
|
||||
const { networkSeal, ...packet } = parsed.data
|
||||
if (packet.configurationCheckpointProof !== configuration.checkpointProof || packet.check.candidateId !== input.candidateId || Date.parse(packet.check.observedAt) < Date.parse(configuration.observedAt) || Date.parse(packet.check.observedAt) > Date.now() || networkSeal !== await privateSecretFingerprint(fingerprint(packet), "route-ai-scoped-network-checkpoint-v1")) return null
|
||||
return { status: packet.check.status, networkSeal }
|
||||
return { status: packet.check.status, networkSeal, ...(packet.originalEffects === undefined ? {} : { originalEffects: packet.originalEffects }) }
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
import { createRoutingNetworkSessionForCurrentExecution } from "./routing-network-execution-session.js"
|
||||
import { readRoutingNetworkScopedCommunityContext } from "./routing-network-scoped-context.js"
|
||||
import { resolveRoutingNetworkForwardRoundConfigurationContext, closeRoutingNetworkForwardRoundConfigurationContext } from "./routing-network-configuration-bridge.js"
|
||||
import { originalEffectSelectionSchema, unknownOriginalEffects, originalEffectBaselineMatches, inspectOriginalEffectRounds, type OriginalEffectReport } from "./routing-original-effects.js"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { z } from "zod"
|
||||
import { routeAiProfileSchema } from "@mmapp/contracts/mcp-routing"
|
||||
@@ -25,6 +29,11 @@ import { createRoutingReservationStore } from "./routing-reservation-store.js"
|
||||
|
||||
const principalSchema = z.object({ connectionId: z.string().uuid(), credentialId: z.string().uuid(), credentialExpiresAt: z.string() }).strict()
|
||||
const fail = (message: string, code = "STATE_CONFLICT") => new McpError(code, message, 409)
|
||||
const effectReadFailure = (stage: "original-effect-rounds-unavailable" | "effect-publication-revalidation-unavailable", error: unknown) => {
|
||||
const code = error instanceof McpError && ["READ_CANCELLED", "PLAN_EXPIRED", "LIMIT_EXCEEDED", "STATE_CONFLICT", "RESET_REQUIRED", "STATE_UNAVAILABLE"].includes(error.code)
|
||||
? error.code : "STATE_UNAVAILABLE"
|
||||
return unknownOriginalEffects(stage + ":" + code)
|
||||
}
|
||||
export const scopedProfileIds = (profile: z.infer<typeof routeAiProfileSchema>) => [...new Set([profile.serverId, ...profile.candidates.flatMap(candidate => [candidate.jumpHostId, candidate.exitNodeId])])].sort((a, b) => a - b)
|
||||
const publicRule = (rule: { community: string; gateway: string; outIface: string }) => ({ community: rule.community, action: "route", gateway: rule.gateway, gatewayTunnelId: rule.outIface })
|
||||
type ObservationPhase = "admission" | "configuration"
|
||||
@@ -80,7 +89,7 @@ async function receipt(input: Record<string, unknown>, action: string) {
|
||||
await assertPersistentScopedProfileAuthority(input)
|
||||
await audit(pool, String(input.ownerId), action, principalSchema.parse(input.principal).connectionId, { receiptId: input.receiptId, requestSeal, revision: input.proofRevision })
|
||||
}
|
||||
const matches = (input: Record<string, unknown>, context: Awaited<ReturnType<typeof readRouteCommunityContext>>) => scopedConfigurationMatches({ dependencyProof: input.dependencyProof, originalTargetProof: input.originalTargetProof, desiredTargetProof: input.desiredTargetProof, candidateId: input.candidateId }, context.before)
|
||||
const matches = (input: Record<string, unknown>, context: { before: Parameters<typeof scopedConfigurationMatches>[1] }) => scopedConfigurationMatches({ dependencyProof: input.dependencyProof, originalTargetProof: input.originalTargetProof, desiredTargetProof: input.desiredTargetProof, candidateId: input.candidateId }, context.before)
|
||||
async function original(input: Record<string, unknown>, verified: boolean) {
|
||||
await sealedInput(input)
|
||||
const value = await observe(input, undefined, verified)
|
||||
@@ -128,7 +137,8 @@ export async function prepareScopedCommunitySwitch(input: Record<string, unknown
|
||||
try { managementBindingCiphertext = await encryptSecret(JSON.stringify(await prepareManagementTransportBinding(profile.serverId, { authorize: value.authorize, signal: action.signal, deadline: Math.min(Date.now() + 120000, Date.parse(action.principal.credentialExpiresAt), action.connection.owner_valid_until.getTime(), Date.parse(action.connection.policy.expiresAt)) }))) }
|
||||
catch (error) { if (!(error instanceof McpError) || error.code !== "APPROVAL_REQUIRED") throw error }
|
||||
}
|
||||
const sealed: Record<string, unknown> = { ...withPath, nativeId: owned.nativeId, outIface, contextSources: value.context.before.sourceProofs, dependencyProof: value.context.before.dependencyProof,
|
||||
const originalEffectSelection = await value.context.captureOriginalEffectSelection(String(input.candidateId))
|
||||
const sealed: Record<string, unknown> = { ...withPath, originalEffectSelection, nativeId: owned.nativeId, outIface, contextSources: value.context.before.sourceProofs, dependencyProof: value.context.before.dependencyProof,
|
||||
originalTargetProof: value.context.before.targetRuleProof, desiredTargetProof: owned.desiredTargetProof(compiled.compiledBody), receiptId: randomUUID(), proofRevision: persistent ? 3 : 2,
|
||||
originalCandidateId: value.context.before.currentCandidateId, originalRuleCiphertext: await encryptSecret(String(owned.rawRow.rule)), desiredRuleCiphertext: await encryptSecret(compiled.compiledBody), managementBindingCiphertext,
|
||||
rules: [publicRule(compiled.proposed)], beforeRules: [publicRule(compiled.before)] }
|
||||
@@ -156,7 +166,26 @@ export function registerScopedCommunityService() {
|
||||
if (await receiptExists(input, "routing.scoped.attempt")) throw fail("Повтор PATCH запрещён", "MUTATION_OUTCOME_UNKNOWN")
|
||||
await receipt(input, "routing.scoped.attempt")
|
||||
const before = await original(input, true), owned = before.context.ownedTarget!
|
||||
let effectSession: Awaited<ReturnType<typeof createRoutingNetworkSessionForCurrentExecution>> | undefined
|
||||
let effectBaseline: Parameters<typeof originalEffectBaselineMatches>[1] | undefined
|
||||
let originalEffects: OriginalEffectReport | undefined
|
||||
const effectSelection = originalEffectSelectionSchema.safeParse(input.originalEffectSelection)
|
||||
if (effectSelection.success) originalEffects = unknownOriginalEffects(effectSelection.data.status === "unknown" ? effectSelection.data.reason : "effect-acquisition-unavailable")
|
||||
try {
|
||||
// Optional original-effect vector is never an extra write/recovery grant.
|
||||
// Old manual configuration+probe acceptance remains authoritative.
|
||||
if (context?.phase === "forward" && input.proofRevision === 3 && effectSelection.success && effectSelection.data.status === "prepared") {
|
||||
try {
|
||||
const selected = effectSelection.data
|
||||
effectSession = await createRoutingNetworkSessionForCurrentExecution({ servers: scopedProfileIds(before.profile),
|
||||
probes: [{ key: selected.probe.key, serverId: selected.probe.serverId, destination: selected.probe.destination,
|
||||
source: selected.probe.source, interface: selected.probe.interface, probeVrf: selected.probe.probeVrf }] })
|
||||
effectBaseline = await effectSession.readSnapshot("before")
|
||||
if (!originalEffectBaselineMatches(selected, effectBaseline)) {
|
||||
effectSession.close(); effectSession = undefined; originalEffects = unknownOriginalEffects("prepared-effect-baseline-drift")
|
||||
}
|
||||
} catch { effectSession?.close(); effectSession = undefined }
|
||||
}
|
||||
await executeGuardedConfigurationWrite(before.profile.serverId, "PATCH", "/routing/filter/rule/" + owned.nativeId, async () => {
|
||||
// This runs AFTER the durable configuration.intent, immediately before transport.
|
||||
const fresh = await original(input, true); await before.context.fence()
|
||||
@@ -170,13 +199,47 @@ export function registerScopedCommunityService() {
|
||||
await saveScopedConfigurationCheckpoint(input, await sealedInput(input))
|
||||
const check = await checkCandidatePath(after.profile, after.candidate.id, principalSchema.parse(input.principal).connectionId, { authorize: after.authorize })
|
||||
if (check.status === "unknown") throw fail("Control probe неизвестен", "MUTATION_OUTCOME_UNKNOWN")
|
||||
// A probe can be long: prove the whole configuration again before a durable VERIFIED receipt.
|
||||
const final = await observe(input, undefined, true, undefined, "configuration")
|
||||
if (!matches(input, final.context).configurationMatchesDesired) throw fail("Состояние изменилось после probe")
|
||||
await final.context.fence()
|
||||
await saveScopedNetworkCheckpoint(input, await sealedInput(input), { ...check, status: check.status })
|
||||
if (effectSession && effectBaseline && effectSelection.success && effectSelection.data.status === "prepared") {
|
||||
let roundContext: Awaited<ReturnType<typeof resolveRoutingNetworkForwardRoundConfigurationContext>> | undefined
|
||||
try {
|
||||
const principal = principalSchema.parse(input.principal), action = { principal, connection: await effectiveMcpConnection(principal) }
|
||||
roundContext = await resolveRoutingNetworkForwardRoundConfigurationContext(effectSession.sharedContext, action)
|
||||
const first = await effectSession.readConfigurationBoundForwardSnapshot(roundContext)
|
||||
const second = await effectSession.readConfigurationBoundForwardSnapshot(roundContext)
|
||||
const observed = await inspectOriginalEffectRounds(effectSelection.data, [first, second], effectBaseline), budget = effectSession.readBudget()
|
||||
originalEffects = { ...observed, budget: { deadline: budget.deadline, calls: budget.calls, bytes: budget.bytes, rows: budget.rows } }
|
||||
} catch (error) { originalEffects = effectReadFailure("original-effect-rounds-unavailable", error) }
|
||||
finally { if (roundContext) closeRoutingNetworkForwardRoundConfigurationContext(roundContext) }
|
||||
}
|
||||
// Publication revalidation uses the existing native owner's fixed
|
||||
// context reader and therefore its SAME counters, without a snapshot.
|
||||
let sharedPublication = false
|
||||
if (effectSession && !effectSession.readBudget().closed) {
|
||||
try {
|
||||
const published = await readRoutingNetworkScopedCommunityContext(effectSession.sharedContext)
|
||||
if (!matches(input, published).configurationMatchesDesired) throw fail("Состояние изменилось после effect-check")
|
||||
await published.fence()
|
||||
const budget = effectSession.readBudget()
|
||||
originalEffects = { ...originalEffects!, budget: { deadline: budget.deadline, calls: budget.calls, bytes: budget.bytes, rows: budget.rows } }
|
||||
sharedPublication = true
|
||||
} catch (error) { originalEffects = effectReadFailure("effect-publication-revalidation-unavailable", error) }
|
||||
}
|
||||
if (!sharedPublication) {
|
||||
// This is the OLD manual final read, relocated after optional work,
|
||||
// never duplicated or counted as a completed effect-owner read.
|
||||
// Closed/exhausted effect owners cannot waive this fresh guard.
|
||||
const final = await observe(input, undefined, true, undefined, "configuration")
|
||||
if (!matches(input, final.context).configurationMatchesDesired) throw fail("Состояние изменилось после probe")
|
||||
await final.context.fence()
|
||||
}
|
||||
if (effectSession && originalEffects) {
|
||||
const budget = effectSession.readBudget()
|
||||
originalEffects = { ...originalEffects, budget: { deadline: budget.deadline, calls: budget.calls, bytes: budget.bytes, rows: budget.rows } }
|
||||
}
|
||||
await saveScopedNetworkCheckpoint(input, await sealedInput(input), { ...check, status: check.status }, originalEffects)
|
||||
return verifiedResult(input)
|
||||
} catch { throw fail("Результат переключения не подтверждён; повтор запрещён, требуется сверка", "MUTATION_OUTCOME_UNKNOWN") }
|
||||
finally { effectSession?.close() }
|
||||
})),
|
||||
verify: async (input, result) => {
|
||||
const expected = await verifiedResult(input)
|
||||
@@ -200,6 +263,7 @@ async function verifiedResult(input: Record<string, unknown>) {
|
||||
const network = await loadScopedNetworkCheckpoint(input, await sealedInput(input))
|
||||
const result = { outcome: network?.status === "passed" ? "applied" : "configuration-applied-network-unverified", nativeWrites: 1, forwardingVerified: false, configurationVerified: true, receiptId: input.receiptId, proofRevision: input.proofRevision,
|
||||
configurationCheckpointAvailable: !!checkpoint, configurationCheckpointProof: checkpoint?.checkpointProof ?? null, controlProbeVerified: network?.status === "passed", postProbeStatus: network?.status ?? "unknown", networkCheckpointProof: network?.networkSeal ?? null,
|
||||
...(network?.originalEffects === undefined ? {} : { originalEffects: network.originalEffects }),
|
||||
nativeVerificationSeal: await privateSecretFingerprint(fingerprint({ request: await sealedInput(input), dependency: input.dependencyProof, desired: input.desiredTargetProof, candidate: input.candidateId, configuration: checkpoint?.checkpointProof ?? null, network: network?.networkSeal ?? null }), `route-ai-scoped-verified-v${input.proofRevision}`) }
|
||||
await assertPersistentScopedProfileAuthority(input)
|
||||
return result
|
||||
|
||||
@@ -4,6 +4,7 @@ import { findMcpOperation } from "./registry.js"
|
||||
import { assertScopedCommunityRequest } from "./routing-community-scoped-request.js"
|
||||
import { assertPersistentScopedProfileAuthority, routingProfileAuthorityBindingSchema } from "./routing-profile-authority.js"
|
||||
import { loadScopedConfigurationPacket, loadScopedNetworkCheckpoint } from "./routing-community-scoped-checkpoint.js"
|
||||
import { originalEffectSelectionSchema } from "./routing-original-effects.js"
|
||||
import { z } from "zod"
|
||||
import { routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||
import { hasPermission } from "../../lib/permissions.js"
|
||||
@@ -166,6 +167,13 @@ export async function advanceRoutingControllerBaseline(rawBaseline: unknown, pro
|
||||
const configuration = await loadScopedConfigurationPacket(input, requestSeal, { operationId, stepIndex: 0 })
|
||||
const network = await loadScopedNetworkCheckpoint(input, requestSeal)
|
||||
if (!configuration || configuration.packet.revision !== 2 || !network || network.status !== "passed") throw fail()
|
||||
// A genuinely prepared effect check may pause controller advancement without
|
||||
// erasing the separate successful manual configuration/control-probe receipt.
|
||||
if (Object.hasOwn(input, "originalEffectSelection")) {
|
||||
const effects = originalEffectSelectionSchema.safeParse(input.originalEffectSelection)
|
||||
if (!effects.success || effects.data.status !== "prepared" || network.originalEffects?.status !== "observed-expected" ||
|
||||
network.originalEffects.selectionIdentity !== fingerprint(effects.data) || network.originalEffects.switchEffectObserved !== true || !network.originalEffects.transition?.changedPrefixes.length) throw fail()
|
||||
}
|
||||
const packet = configuration.packet, result = row.result
|
||||
if (packet.operationId !== operationId || packet.stepIndex !== 0 || packet.nativeId !== original.nativeId ||
|
||||
packet.originalCandidateId !== original.candidateId || packet.originalTargetProof !== original.targetProof ||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readRoutingTopology } from "../../services/routing-topology-observation.js"
|
||||
import { createRoutingSourceContext, readRoutingEndpoints } from "./routing-observation-source.js"
|
||||
import { z } from "zod"
|
||||
import { dedupeVrfAliasSnapshots } from "../../services/vrf-production-action-binding.js"
|
||||
import { pool } from "../../db/index.js"
|
||||
@@ -177,14 +179,26 @@ export function registerRoutingControls(register: typeof add) {
|
||||
},
|
||||
})
|
||||
register("routing.topology.read", "mm_routing_topology_get", "Наблюдаемая конфигурация маршрутизации", "network", "mm:network:read", "read", "servers", z.object({ serverId }).strict(), {
|
||||
read: async input => {
|
||||
const { client } = await routerClient(Number(input.serverId))
|
||||
const paths = { interfaces: "/interface", ipv4: "/ip/route", ipv6: "/ipv6/route", tables: "/routing/table", rules: "/routing/rule", vrfs: "/ip/vrf", ospfNeighbors: "/routing/ospf/neighbor", bgpSessions: "/routing/bgp/session" }
|
||||
const entries = await Promise.all(Object.entries(paths).map(async ([key, path]) => {
|
||||
try { const values = await client.get<unknown>(path); const rows = Array.isArray(values) ? values : [values]; return [key, { items: rows.slice(0, 500), truncated: rows.length > 500, observed: true }] }
|
||||
catch { return [key, { items: [], observed: false, reason: "Устройство не подтвердило возможность чтения" }] }
|
||||
}))
|
||||
return { serverId: input.serverId, observedAt: new Date().toISOString(), resources: Object.fromEntries(entries), observedPath: false }
|
||||
read: async (input, context) => {
|
||||
const sid = Number(input.serverId)
|
||||
if (!context.connection.policy.scope.serverIds.includes(sid)) throw new McpError("SERVER_DENIED", "Источник топологии вне разрешённой области", 403)
|
||||
const signal = AbortSignal.any([AbortSignal.timeout(30000), ...(context.signal ? [context.signal] : [])])
|
||||
const authorize = async () => {
|
||||
if (signal.aborted) throw new McpError("READ_CANCELLED", "Чтение топологии отменено или превысило срок", 409)
|
||||
const current = await effectiveMcpConnection(context.principal)
|
||||
if (!hasPermission(current.owner_permissions, "mm:network:read") || !hasPermission(current.policy.permissions, "mm:network:read")) throw new McpError("PERMISSION_DENIED", "Право чтения сети отозвано", 403)
|
||||
if (fingerprint(current.policy) !== fingerprint(context.connection.policy) || fingerprint(current.owner_permissions) !== fingerprint(context.connection.owner_permissions)) throw new McpError("RESET_REQUIRED", "Допуск изменился; повторите чтение топологии", 409)
|
||||
}
|
||||
await authorize()
|
||||
const source = await createRoutingSourceContext(await readRoutingEndpoints([sid]))
|
||||
if (source.expected.length !== 1) throw new McpError("DEVICE_UNAVAILABLE", "Источник топологии отсутствует или выключен", 409)
|
||||
const beforeRead = async () => {
|
||||
await authorize(); await source.assertCurrent()
|
||||
if (signal.aborted) throw new McpError("READ_CANCELLED", "Чтение топологии отменено или превысило срок", 409)
|
||||
}
|
||||
await beforeRead()
|
||||
const { client } = await routerClient(sid)
|
||||
return { serverId: sid, ...await readRoutingTopology(client, beforeRead, signal) }
|
||||
},
|
||||
})
|
||||
register("routing.ecmp.update", "mm_ecmp_plan", "Равная стоимость маршрутов ECMP и hash policy", "network", "mm:network:write", "write", "servers", z.object({ serverId, family, routeIds: z.array(objectId).min(2).max(8).refine(ids => new Set(ids).size === ids.length), distance: z.number().int().min(1).max(255).default(1), hashPolicy: z.enum(["l3", "l4", "l3-inner"]).optional() }).strict(), {
|
||||
|
||||
@@ -201,12 +201,13 @@ test("missing genuine checkpoint closes shared owner without accepting equality"
|
||||
|
||||
test("forward round context reuses one admitted source only through its exact ephemeral acquisition", async () => {
|
||||
const f = await fixture(), token = await f.resolveRound()
|
||||
assert.equal(f.stats().sharedReads, 0, "Round admission grants no native-success observation")
|
||||
for (let round = 0; round < 2; round++) {
|
||||
const before = await f.readRound(token), after = await f.readRound(token)
|
||||
assert.equal(before.operationId, f.row.id); assert.equal(after.securityProof, false)
|
||||
assert.equal(after.forwardingVerified, false); assert.equal(after.sharedNetworkBudgetVerified, true)
|
||||
}
|
||||
assert.equal(f.stats().sharedReads, 5)
|
||||
assert.equal(f.stats().sharedReads, 4)
|
||||
await assert.rejects(f.resolveShared(), /already issued/)
|
||||
})
|
||||
|
||||
@@ -221,3 +222,16 @@ for (const fault of ["clone", "owner", "body", "dependency", "checkpoint", "revo
|
||||
await assert.rejects(f.readRound(fault === "clone" ? JSON.parse(JSON.stringify(token)) : token, fault === "owner" ? {} : f.acquisition))
|
||||
assert.equal(f.stats().sharedClosed, !["clone", "close"].includes(fault))
|
||||
})
|
||||
|
||||
|
||||
for (const drift of ["body", "dependency", "checkpoint", "revoke"] as const)
|
||||
test("first forward-round read detects " + drift + " after source-only admission", async () => {
|
||||
const f = await fixture(), token = await f.resolveRound()
|
||||
assert.equal(f.stats().nativeReads, 0)
|
||||
if (drift === "body" || drift === "dependency") f.drift(drift)
|
||||
if (drift === "checkpoint") f.checkpointChanged()
|
||||
if (drift === "revoke") f.revoke()
|
||||
await assert.rejects(f.readRound(token))
|
||||
assert.equal(f.stats().sharedClosed, true)
|
||||
await assert.rejects(f.readRound(token))
|
||||
})
|
||||
@@ -68,7 +68,9 @@ export async function resolveRoutingNetworkConfigurationContextFromSharedContext
|
||||
* as the existing bridge. Only its owning session can use it inside a queued
|
||||
* round acquisition; JSON copies and caller-supplied observations cannot. */
|
||||
export async function resolveRoutingNetworkForwardRoundConfigurationContext(sharedContext: RoutingNetworkSharedContext, action: ActionContext): Promise<RoutingNetworkForwardRoundConfigurationContext> {
|
||||
const initial = await resolveRoutingNetworkConfigurationContextFromSharedContext(sharedContext, action)
|
||||
const binding = inspectRoutingNetworkSharedContext(sharedContext)
|
||||
if (fingerprint(binding.principal) !== fingerprint(action.principal)) throw fail("Shared configuration principal changed")
|
||||
const initial = await resolveConfigurationContext(binding.sourceOperationId, action, sharedContext, true)
|
||||
const entry = contexts.get(initial)
|
||||
if (!entry) throw fail("Configuration bridge admission disappeared")
|
||||
contexts.delete(initial)
|
||||
@@ -96,7 +98,8 @@ export function closeRoutingNetworkForwardRoundConfigurationContext(context: Rou
|
||||
roundContexts.delete(context); entry?.close()
|
||||
}
|
||||
|
||||
async function resolveConfigurationContext(sourceOperationId: string, action: ActionContext, sharedContext?: RoutingNetworkSharedContext): Promise<RoutingNetworkConfigurationContext> {
|
||||
async function resolveConfigurationContext(sourceOperationId: string, action: ActionContext, sharedContext?: RoutingNetworkSharedContext, deferredRoundReadback = false): Promise<RoutingNetworkConfigurationContext> {
|
||||
if (deferredRoundReadback && !sharedContext) throw fail("Forward round requires its original shared owner")
|
||||
z.string().uuid().parse(sourceOperationId)
|
||||
const principal = freeze(structuredClone(action.principal)), connection = freeze(structuredClone(action.connection))
|
||||
const abort = new AbortController()
|
||||
@@ -190,7 +193,11 @@ async function resolveConfigurationContext(sourceOperationId: string, action: Ac
|
||||
bodyIdentity: fingerprint(original.packet.desiredRule), dependencyIdentity: original.packet.dependencyProof },
|
||||
securityProof: false as const, forwardingVerified: false as const, sharedNetworkBudgetVerified: !!sharedContext })
|
||||
}
|
||||
await readback()
|
||||
// A forward-round token carries no native success observation. Its fixed
|
||||
// owner must perform a fresh read immediately BEFORE every snapshot and
|
||||
// another immediately AFTER. Avoid an unused eager native read here;
|
||||
// independent/shared one-shot bridge semantics remain unchanged.
|
||||
if (!deferredRoundReadback) await readback()
|
||||
const token = Object.freeze({}) as RoutingNetworkConfigurationContext
|
||||
contexts.set(token, { consumed: false, close, read: readback, consume: async () => {
|
||||
try { return await readback() }
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
import test from 'node:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
const require = createRequire(new URL('../../../package.json', import.meta.url));
|
||||
const ts = require('typescript');
|
||||
const code = ts.transpileModule(await readFile(new URL('./routing-network-execution-session.ts', import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
|
||||
}).outputText;
|
||||
function fixture() {
|
||||
const now = Date.now();
|
||||
const metadata = { approved: true, phase: 'forward', stepIndex: 0, operationName: 'routing.community.switch', operationVersion: 7,
|
||||
serviceName: 'routing.community.scoped', operationId: 'real-operation', planId: 'real-plan', principal: { connectionId: 'real-connection', credentialExpiresAt: new Date(now + 90000).toISOString() },
|
||||
serviceInput: { persistentProfileAuthority: { packet: { validUntil: new Date(now + 70000).toISOString() } } } };
|
||||
metadata.sealedEvidenceProof = createHash('sha256').update('evidence-ciphertext').digest('hex');
|
||||
metadata.sealedPayloadProof = createHash('sha256').update('payload-ciphertext').digest('hex');
|
||||
const original = structuredClone(metadata);
|
||||
const row = { created_at: new Date(now - 40000), expires_at: new Date(now + 100000), evidence: { sealed: 'evidence-ciphertext' }, payload: { sealed: 'payload-ciphertext' },
|
||||
intended_state: { kind: 'service', service: metadata.serviceName, input: structuredClone(metadata.serviceInput) } };
|
||||
const lifetime = { expiresAt: now + 60000, monotonicDeadline: performance.now() + 60000, signal: new AbortController().signal };
|
||||
let calls = 0, inspections = 0, closed = 0, options, query, originAvailable = true, afterCreate = () => {};
|
||||
const connection = { owner_valid_until: new Date(now + 110000), policy: { expiresAt: new Date(now + 120000).toISOString() } };
|
||||
const token = Object.freeze({});
|
||||
const providers = {
|
||||
'node:crypto': { createHash },
|
||||
'../../db/index.js': { pool: { query: async value => { query = value; return { rows: [row] }; } } },
|
||||
'../../services/config-mutation-policy.js': {
|
||||
captureVerifiedMcpServiceExecution: async () => { if (!originAvailable) throw Error('no-origin'); return token; },
|
||||
inspectVerifiedMcpServiceExecution: async value => { assert.equal(value, token); inspections++; return structuredClone(metadata); },
|
||||
inspectVerifiedMcpServiceExecutionLifetime: async value => { assert.equal(value, token); return lifetime; }
|
||||
},
|
||||
'./store.js': { effectiveMcpConnection: async principal => { assert.deepEqual(principal, original.principal); return connection; } },
|
||||
'./registry.js': { findMcpOperation: () => ({ version: 7 }) },
|
||||
'./security.js': { fingerprint: JSON.stringify, redact: value => value, McpError: Error },
|
||||
'./routing-profile-authority.js': { routingProfileAuthorityBindingSchema: { parse: value => value } },
|
||||
'./routing-network-native-session.js': { createRoutingNetworkNativeSession: async value => { calls++; options = value; afterCreate(); return { close() { closed++; } }; } }
|
||||
};
|
||||
const exports = {};
|
||||
new Function('exports', 'require', code)(exports, name => { assert.ok(providers[name], name); return providers[name]; });
|
||||
const manifest = { servers: [1, 2], probes: [] };
|
||||
return { metadata, row, lifetime, connection, manifest, now, run: () => exports.createRoutingNetworkSessionForCurrentExecution(manifest),
|
||||
revokeOrigin: () => { originAvailable = false; }, afterCreate: fn => { afterCreate = fn; },
|
||||
stats: () => ({ calls, closed, inspections, options, query }) };
|
||||
}
|
||||
test('real origin supplies operation, principal, signal and minimum immutable horizon', async () => {
|
||||
const f = fixture(); await f.run(); const { options, query } = f.stats();
|
||||
assert.equal(options.sourceOperationId, f.metadata.operationId); assert.equal(options.context.signal, f.lifetime.signal);
|
||||
assert.equal(options.deadline, f.lifetime.expiresAt - 15000); assert.equal(options.manifest, f.manifest);
|
||||
assert.deepEqual(query.values, [f.metadata.operationId, f.metadata.principal.connectionId, f.metadata.planId]);
|
||||
assert.match(query.text, /o.state='running'/); assert.match(query.text, /s.state='intent'/);
|
||||
});
|
||||
test('elapsed original 120 seconds cannot be renewed from current time', async () => {
|
||||
const f = fixture(); f.row.created_at = new Date(f.now - 120001); await assert.rejects(f.run); assert.equal(f.stats().calls, 0);
|
||||
});
|
||||
for (const [name, change] of [
|
||||
['plan', f => { f.row.expires_at = new Date(f.now + 30000); }],
|
||||
['owner', f => { f.connection.owner_valid_until = new Date(f.now + 30000); }],
|
||||
['policy', f => { f.connection.policy.expiresAt = new Date(f.now + 30000).toISOString(); }],
|
||||
['profile', f => { f.metadata.serviceInput.persistentProfileAuthority.packet.validUntil = new Date(f.now + 30000).toISOString(); f.row.intended_state.input = structuredClone(f.metadata.serviceInput); }],
|
||||
['operation', f => { f.row.created_at = new Date(f.now - 90000); }]
|
||||
]) test(`minimum ${name} expiry is conserved with publication reserve`, async () => { const f = fixture(); change(f); await f.run(); assert.equal(f.stats().options.deadline, f.now + 15000); });
|
||||
for (const [key, value] of [['approved', false], ['phase', 'recovery'], ['stepIndex', 1], ['operationName', 'operations.recover'], ['operationVersion', 6], ['serviceName', 'routing.community']]) {
|
||||
test(`wrong live origin ${key} is denied before native factory`, async () => { const f = fixture(); f.metadata[key] = value; await assert.rejects(f.run); assert.equal(f.stats().calls, 0); });
|
||||
}
|
||||
test('outside verified origin cannot supply authority', async () => { const f = fixture(); f.revokeOrigin(); await assert.rejects(f.run); assert.equal(f.stats().calls, 0); });
|
||||
test('persisted intended state must match the live service input', async () => { const f = fixture(); f.row.intended_state.input = {}; await assert.rejects(f.run); assert.equal(f.stats().calls, 0); });
|
||||
for (const field of ['evidence', 'payload']) test(`changed randomized sealed ${field} is denied before native`, async () => { const f = fixture(); f.row[field].sealed = 'changed'; await assert.rejects(f.run); assert.equal(f.stats().calls, 0); });
|
||||
test('monotonic expiry denies open even with unexpired wall horizon', async () => { const f = fixture(); f.lifetime.monotonicDeadline = performance.now() - 1; await assert.rejects(f.run); assert.equal(f.stats().calls, 0); });
|
||||
test('late origin change closes the newly opened native owner', async () => { const f = fixture(); f.afterCreate(() => { f.metadata.planId = 'changed'; }); await assert.rejects(f.run); assert.equal(f.stats().closed, 1); });
|
||||
test('returned native authorize callback remains tied to original metadata', async () => { const f = fixture(); await f.run(); f.metadata.operationId = 'changed'; await assert.rejects(f.stats().options.authorize); });
|
||||
@@ -0,0 +1,62 @@
|
||||
import { createHash } from "node:crypto"
|
||||
import type { QueryConfig } from "pg"
|
||||
import { pool } from "../../db/index.js"
|
||||
import { captureVerifiedMcpServiceExecution, inspectVerifiedMcpServiceExecution, inspectVerifiedMcpServiceExecutionLifetime } from "../../services/config-mutation-policy.js"
|
||||
import { effectiveMcpConnection } from "./store.js"
|
||||
import { findMcpOperation } from "./registry.js"
|
||||
import { fingerprint, McpError, redact } from "./security.js"
|
||||
import { routingProfileAuthorityBindingSchema } from "./routing-profile-authority.js"
|
||||
import { createRoutingNetworkNativeSession, type RoutingNetworkNativeManifest } from "./routing-network-native-session.js"
|
||||
|
||||
/** Private producer for the existing native/configuration-round reader. The
|
||||
* manifest selects reads, never identity or authority. Its exact scope, probe
|
||||
* ownership and whole-session budget are still checked by the native factory.
|
||||
* Only the original live verified service step can open or use this session.
|
||||
* No operation/principal/deadline/authorization callback is caller supplied.
|
||||
* This grants no write, recovery or authenticated log-interval coverage. */
|
||||
export async function createRoutingNetworkSessionForCurrentExecution(manifest: RoutingNetworkNativeManifest): Promise<Awaited<ReturnType<typeof createRoutingNetworkNativeSession>>> {
|
||||
const fail = () => new McpError("STATE_CONFLICT", "Нет исходного running scoped execution для native acquisition", 409)
|
||||
const origin = await captureVerifiedMcpServiceExecution()
|
||||
const initial = await inspectVerifiedMcpServiceExecution(origin)
|
||||
if (!initial.approved || initial.phase !== "forward" || initial.stepIndex !== 0 ||
|
||||
initial.operationName !== "routing.community.switch" || initial.operationVersion !== findMcpOperation(initial.operationName)?.version ||
|
||||
initial.serviceName !== "routing.community.scoped") throw fail()
|
||||
const lifetime = await inspectVerifiedMcpServiceExecutionLifetime(origin)
|
||||
const authorize = async () => {
|
||||
const current = await inspectVerifiedMcpServiceExecution(origin)
|
||||
if (fingerprint(current) !== fingerprint(initial)) throw fail()
|
||||
}
|
||||
await authorize()
|
||||
const connection = await effectiveMcpConnection(initial.principal)
|
||||
await authorize()
|
||||
// The service lifetime may be narrower than plan expiry, but it does not
|
||||
// replace the operation-created-at +120s native horizon. Never renew at now.
|
||||
const query: QueryConfig & { query_timeout: number } = { text: `SELECT o.created_at,p.expires_at,
|
||||
CASE WHEN octet_length(p.evidence::text)<=1048576 THEN p.evidence END AS evidence,
|
||||
CASE WHEN octet_length(p.payload::text)<=1048576 THEN p.payload END AS payload,
|
||||
CASE WHEN octet_length(s.intended_state::text)<=1048576 THEN s.intended_state END AS intended_state FROM mcp_operations o
|
||||
JOIN mcp_plans p ON p.id=o.plan_id JOIN mcp_operation_steps s ON s.operation_id=o.id
|
||||
WHERE o.id=$1 AND o.connection_id=$2 AND o.plan_id=$3 AND o.state='running'
|
||||
AND s.step_index=0 AND s.state='intent' LIMIT 2`,
|
||||
values: [initial.operationId, initial.principal.connectionId, initial.planId],
|
||||
query_timeout: Math.max(1, Math.min(10000, lifetime.expiresAt - Date.now())) }
|
||||
const source = await pool.query(query)
|
||||
await authorize()
|
||||
if (source.rows.length !== 1 || !(source.rows[0].created_at instanceof Date) || !(source.rows[0].expires_at instanceof Date)) throw fail()
|
||||
const sha = (value: string) => createHash("sha256").update(value).digest("hex")
|
||||
if (typeof source.rows[0].evidence?.sealed !== "string" || typeof source.rows[0].payload?.sealed !== "string" ||
|
||||
sha(source.rows[0].evidence.sealed) !== initial.sealedEvidenceProof || sha(source.rows[0].payload.sealed) !== initial.sealedPayloadProof) throw fail()
|
||||
if (fingerprint(source.rows[0].intended_state) !== fingerprint(redact({ kind: "service", service: initial.serviceName, input: initial.serviceInput }))) throw fail()
|
||||
const authorityExpiry = initial.serviceInput.persistentProfileAuthority === undefined ? Infinity :
|
||||
Date.parse(routingProfileAuthorityBindingSchema.parse(initial.serviceInput.persistentProfileAuthority).packet.validUntil)
|
||||
const deadline = Math.min(source.rows[0].created_at.getTime() + 120000, source.rows[0].expires_at.getTime(), lifetime.expiresAt,
|
||||
Date.parse(initial.principal.credentialExpiresAt), connection.owner_valid_until.getTime(), Date.parse(connection.policy.expiresAt), authorityExpiry)
|
||||
// Reserve publication/current-authority time for the existing manual result.
|
||||
// This only narrows the original horizon; it never creates a renewed grant.
|
||||
const readDeadline = deadline - 15000
|
||||
if (!Number.isFinite(readDeadline) || Date.now() >= readDeadline || lifetime.signal.aborted || performance.now() >= lifetime.monotonicDeadline) throw fail()
|
||||
const session = await createRoutingNetworkNativeSession({ sourceOperationId: initial.operationId,
|
||||
context: { principal: initial.principal, connection, signal: lifetime.signal }, authorize, deadline: readDeadline, manifest })
|
||||
try { await authorize(); return session }
|
||||
catch (error) { session.close(); throw error }
|
||||
}
|
||||
@@ -15,6 +15,8 @@ assert.equal(target.search, ""); assert.equal(target.hash, "")
|
||||
assert(process.env.MCP_STATE_DIR && isAbsolute(process.env.MCP_STATE_DIR))
|
||||
assert.equal(basename(resolve(process.env.MCP_STATE_DIR)), "state")
|
||||
assert(basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-"))
|
||||
const originalEffects = process.env.MMAPP_OWN_ROUTING_ORIGINAL_EFFECTS === "true"
|
||||
assert(!(originalEffects && process.env.MMAPP_OWN_ROUTING_WORKER_REPRO === "true"), "Owned effect acceptance cannot mix with the worker repro profile")
|
||||
process.env.AUTH_REQUIRED = "true"
|
||||
process.env.AUTH_JWT_SECRET = "owned-routing-forward-rounds-acceptance-secret"
|
||||
process.env.AUTH_ISSUER = "https://owned-routing-forward-rounds.test"
|
||||
@@ -32,7 +34,8 @@ try {
|
||||
if(process.env.MMAPP_OWN_ROUTING_WORKER_REPRO==="true") {
|
||||
console.log("Worker fixture repro:",await (await import("./routing-worker-fixture-isolation.sql-helper.js")).acceptRoutingWorkerFixtureIsolation(actor))
|
||||
}
|
||||
const result = await (await import("./routing-community-scoped-acceptance.js")).acceptScopedRouteCommunitySwitch(actor, process.env.MMAPP_OWN_ROUTING_WORKER_REPRO==="true"?{}:{ forwardRoundsOnly: true })
|
||||
const result = await (await import("./routing-community-scoped-acceptance.js")).acceptScopedRouteCommunitySwitch(actor,
|
||||
originalEffects ? { originalEffectsOnly: true } : process.env.MMAPP_OWN_ROUTING_WORKER_REPRO==="true"?{}:{ forwardRoundsOnly: true })
|
||||
assert.equal(result.accepted, true)
|
||||
} finally {
|
||||
await (await import("../../services/scheduler.js")).stopSchedulerForDatabaseOperation()
|
||||
|
||||
@@ -353,3 +353,21 @@ test("DNS cancellation retains uncancellable lookup capacity and a late answer c
|
||||
authorize: async () => { if (++checks > 1) throw new SessionError("RESET_REQUIRED", "revoked during DNS") } }), (error: { code?: string }) => error.code === "RESET_REQUIRED")
|
||||
assert.equal(lookups, 1)
|
||||
})
|
||||
|
||||
|
||||
test("complete authority fences bound repeated runtime authorization while preserving every native boundary", async () => {
|
||||
const f = await fixture(), session = await f.create(f.options)
|
||||
const before = f.stats()
|
||||
await session.readSnapshot("before")
|
||||
const after = f.stats(), native = after.nativeCalls - before.nativeCalls, callbacks = after.callbacks - before.callbacks
|
||||
assert.equal(native, 6)
|
||||
// Two full fences and the direct dispatch guard stay fresh for every call.
|
||||
// SQL/file leaves inside those fences must not recursively multiply them.
|
||||
assert(callbacks >= native * 4)
|
||||
assert(callbacks <= 50, "Six native reads must fit a bounded number of complete runtime revalidations")
|
||||
f.afterNative(f.revoke)
|
||||
await assert.rejects(session.readSnapshot("after-forward"))
|
||||
assert.equal(f.stats().nativeCalls, after.nativeCalls + 1)
|
||||
await assert.rejects(session.readSnapshot("after-forward"))
|
||||
assert.equal(f.stats().nativeCalls, after.nativeCalls + 1)
|
||||
})
|
||||
@@ -119,8 +119,16 @@ export async function createRoutingNetworkNativeSession(options: {
|
||||
try { return await work() }
|
||||
finally { active(); await trustedAuthorize(); active() }
|
||||
}
|
||||
// Primitive source reads keep the immutable lifetime checks. The complete
|
||||
// authority fence surrounds their batch; native dispatch retains its own
|
||||
// fresh before/after authorization. Avoid recursively re-running the full
|
||||
// runtime authorization around every SQL/file leaf inside that same fence.
|
||||
const bounded = async <T>(work: () => Promise<T>) => {
|
||||
active()
|
||||
try { return await work() } finally { active() }
|
||||
}
|
||||
const currentAuthority = async () => {
|
||||
const current = await guarded(() => effectiveMcpConnection(principal))
|
||||
const current = await bounded(() => effectiveMcpConnection(principal))
|
||||
if (current.id !== connection.id || current.owner_id !== connection.owner_id || current.generation !== connection.generation ||
|
||||
fingerprint(current.policy) !== fingerprint(connection.policy) || fingerprint(current.owner_permissions) !== fingerprint(connection.owner_permissions) ||
|
||||
!hasPermission(current.owner_permissions, "mm:network:read") || !hasPermission(current.policy.permissions, "mm:network:read") ||
|
||||
@@ -129,13 +137,14 @@ export async function createRoutingNetworkNativeSession(options: {
|
||||
const sourceRow = async () => {
|
||||
const query: QueryConfig & { query_timeout: number } = { text: "SELECT o.id,o.state,o.connection_id,o.created_at,p.id AS plan_id,p.operation_id,p.operation_version,p.approved_by,p.expires_at,s.state AS step_state,CASE WHEN octet_length(s.intended_state::text)<=1048576 THEN s.intended_state END AS intended_state,CASE WHEN octet_length(p.evidence::text)<=1048576 THEN p.evidence END AS evidence FROM mcp_operations o JOIN mcp_plans p ON p.id=o.plan_id JOIN mcp_operation_steps s ON s.operation_id=o.id AND s.step_index=0 WHERE o.id=$1 AND o.connection_id=$2 LIMIT 2",
|
||||
values: [sourceOperationId, principal.connectionId], query_timeout: Math.max(1, Math.min(10000, deadline - Date.now())) }
|
||||
const result = await guarded(() => pool.query(query))
|
||||
const result = await bounded(() => pool.query(query))
|
||||
if (result.rows.length !== 1) throw fail("NOT_FOUND", "Exact source native session недоступен")
|
||||
const row = result.rows[0]
|
||||
if (!["running", "applied", "partial"].includes(row.state) || !["intent", "applied", "verified"].includes(row.step_state) || row.operation_id !== "routing.community.switch" || row.operation_version !== findMcpOperation(row.operation_id)?.version || !row.approved_by || !row.evidence?.sealed || !(row.created_at instanceof Date) || !(row.expires_at instanceof Date)) throw fail("STATE_CONFLICT", "Нет совместимого подтверждённого source intent")
|
||||
return row
|
||||
}
|
||||
try {
|
||||
await guarded(async () => {})
|
||||
await currentAuthority()
|
||||
const row = await sourceRow()
|
||||
if (row.state !== "running" || row.step_state !== "intent") throw fail("STATE_CONFLICT", "Native session требует исходный running intent")
|
||||
@@ -176,14 +185,14 @@ export async function createRoutingNetworkNativeSession(options: {
|
||||
if (endpoints.length !== fullScope.length || endpoints.some(endpoint => !endpoint.enabled) || fingerprint(endpoints.map(endpoint => endpoint.id).sort((a,b) => a-b)) !== fingerprint(fullScope)) throw fail("DEVICE_UNAVAILABLE", "Полный источник native manifest недоступен")
|
||||
const sources = await guarded(() => createRoutingSourceContext(endpoints))
|
||||
if (fingerprint(sources.expected) !== fingerprint(input.contextSources)) throw fail("STATE_CONFLICT", "Исходный endpoint manifest изменился")
|
||||
const fence = async () => {
|
||||
const fence = async () => guarded(async () => {
|
||||
await currentAuthority()
|
||||
if (await guarded(() => accessGeneration()) !== generation) throw fail("RESET_REQUIRED", "Access generation native session изменён")
|
||||
await guarded(() => assertPersistentScopedProfileAuthority(input, signal))
|
||||
if (await bounded(() => accessGeneration()) !== generation) throw fail("RESET_REQUIRED", "Access generation native session изменён")
|
||||
await bounded(() => assertPersistentScopedProfileAuthority(input, signal))
|
||||
const current = await sourceRow()
|
||||
if (fingerprint({ id: current.id, createdAt: current.created_at, planId: current.plan_id, evidence: current.evidence, expiresAt: current.expires_at, intendedState: current.intended_state }) !== sourceIdentity) throw fail("STATE_CONFLICT", "Исходный native intent изменён")
|
||||
await guarded(() => sources.assertCurrent())
|
||||
}
|
||||
await bounded(() => sources.assertCurrent())
|
||||
})
|
||||
const pins = await guarded(() => resolveRoutingNetworkDestinationPins(endpoints, { deadline, signal, authorize: fence }))
|
||||
await fence()
|
||||
const clients = routeContextClients(freeze(structuredClone(endpoints)), signal, { deadline, maxCalls: 256, maxBytes: 8 * 1048576, pins })
|
||||
|
||||
@@ -17,7 +17,8 @@ const { installLoopbackFixtureAgent } = await import("../../test/loopback-http-a
|
||||
const { mcpConnectionPolicySchema } = await import("@mmapp/contracts/mcp")
|
||||
const { routeAiProfileSchema } = await import("@mmapp/contracts/mcp-routing")
|
||||
const security = await import("./security.js")
|
||||
const { effectiveMcpConnection } = await import("./store.js")
|
||||
const { effectiveMcpConnection, authenticateMcpToken } = await import("./store.js")
|
||||
const { invokeMcpTool } = await import("./runtime.js")
|
||||
const { createRoutingSourceContext, readRoutingEndpoints } = await import("./routing-observation-source.js")
|
||||
const { resolveRoutingProfileAuthority } = await import("./routing-profile-authority.js")
|
||||
await import("./actions.js")
|
||||
@@ -28,7 +29,7 @@ const { captureRoutingNetworkObservationAssembly } = await import("./routing-net
|
||||
const { readRoutingNetworkScopedCommunityContext } = await import("./routing-network-scoped-context.js")
|
||||
type Options = Parameters<typeof createRoutingNetworkNativeSession>[0]
|
||||
|
||||
type Mode = "normal" | "zero-ping" | "redirect" | "auth" | "malformed" | "oversized" | "rows" | "total-bytes" | "total-rows"
|
||||
type Mode = "topology-unknown" | "normal" | "zero-ping" | "redirect" | "auth" | "malformed" | "oversized" | "rows" | "total-bytes" | "total-rows"
|
||||
let mode: Mode = "normal", onRequest: (() => Promise<void> | void) | undefined
|
||||
const requests: { method: string; path: string; body: Record<string, string> }[] = []
|
||||
let responseBytes = 0, writes = 0, sinks = 0
|
||||
@@ -82,6 +83,7 @@ const router = http.createServer(async (req, res) => {
|
||||
assert.equal(body.address, "203.0.113.9"); assert.equal(body.interface, "wan1"); assert.equal(body.vrf, "probe"); assert.equal(body["max-hops"], "16")
|
||||
payload = [{ ".section": "0", address: "203.0.113.9", sent: "3", loss: "0", last: "1ms" }]
|
||||
} else { writes++; throw Error("Unexpected native mutation") }
|
||||
if (mode === "topology-unknown" && path === "/routing/route") payload = [{ ...collections(path)[0], "immediate-gw": "17", "bgp.peer-cache-id": "*s1" }]
|
||||
if (mode === "rows") payload = Array.from({ length: 1001 }, () => ({ version: "7.26" }))
|
||||
if (mode === "total-rows" && path !== "/system/resource") payload = Array.from({ length: 1000 }, () => ({ value: "fixture" }))
|
||||
if (mode === "total-bytes") payload = [{ version: "7.26", padding: "x".repeat(600000) }]
|
||||
@@ -133,6 +135,12 @@ async function source(withProbes = true) {
|
||||
|
||||
try {
|
||||
await applySqlMigrations(pool)
|
||||
// Other genuine phases may have already created authenticated checkpoints in
|
||||
// this owned database. Read-only acceptance must preserve every existing row
|
||||
// and add none; raw SQL JSON also preserves timestamp microseconds that
|
||||
// conversion to a JavaScript Date would truncate.
|
||||
const checkpointBaselineRows = (await pool.query("SELECT to_jsonb(c)::text AS inventory_row FROM mcp_operation_checkpoints c ORDER BY operation_id,step_index")).rows
|
||||
const checkpointBaseline = security.fingerprint(checkpointBaselineRows)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM servers")).rows[0].n, 0)
|
||||
await pool.query("UPDATE mcp_settings SET enabled=true WHERE id=1")
|
||||
serverId = Number((await pool.query("INSERT INTO servers(name,host,port,enabled,username,password,use_ssl,verify_ssl) VALUES('owned-native-reader','127.0.0.1',$1,true,'fixture','inert-only',false,true) RETURNING id", [bound.port])).rows[0].id)
|
||||
@@ -140,9 +148,11 @@ try {
|
||||
const f = await source(), originalAuthorize = f.options.authorize, session = await createRoutingNetworkNativeSession(f.options), before = responseBytes
|
||||
const first = await session.readSnapshot("before")
|
||||
assert.equal(first.securityProof, false); assert.equal(first.logCoverage, "unknown"); assert.equal(first.probes.length, 1)
|
||||
const stamp = Date.now(), server = first.servers[0]
|
||||
const server = first.servers[0]
|
||||
const manifest = { revision: 1, phase: "forward", identity: { operationId: f.operationId, stepIndex: 0, profileId: f.profileId, profileVersion: 1, sourceEpoch: "owned-fixture-epoch", authorityIdentity: "owned-fixture-authority" },
|
||||
sourceCreatedAt: stamp - 1000, deadline: f.options.deadline, observationStartAt: stamp - 500, maximumSampleAgeMs: 30000, serverIds: [serverId],
|
||||
// Bind the diagnostic fixture to the actual acquisition interval. A guessed
|
||||
// lookback after SQL/HTTP completes can put its source after the first read.
|
||||
sourceCreatedAt: Date.parse(first.startedAt), deadline: f.options.deadline, observationStartAt: Date.parse(first.observedAt), maximumSampleAgeMs: 30000, serverIds: [serverId],
|
||||
configuration: { serverId, nativeId: "*r1", table: "tenant", bodyIdentity: "not-a-configuration-checkpoint", dependencyIdentity: "not-a-publication-proof" },
|
||||
routes: [{ key: "route1", serverId, family: "ipv4", prefix: "203.0.113.0/24", table: "tenant", sessionKey: "peer1", nextHop: "192.0.2.1", interface: "wan1", resolverTable: "main", resolutionChain: [{ address: "192.0.2.1", table: "main", interface: "wan1" }] }],
|
||||
bgp: [{ key: "peer1", serverId, family: "ipv4", connectionId: "*c1", instance: "default", localAddress: "192.0.2.2", remoteAddress: "192.0.2.1", remoteAsn: 65001 }],
|
||||
@@ -233,9 +243,59 @@ try {
|
||||
const f = await source(false), session = await createRoutingNetworkNativeSession(f.options); mode = "total-rows"
|
||||
await session.readSnapshot("before"); await assert.rejects(session.readSnapshot("after-forward")); assert(session.readBudget().rows > 10000)
|
||||
})
|
||||
const topologyObserver = async () => {
|
||||
const f = await source(false), { connectionId, credentialId } = f.options.context.principal
|
||||
const policy = mcpConnectionPolicySchema.parse({ ...f.options.context.connection.policy, mode: "observer", permissions: ["mm:network:read"],
|
||||
scope: { serverIds: [serverId!], operationIds: ["routing.topology.read"], allowGlobal: false } })
|
||||
await pool.query("UPDATE mcp_connections SET policy=$2::jsonb,owner_permissions=$3::jsonb WHERE id=$1", [connectionId, JSON.stringify(policy), JSON.stringify(["mm:network:read"])])
|
||||
const token = security.randomToken("bearer")
|
||||
await pool.query("UPDATE mcp_credentials SET digest=$2 WHERE id=$1", [credentialId, security.tokenDigest(token)])
|
||||
return { principal: await authenticateMcpToken(token), connectionId }
|
||||
}
|
||||
await run("actual public topology bearer reader observes final gateway without operation binding or namespace joins", async () => {
|
||||
const f = await topologyObserver(), count = requests.length, plans = Number((await pool.query("SELECT count(*) AS n FROM mcp_plans")).rows[0].n)
|
||||
const result = await invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId }) as { routeResolution: { status: string; items: Array<{ status: string; immediateGateway: { address: string; interface: string }; semanticProof: boolean; routeOriginVerified: boolean; recursiveChainVerified: boolean }> } }
|
||||
assert.equal(requests.length - count, 11)
|
||||
assert.equal(result.routeResolution.status, "observed")
|
||||
const route = result.routeResolution.items[0]
|
||||
assert.equal(route.status, "observed"); assert.deepEqual(route.immediateGateway, { address: "192.0.2.1", interface: "wan1" })
|
||||
assert.equal(route.semanticProof, false); assert.equal(route.routeOriginVerified, false); assert.equal(route.recursiveChainVerified, false)
|
||||
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM mcp_plans")).rows[0].n), plans)
|
||||
assert(!JSON.stringify(result).includes("peer-cache-id")); assert(!JSON.stringify(result).includes("bgp.session"))
|
||||
})
|
||||
await run("actual public topology preserves unknown numeric gateway despite matching BGP cache/session strings", async () => {
|
||||
const f = await topologyObserver(); mode = "topology-unknown"
|
||||
const result = await invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId }) as { routeResolution: { items: Array<{ status: string; reason: string }> } }
|
||||
assert.equal(result.routeResolution.items[0].status, "unknown")
|
||||
assert.equal(result.routeResolution.items[0].reason, "unconfirmed-immediate-endpoint")
|
||||
})
|
||||
await run("actual public topology bearer and server scope/disabled checks refuse before native I/O", async () => {
|
||||
const f = await topologyObserver(), count = requests.length
|
||||
await assert.rejects(authenticateMcpToken("not-a-token"))
|
||||
await assert.rejects(invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId: serverId! + 100000 }))
|
||||
await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [serverId])
|
||||
await assert.rejects(invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId }))
|
||||
await pool.query("UPDATE servers SET enabled=true WHERE id=$1", [serverId])
|
||||
assert.equal(requests.length, count)
|
||||
})
|
||||
await run("actual public topology pause endpoint ABA and cancellation retire at first response without publication", async () => {
|
||||
for (const fault of ["pause", "endpoint-aba", "cancel"] as const) {
|
||||
const f = await topologyObserver(), count = requests.length, cancel = new AbortController()
|
||||
onRequest = async () => {
|
||||
if (fault === "pause") await pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"paused\"') WHERE id=$1", [f.connectionId])
|
||||
else if (fault === "endpoint-aba") {
|
||||
await pool.query("UPDATE servers SET verify_ssl=NOT verify_ssl WHERE id=$1", [serverId])
|
||||
await pool.query("UPDATE servers SET verify_ssl=NOT verify_ssl WHERE id=$1", [serverId])
|
||||
} else cancel.abort()
|
||||
}
|
||||
await assert.rejects(invokeMcpTool(f.principal, "mm_routing_topology_get", { serverId }, cancel.signal))
|
||||
assert.equal(requests.length, count + 1)
|
||||
}
|
||||
})
|
||||
assert.equal(writes, 0)
|
||||
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_operation_checkpoints")).rows[0].n, 0, "Read-only acceptance must not manufacture CONFIG_APPLIED or network checkpoints")
|
||||
console.log("Owned routing native reader SQL/HTTP:", JSON.stringify({ cases: cases.length, names: cases, requests: requests.length, nativeWrites: writes, actualSql: true, actualHttp: true, syntheticEncryptedSourcePlans: true, genuinePrepareAccepted: false, configurationCheckpointFabricated: false, signedNetworkOutcomePublished: false, logCoverage: "unknown", reservedDispatchEnabled: false, realChr: false }))
|
||||
assert.equal(security.fingerprint((await pool.query("SELECT to_jsonb(c)::text AS inventory_row FROM mcp_operation_checkpoints c ORDER BY operation_id,step_index")).rows), checkpointBaseline,
|
||||
"Read-only acceptance must preserve existing checkpoints exactly and create none")
|
||||
console.log("Owned routing native reader SQL/HTTP:", JSON.stringify({ cases: cases.length, names: cases, requests: requests.length, nativeWrites: writes, actualSql: true, actualHttp: true, syntheticEncryptedSourcePlans: true, genuinePrepareAccepted: false, configurationCheckpointFabricated: false, priorCheckpointsPreserved: checkpointBaselineRows.length, checkpointInventoryUnchanged: true, signedNetworkOutcomePublished: false, logCoverage: "unknown", reservedDispatchEnabled: false, realChr: false }))
|
||||
} finally {
|
||||
if (profiles.length) await pool.query("UPDATE mcp_routing_profiles SET enabled=false WHERE id=ANY($1::uuid[])", [profiles]).catch(() => {})
|
||||
if (connections.length) await pool.query("UPDATE mcp_connections SET policy=jsonb_set(policy,'{status}','\"paused\"') WHERE id=ANY($1::uuid[])", [connections]).catch(() => {})
|
||||
|
||||
@@ -65,6 +65,7 @@ for (const ipv6 of [false, true]) for (const inverse of [false, true]) test(`fix
|
||||
})
|
||||
|
||||
const invalid = {
|
||||
"source-after-first-read": (f: ReturnType<typeof captured>) => { f.manifest.sourceCreatedAt = Date.parse(f.snapshots[0].startedAt) + 1 },
|
||||
"foreign-operation": (f: ReturnType<typeof captured>) => { f.snapshots[1].sourceOperationId = "00000000-0000-4000-8000-000000000099" },
|
||||
"duplicate-server": (f: ReturnType<typeof captured>) => { f.snapshots[1].servers.push(f.snapshots[1].servers[0]) },
|
||||
"missing-probe": (f: ReturnType<typeof captured>) => { f.snapshots[1].probes = [] },
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import test from 'node:test';
|
||||
const require=createRequire(new URL('../../../package.json',import.meta.url)),ts=require('typescript'),{z}=require('zod');
|
||||
const code=ts.transpileModule(await readFile(new URL('./routing-community-scoped-service.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
async function fixture(mode='prepared',failure){
|
||||
const calls=[],principal={connectionId:randomUUID(),credentialId:randomUUID(),credentialExpiresAt:new Date(Date.now()+120000).toISOString()},connection={id:principal.connectionId,owner_id:'owner',generation:'generation',owner_permissions:['mm:filters:write','mm:network:read'],policy:{mode:'copilot',permissions:['mm:filters:write','mm:network:read'],scope:{serverIds:[1]},expiresAt:new Date(Date.now()+120000).toISOString()},owner_valid_until:new Date(Date.now()+120000)};
|
||||
const profile={serverId:1,family:'ipv4',table:'tenant',probeVrf:'probe',community:'65000:10',autoRecovery:false,candidates:[{id:'a',jumpHostId:1,exitNodeId:1,gateway:'192.0.2.8',gatewayRef:{resource:'ipv4_route',id:'*r0'},controlProbe:{}},{id:'b',jumpHostId:1,exitNodeId:1,gateway:'192.0.2.9',gatewayRef:{resource:'ipv4_route',id:'*r'},controlProbe:{}}],excludedCandidateIds:[],pinnedCandidateId:null};
|
||||
const input={serverId:1,profile,candidateId:'b',principal,ownerId:'owner',policyProof:JSON.stringify(connection.policy),connectionGeneration:'generation',generation:'access',proofRevision:3,originalCandidateId:'a',nativeId:'*1',outIface:'',originalRuleCiphertext:'original',desiredRuleCiphertext:'desired',desiredTargetProof:'desired-proof',beforeRules:[],receiptId:randomUUID()};
|
||||
if(mode!=='legacy')input.originalEffectSelection=mode==='prepared'?{status:'prepared',probe:{key:'b',serverId:1,destination:'198.51.100.20',source:'198.51.100.10',interface:'wan',probeVrf:'probe'}}:{status:'unknown',reason:'unsupported-source'};
|
||||
let wrote=false,handler,network,foreign=false,reads=0,rounds=0,closed=0,ownerClosed=false,nativeCalls=100;
|
||||
const unknown=reason=>({scope:'prepared-route-fib-adjacency-control-effects',status:'unknown',reason,rounds:[],logCoverage:'unknown',semanticProof:false,forwardingVerified:false,autoRecoveryAllowed:false});
|
||||
const report={...unknown(null),status:'observed-expected',rounds:[{controlProbe:'passed'},{controlProbe:'passed'}]};
|
||||
const session={sharedContext:{},readSnapshot:async stage=>{calls.push('baseline:'+stage);return {};},readConfigurationBoundForwardSnapshot:async()=>{calls.push('round:'+(++rounds));if(failure==='round'||failure==='round-closed'){ownerClosed=failure==='round-closed';throw Error('unknown');}return {};},readBudget:()=>({deadline:Date.now()+10000,calls:nativeCalls,bytes:1000,rows:50,closed:ownerClosed}),close:()=>{closed++;ownerClosed=true;calls.push('close-session');}};
|
||||
const providers={
|
||||
'node:crypto':{randomUUID},zod:{z},'@mmapp/contracts/mcp-routing':{routeAiProfileSchema:{parse:x=>x}},'../../db/index.js':{pool:{query:async sql=>({rows:String(sql).includes('FROM mcp_path_checks')?[{id:randomUUID(),connection_id:principal.connectionId,status:'passed',created_at:new Date(),evidence:{}}]:[]})}},
|
||||
'../../lib/permissions.js':{hasPermission:(list,value)=>list.includes(value)},
|
||||
'../../services/config-mutation-policy.js':{assertVerifiedConfigurationAccess:async()=>{},executeGuardedConfigurationWrite:async(_sid,_method,_path,work)=>{calls.push('guarded-intent');return work();}},
|
||||
'../../services/config-mutation-lock.js':{withApplicationMutationLock:work=>work(),withConfigMutationLock:(_ids,work)=>work()},
|
||||
'./store.js':{effectiveMcpConnection:async()=>connection,audit:async()=>{}},
|
||||
'./security.js':{accessGeneration:async()=>'access',decryptSecret:async x=>x,encryptSecret:async x=>x,fingerprint:JSON.stringify,McpError:Error,privateSecretFingerprint:async()=>'seal',redact:x=>x},
|
||||
'./routing-community-scoped-checkpoint.js':{saveScopedConfigurationCheckpoint:async()=>{calls.push('CONFIG_APPLIED');},loadScopedConfigurationCheckpoint:async()=>({checkpointProof:'configuration'}),saveScopedNetworkCheckpoint:async(_input,_seal,check,originalEffects)=>{calls.push('save-network');network={status:check.status,networkSeal:'network',...(originalEffects?{originalEffects}:{})};},loadScopedNetworkCheckpoint:async()=>network},
|
||||
'./routing-community-scoped-request.js':{assertScopedCommunityRequest:async()=>'request'},'./management-transport.js':{prepareManagementTransportBinding:async()=>({})},
|
||||
'./routing-community-context.js':{readRouteCommunityContext:async()=>{reads++;return {before:{scopedExecutionAvailable:true,currentCandidateId:wrote?'b':'a',dependencyProof:'dep',sourceProofs:[{serverId:1,proof:'source'}]},ownedTarget:{nativeId:'*1',rawRow:{rule:wrote?'desired':'original'},endpoint:{},desiredTargetProof:()=> 'desired-proof'},fence:async()=>{},clients:new Map([[1,{get:async()=>[{'.id':'*r'}]}]]),captureOriginalEffectSelection:async()=>{calls.push('capture-prepared-selection');return input.originalEffectSelection;}};}},
|
||||
'./routing-community-context-model.js':{candidateMatchesGateway:()=>true},'./routing-model.js':{rankRoutingCandidates:()=>profile.candidates.map(candidate=>({candidate,eligible:true}))},'./routing-observations.js':{readRoutingObservations:async()=>[]},
|
||||
'./path-verification.js':{requireRecentPath:async()=>'path-check',checkCandidatePath:async()=>{calls.push('legacy-probe');return {id:randomUUID(),candidateId:'b',status:'passed',observedAt:new Date().toISOString()};}},
|
||||
'./routing-community-scoped-model.js':{compileScopedCommunitySwitch:()=>({compiledBody:'desired',proposed:{community:'65000:10',gateway:'192.0.2.9',outIface:''},before:{community:'65000:10',gateway:'192.0.2.8',outIface:''}}),scopedConfigurationMatches:()=>({configurationMatchesOriginal:!wrote,configurationMatchesDesired:wrote&&!foreign})},
|
||||
'./routing-community-scoped-native.js':{patchScopedCommunity:async()=>{calls.push('PATCH');wrote=true;}},'./service-registry.js':{registerMcpService:(_name,value)=>{handler=value;}},
|
||||
'./routing-profile-authority.js':{assertPersistentScopedProfileAuthority:async()=>{},resolveRoutingProfileAuthority:async()=>{},routingProfileAuthorityBindingSchema:{parse:x=>x},scopedProfileAuthorityTransport:async()=>({})},
|
||||
'./routing-observation-source.js':{createRoutingSourceContext:async()=>({}),readRoutingEndpoints:async()=>[]},'./routing-reservation-store.js':{createRoutingReservationStore:()=>({})},
|
||||
'./routing-network-execution-session.js':{createRoutingNetworkSessionForCurrentExecution:async options=>{calls.push('open-session');assert.deepEqual(Object.keys(options).sort(),['probes','servers']);if(failure==='open')throw Error('unknown');return session;}},
|
||||
'./routing-network-configuration-bridge.js':{resolveRoutingNetworkForwardRoundConfigurationContext:async()=>{calls.push('configuration-round-owner');return {};},closeRoutingNetworkForwardRoundConfigurationContext:()=>{calls.push('close-round-owner');}},
|
||||
'./routing-network-scoped-context.js':{readRoutingNetworkScopedCommunityContext:async()=>{calls.push('shared-publication');if(failure==='publication')throw Error('DO_NOT_EXPOSE_TEST_DETAIL');nativeCalls+=10;return{before:{dependencyProof:'dep',targetRuleProof:'desired-proof',currentCandidateId:'b'},fence:async()=>{}};}},
|
||||
'./routing-original-effects.js':{originalEffectSelectionSchema:{safeParse:x=>x?{success:true,data:x}:{success:false}},unknownOriginalEffects:unknown,originalEffectBaselineMatches:()=>failure!=='baseline',inspectOriginalEffectRounds:async()=>{calls.push('inspect-effects');if(failure==='foreign')foreign=true;return report;}}
|
||||
};
|
||||
const exports={};new Function('exports','require',code)(exports,name=>{assert.ok(providers[name],name);return providers[name];});exports.registerScopedCommunityService();
|
||||
return {calls,input,run:()=>handler.execute(input,{operationId:randomUUID(),phase:'forward',stepIndex:0}),prepare:()=>exports.prepareScopedCommunitySwitch({profile,candidateId:'b'},{principal,connection}),stats:()=>({wrote,closed,reads}),network:()=>network};
|
||||
}
|
||||
test('actual service consumer baselines before the single PATCH and persists separate effects after genuine CONFIG_APPLIED and manual probe',async()=>{const f=await fixture(),result=await f.run();const c=f.calls;assert(c.indexOf('baseline:before')<c.indexOf('PATCH'));assert(c.indexOf('CONFIG_APPLIED')<c.indexOf('configuration-round-owner'));assert(c.indexOf('legacy-probe')<c.indexOf('round:1'));assert(c.indexOf('round:2')<c.indexOf('shared-publication'));assert(c.indexOf('shared-publication')<c.indexOf('save-network'));assert.equal(c.filter(x=>x==='PATCH').length,1);assert.equal(result.configurationVerified,true);assert.equal(result.controlProbeVerified,true);assert.equal(result.forwardingVerified,false);assert.equal(result.originalEffects.status,'observed-expected');assert.equal(result.originalEffects.budget.calls,110);assert.equal(f.stats().closed,1);assert.deepEqual(result.originalEffects,f.network().originalEffects);});
|
||||
for(const mode of ['legacy','unknown'])test(`existing ${mode} manual path does not open native effect session`,async()=>{const f=await fixture(mode),result=await f.run();assert(!f.calls.includes('open-session'));assert.equal(result.configurationVerified,true);assert.equal(result.controlProbeVerified,true);assert.equal(f.calls.filter(x=>x==='PATCH').length,1);});
|
||||
for(const failure of ['open','baseline','round','round-closed','publication'])test(`optional ${failure} uncertainty preserves actual manual config/control receipt with effects unknown`,async()=>{const f=await fixture('prepared',failure),result=await f.run();assert.equal(result.configurationVerified,true);assert.equal(result.controlProbeVerified,true);assert.equal(result.originalEffects.status,'unknown');assert.equal(f.calls.filter(x=>x==='PATCH').length,1);assert(f.calls.includes('save-network'));});
|
||||
test('foreign configuration drift after optional effect observations still refuses publication, never repeats PATCH',async()=>{const f=await fixture('prepared','foreign');await assert.rejects(f.run);assert.equal(f.calls.filter(x=>x==='PATCH').length,1);assert(!f.calls.includes('save-network'));assert.equal(f.stats().closed,1);});
|
||||
test('revision2 remains on existing manual path even with a prepared-like field',async()=>{const f=await fixture();f.input.proofRevision=2;await f.run();assert(!f.calls.includes('open-session'));});
|
||||
test('actual preparation consumes the required real-context selection method and includes it in sealed service input',async()=>{const f=await fixture(),evidence=await f.prepare();assert(f.calls.includes('capture-prepared-selection'));assert.deepEqual(evidence.steps[0].input.originalEffectSelection,f.input.originalEffectSelection);assert.equal(evidence.steps[0].input.requestProof,'seal');assert(!f.calls.includes('PATCH'));});
|
||||
test('closed effect owner falls back to exactly the old final context read without bypassing publication guard',async()=>{const legacy=await fixture('legacy');await legacy.run();const f=await fixture('prepared','round-closed');await f.run();assert(!f.calls.includes('shared-publication'));assert.equal(f.stats().reads,legacy.stats().reads);});
|
||||
|
||||
test('optional publication error exposes only a bounded failure category', async()=>{
|
||||
const f=await fixture('prepared','publication'), result=await f.run();
|
||||
assert.equal(result.originalEffects.reason,'effect-publication-revalidation-unavailable:STATE_UNAVAILABLE');
|
||||
assert(!JSON.stringify(result).includes('DO_NOT_EXPOSE_TEST_DETAIL'));
|
||||
assert.equal(result.configurationVerified,true);assert.equal(result.controlProbeVerified,true);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import test from 'node:test';
|
||||
const require=createRequire(new URL('../../../package.json',import.meta.url)),ts=require('typescript'),{z}=require('zod');
|
||||
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex'),sign=async(value,purpose)=>hash([purpose,value]);
|
||||
const code=ts.transpileModule(await readFile(new URL('./routing-controller-baseline.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const effectCode=ts.transpileModule(await readFile(new URL('./routing-original-effects.ts',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText,effectExports={};
|
||||
new Function('exports','require',effectCode)(effectExports,name=>{if(name==='node:net')return require('node:net');if(name==='zod')return{z};if(name==='./security.js')return{fingerprint:hash};if(name==='./routing-community-context-model.js')return{};throw Error(name);});
|
||||
const preparedValue={status:'prepared',revision:1,serverId:1,routeSelectionScope:'table-afi-community-observation',candidateId:'b',family:'ipv4',table:'tenant',community:'65000:10',expectedGateway:'192.0.2.9',expectedImmediate:{address:'198.51.100.2',interface:'ether2'},binding:{connectionId:'*c',sessionId:'*s',instance:'default',table:'tenant',vrf:'main',localAddress:'192.0.2.1',remoteAddress:'192.0.2.2',remoteAsn:65001,afi:'ip'},bfd:{applicability:'not-configured',evidence:'explicit-use-bfd-false'},routes:[{nativeId:'*r',prefix:'203.0.113.0/24',originalGateway:'192.0.2.8'}],probe:{key:'b',serverId:1,destination:'198.51.100.20',source:'198.51.100.10',interface:'wan',probeVrf:'probe',expectedHops:['198.51.100.20']}};
|
||||
async function fixture(selection='absent',effectStatus='observed-expected',switched=true){
|
||||
const principal={connectionId:randomUUID(),credentialId:randomUUID(),credentialExpiresAt:new Date(Date.now()+120000).toISOString()},profileId=randomUUID(),planId=randomUUID(),operationId=randomUUID(),grant=new Date(Date.now()+60000).toISOString();
|
||||
const profile={serverId:1,table:'tenant',probeVrf:'probe',candidates:[{id:'a',jumpHostId:1,exitNodeId:1},{id:'b',jumpHostId:1,exitNodeId:1}]},perms=['mm:network:read','mm:network:write','mm:filters:write'];
|
||||
const connection={id:principal.connectionId,owner_id:'owner',owner_permissions:perms,owner_valid_until:new Date(Date.now()+120000),owner_claims_issued_at:new Date(Date.now()-1000),generation:'access',policy:{status:'active',mode:'copilot',permissions:perms,scope:{serverIds:[1],operationIds:['routing.analyze','routing.community.switch','routing.path.verify']},expiresAt:new Date(Date.now()+120000).toISOString()}};
|
||||
const context={principal,connection},sourceProofs=[{serverId:1,proof:'c'.repeat(64)}],dependency='d'.repeat(64),originalTarget='a'.repeat(64),desiredTarget='b'.repeat(64),checkpointProof='e'.repeat(64),networkSeal='f'.repeat(64),requestSeal='1'.repeat(64);
|
||||
let advancing=false,nativeReads=0,row;
|
||||
const input={proofRevision:3,profile,principal,ownerId:'owner',nativeId:'*1',originalCandidateId:'a',originalTargetProof:originalTarget,desiredTargetProof:desiredTarget,dependencyProof:dependency,contextSources:sourceProofs,candidateId:'b',receiptId:randomUUID(),persistentProfileAuthority:{packet:{profileId,profileVersion:1}}};
|
||||
if(selection!=='absent')input.originalEffectSelection=selection?.status==='prepared'&&Object.keys(selection).length===1?structuredClone(preparedValue):selection;
|
||||
const packet={revision:2,operationId,stepIndex:0,nativeId:'*1',originalCandidateId:'a',originalTargetProof:originalTarget,dependencyProof:dependency,contextSources:sourceProofs,desiredCandidateId:'b',desiredTargetProof:desiredTarget,desiredRule:'desired'};
|
||||
const network={status:'passed',networkSeal,...(effectStatus==='missing'?{}:{originalEffects:{status:effectStatus,switchEffectObserved:switched,selectionIdentity:hash(input.originalEffectSelection??null),transition:{changedPrefixes:switched?['203.0.113.0/24']:[]}}})};
|
||||
const providers={
|
||||
'./routing-main-transition.js':{},'../../db/index.js':{pool:{query:async()=>({rows:[row]})}},'./registry.js':{findMcpOperation:()=>({version:7})},
|
||||
'./routing-community-scoped-request.js':{assertScopedCommunityRequest:async()=>requestSeal},'./routing-profile-authority.js':{assertPersistentScopedProfileAuthority:async()=>{},routingProfileAuthorityBindingSchema:{parse:x=>x}},
|
||||
'./routing-community-scoped-checkpoint.js':{loadScopedConfigurationPacket:async()=>({packet,checkpointProof,observedAt:new Date(Date.now()-500).toISOString()}),loadScopedNetworkCheckpoint:async()=>network},
|
||||
zod:{z},'@mmapp/contracts/mcp-routing':{routeAiProfileSchema:{parse:x=>x}},'../../lib/permissions.js':{hasPermission:(list,value)=>list.includes(value)},'./store.js':{effectiveMcpConnection:async()=>connection},
|
||||
'./security.js':{accessGeneration:async()=>'access',constantEqual:(a,b)=>a===b,decryptSecret:async x=>x,fingerprint:hash,redact:x=>x,McpError:Error,privateSecretFingerprint:sign},
|
||||
'./routing-community-context.js':{readRouteCommunityContext:async()=>{nativeReads++;return {before:{scopedExecutionAvailable:true,currentCandidateId:advancing?'b':'a',targetRuleProof:advancing?desiredTarget:originalTarget,dependencyProof:dependency,sourceProofs,nativeRuleId:'*1'},ownedTarget:{nativeId:'*1',rawRow:{rule:advancing?'desired':'original'}},fence:async()=>{}};}},
|
||||
'./routing-original-effects.js':{originalEffectSelectionSchema:effectExports.originalEffectSelectionSchema}
|
||||
};
|
||||
const exports={};new Function('exports','require',code)(exports,name=>{assert.ok(providers[name],name);return providers[name];});
|
||||
const baseline=await exports.prepareRoutingControllerBaseline(profileId,1,profile,grant,context);advancing=true;
|
||||
const step={kind:'service',service:'routing.community.scoped',input};
|
||||
row={id:operationId,plan_id:planId,state:'applied',step_state:'verified',operation_id:'routing.community.switch',operation_version:7,approved_by:'owner',created_at:new Date(Date.now()-1000),evidence:{sealed:JSON.stringify({steps:[step],target:{scope:'servers',serverIds:[1]}})},intended_state:step};
|
||||
row.result={nativeVerificationSeal:await sign(hash({request:requestSeal,dependency,desired:desiredTarget,candidate:'b',configuration:checkpointProof,network:networkSeal}),'route-ai-scoped-verified-v3'),configurationCheckpointProof:checkpointProof,networkCheckpointProof:networkSeal,receiptId:input.receiptId,proofRevision:3,nativeWrites:1,configurationVerified:true,postProbeStatus:'passed',controlProbeVerified:true};
|
||||
return {advance:()=>exports.advanceRoutingControllerBaseline(baseline,profileId,1,profile,grant,context,planId,operationId),nativeReads:()=>nativeReads,row,network};
|
||||
}
|
||||
test('actual controller preserves old advancement only when new selection field is absent',async()=>{const f=await fixture();assert.equal((await f.advance()).packet.candidateId,'b');assert.equal(f.nativeReads(),2);});
|
||||
for(const [name,selection]of[['unknown',{status:'unknown',reason:'unsupported'}],['malformed',{}],['malformed prepared',{status:'prepared',revision:2}],['null',null],['array',[]]])test(`actual controller rejects present ${name} before desired native read`,async()=>{const f=await fixture(selection);await assert.rejects(f.advance);assert.equal(f.nativeReads(),1);assert.equal(f.row.result.configurationVerified,true);assert.equal(f.row.result.controlProbeVerified,true);});
|
||||
for(const status of ['unknown','observed-other','missing'])test(`actual controller rejects prepared selection with ${status} durable effect result`,async()=>{const f=await fixture({status:'prepared'},status);await assert.rejects(f.advance);assert.equal(f.nativeReads(),1);});
|
||||
test('actual controller rejects matched poststate without an observed selected FIB transition',async()=>{const f=await fixture({status:'prepared'},'observed-expected',false);await assert.rejects(f.advance);assert.equal(f.nativeReads(),1);});
|
||||
test('actual controller advances after durable expected selected FIB transition',async()=>{const f=await fixture({status:'prepared'});assert.equal((await f.advance()).packet.candidateId,'b');assert.equal(f.nativeReads(),2);});
|
||||
test('actual controller rejects effect vector belonging to a different prepared selection',async()=>{const f=await fixture({status:'prepared'});f.network.originalEffects.selectionIdentity='0'.repeat(64);await assert.rejects(f.advance);assert.equal(f.nativeReads(),1);});
|
||||
test('actual controller rejects transition flag without an actual changed selected prefix',async()=>{const f=await fixture({status:'prepared'});f.network.originalEffects.transition.changedPrefixes=[];await assert.rejects(f.advance);assert.equal(f.nativeReads(),1);});
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
import { isIP } from 'node:net';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
const require=createRequire(new URL('../../../package.json',import.meta.url)), ts=require('typescript'),{z}=require('zod');
|
||||
const source=await readFile(new URL('./routing-original-effects.ts',import.meta.url),'utf8');
|
||||
const exports={};
|
||||
const gateway=value=>{const match=/^([^@%\s,]+)(?:%([^@%\s,]+))?(?:@([^@%\s,]+))?$/.exec(value);if(!match||!isIP(match[1]))throw Error();return {address:match[1],family:isIP(match[1]),interface:match[2]??null,resolverTable:match[3]??'main'};};
|
||||
const providers={ 'node:net':{isIP},'node:crypto':{randomUUID},zod:{z},'./routing-community-context-model.js':{routeGatewayContext:gateway},'./security.js':{fingerprint:value=>createHash('sha256').update(JSON.stringify(value)).digest('hex')},
|
||||
'./path-verification.js':{inspectControlPing:rows=>{const row=rows.at(-1),sent=Number(row.sent),received=Number(row.received);return {confirmedFailure:sent===3&&received===0,ping:{measured:sent===3&&Number.isInteger(received)&&received>=0&&received<=3,loss:(sent-received)/sent*100}};},
|
||||
inspectTrace:(rows,destination,expected)=>({verified:Array.isArray(rows)&&rows.at(-1)?.address===destination&&expected.every(x=>rows.some(r=>r.address===x))})}};
|
||||
new Function('exports','require',ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText)(exports,name=>{assert.ok(providers[name],name);return providers[name];});
|
||||
function fixture(){
|
||||
const profile={serverId:1,family:'ipv4',table:'tenant',probeVrf:'probe',community:'65000:10',candidates:[{id:'b',wanInterface:'wan',gateway:'192.0.2.9',gatewayRef:{resource:'ipv4_route',id:'*9'},controlProbe:{targetInterface:'target'}}]};
|
||||
const binding={connectionId:'*c',instance:'default',table:'tenant',vrf:'main'};
|
||||
const connection={'.id':'*c',instance:'default','routing-table':'tenant',vrf:'main','local.address':'192.0.2.1','remote.address':'192.0.2.2','remote.as':'65001',afi:'ip',templates:'',disabled:'false','use-bfd':'false'};
|
||||
const session={...connection,'.id':'*s','local.afi':'ip','remote.afi':'ip',established:'true'};
|
||||
const route={'.id':'*r',afi:'ip4','routing-table':'tenant','dst-address':'203.0.113.0/24',bgp:'true','bgp.communities':'65000:10',gateway:'192.0.2.8',active:'true',contribution:'active',ecmp:'false','immediate-gw':'198.51.100.1%ether1'};
|
||||
const raw={connections:[connection],sessions:[session],routes:[route],candidate:{'.id':'*9','immediate-gw':'198.51.100.2%ether2'},probe:{source:'198.51.100.10',destination:'198.51.100.20',expected:['198.51.100.20']}};
|
||||
const selection=exports.prepareOriginalEffectSelection(profile,'b',binding,raw);
|
||||
const sample=()=>({observedAt:new Date().toISOString(),servers:[{serverId:1,routes:{payload:[{...route,gateway:'192.0.2.9','immediate-gw':'198.51.100.2%ether2'}]},bgp:{payload:[{...session}],connectionsPayload:[{...connection}]},logs:{payload:[{topics:'route,info',message:'bounded diagnostic'}]}}],probes:[{key:'b',pingPayload:[{sent:'3',received:'3','packet-loss':'0'}],tracePayload:[{address:'198.51.100.20'}]}]});
|
||||
const baseline=sample();baseline.servers[0].routes.payload=structuredClone(raw.routes);
|
||||
return {profile,binding,raw,selection,sample,baseline,prepare:()=>exports.prepareOriginalEffectSelection(profile,'b',binding,raw),inspect:samples=>exports.inspectOriginalEffectRounds(selection,samples,baseline)};
|
||||
}
|
||||
test('actual captured predicate seals BGP destinations separately from static resolver ID',()=>{const f=fixture();assert.equal(f.selection.status,'prepared');assert.equal(f.selection.routes[0].nativeId,'*r');assert.notEqual(f.selection.routes[0].nativeId,f.raw.candidate['.id']);assert.equal(f.selection.binding.sessionId,'*s');assert.equal('sessionKey'in f.selection.routes[0],false);});
|
||||
test('two real effect captures can observe expected FIB/adjacency/probe while logcoverage and stronger claims stay false',async()=>{const f=fixture(),result=await f.inspect([f.sample(),f.sample()]);assert.equal(result.status,'observed-expected');assert.equal(result.logCoverage,'unknown');assert.equal(result.routeOriginVerified,false);assert.equal(result.recursiveChainVerified,false);assert.equal(result.forwardingVerified,false);assert.equal(result.autoRecoveryAllowed,false);assert.equal(result.rounds[0].relatedTopicRows,1);});
|
||||
for(const [name,change]of[
|
||||
['missing affected BGP route',f=>{f.raw.routes=[];}],['ambiguous prefix',f=>{f.raw.routes.push({...f.raw.routes[0],'.id':'*r2'});}],
|
||||
['connected resolver is not affected BGP route',f=>{f.raw.routes[0].bgp='false';f.raw.routes[0].connect='true';}],
|
||||
['unresolved inheritance',f=>{f.raw.connections[0].templates='template';}],['BFD not explicitly known',f=>{delete f.raw.connections[0]['use-bfd'];}],
|
||||
['router-selected source retained as unsupported effect subset',f=>{delete f.raw.probe.source;}],['mixed session identity',f=>{f.raw.sessions.push({...f.raw.sessions[0],'.id':'*s2'});}],
|
||||
['noncanonical AFI prefix',f=>{f.raw.routes[0]['dst-address']='2001:db8::/64';}]
|
||||
])test(`prepared ambiguity/unsupported remains unknown: ${name}`,()=>{const f=fixture();change(f);assert.equal(f.prepare().status,'unknown');});
|
||||
test('baseline binds saved route IDs/prefix/gateway and does not infer operation UUID',()=>{const f=fixture(),base=f.sample();base.servers[0].routes.payload=structuredClone(f.raw.routes);assert.equal(exports.originalEffectBaselineMatches(f.selection,base),true);base.servers[0].routes.payload[0]['.id']='*different';assert.equal(exports.originalEffectBaselineMatches(f.selection,base),false);});
|
||||
for(const [name,change,expected]of[
|
||||
['unexpected immediate next-hop',s=>{s.servers[0].routes.payload[0]['immediate-gw']='198.51.100.3%ether3';},'observed-other'],
|
||||
['unchanged connected route',s=>{s.servers[0].routes.payload[0].bgp='false';s.servers[0].routes.payload[0].connect='true';},'unknown'],
|
||||
['same prefix competition',s=>{s.servers[0].routes.payload.push({...s.servers[0].routes.payload[0],'.id':'*other'});},'unknown'],
|
||||
['new community target scope',s=>{s.servers[0].routes.payload.push({...s.servers[0].routes.payload[0],'.id':'*other','dst-address':'203.0.114.0/24'});},'unknown'],
|
||||
['reconnected session ID',s=>{s.servers[0].bgp.payload[0]['.id']='*new';},'unknown'],
|
||||
['observed adjacency down',s=>{s.servers[0].bgp.payload[0].established='false';},'observed-other'],
|
||||
['BFD applicability changed',s=>{s.servers[0].bgp.connectionsPayload[0]['use-bfd']='true';},'unknown'],
|
||||
['unreachable route',s=>{s.servers[0].routes.payload[0].unreachable='true';},'unknown'],
|
||||
['terminal control loss',s=>{s.probes[0].pingPayload=[{sent:'3',received:'0','packet-loss':'100'}];},'observed-other']
|
||||
])test(`effect observation: ${name}`,async()=>{const f=fixture(),s=f.sample();change(s);const result=await f.inspect([s,structuredClone(s)]);assert.equal(result.status,expected);assert.equal(result.forwardingVerified,false);});
|
||||
test('one round is not upgraded to two',async()=>{const f=fixture();assert.equal((await f.inspect([f.sample()])).status,'unknown');});
|
||||
test('unchanged expected poststate is not labelled a switch effect',async()=>{const f=fixture();f.baseline.servers[0].routes.payload[0].gateway=f.selection.expectedGateway;f.baseline.servers[0].routes.payload[0]['immediate-gw']='198.51.100.2%ether2';f.selection.routes[0].originalGateway=f.selection.expectedGateway;const result=await f.inspect([f.sample(),f.sample()]);assert.equal(result.status,'unknown');assert.equal(result.switchEffectObserved,false);assert.deepEqual(result.transition.changedPrefixes,[]);assert.equal(result.reason,'poststate-matched-without-selected-fib-transition');});
|
||||
test('actual selected destination gateway/final endpoint transition is recorded separately from origin',async()=>{const f=fixture(),result=await f.inspect([f.sample(),f.sample()]);assert.equal(result.status,'observed-expected');assert.equal(result.switchEffectObserved,true);assert.deepEqual(result.transition.changedPrefixes,['203.0.113.0/24']);assert.equal(result.transition.baselineObservedAt,f.baseline.observedAt);assert.equal(result.routeOriginVerified,false);});
|
||||
test('logical gateway change with unchanged final forwarding endpoint is not a FIB switch',async()=>{const f=fixture();f.baseline.servers[0].routes.payload[0]['immediate-gw']='198.51.100.2%ether2';const result=await f.inspect([f.sample(),f.sample()]);assert.equal(result.status,'unknown');assert.equal(result.switchEffectObserved,false);assert.equal(result.routeSelectionScope,'table-afi-community-observation');assert.equal(result.transitionAttribution,'unproven');assert.deepEqual(result.transition.changedPrefixes,[]);});
|
||||
@@ -0,0 +1,174 @@
|
||||
import { isIP } from "node:net"
|
||||
import { z } from "zod"
|
||||
import type { RouteAiProfile } from "@mmapp/contracts/mcp-routing"
|
||||
import { routeGatewayContext } from "./routing-community-context-model.js"
|
||||
import { fingerprint } from "./security.js"
|
||||
|
||||
type Row = Record<string, unknown>
|
||||
const id = z.string().regex(/^\*[a-z0-9]+$/i).max(100)
|
||||
const text = z.string().min(1).max(200)
|
||||
const ip = text.refine(value => isIP(value) !== 0)
|
||||
const flag = (value: unknown): boolean | undefined => [true, "true", "yes"].includes(value as string | boolean) ? true : [false, "false", "no"].includes(value as string | boolean) ? false : undefined
|
||||
const communities = (row: Row) => Array.isArray(row["bgp.communities"]) ? row["bgp.communities"] as unknown[] : typeof row["bgp.communities"] === "string" ? row["bgp.communities"].split(",") : []
|
||||
const family = (row: Row) => ["ip", "ip4"].includes(String(row.afi)) ? "ipv4" : ["ipv6", "ip6"].includes(String(row.afi)) ? "ipv6" : null
|
||||
const unique = (rows: Row[], nativeId: string) => rows.filter(row => row[".id"] === nativeId)
|
||||
const tupleSchema = z.object({ connectionId: id, sessionId: id, instance: text, table: text, vrf: text,
|
||||
localAddress: ip, remoteAddress: ip, remoteAsn: z.number().int().positive().max(4294967295), afi: z.enum(["ip", "ipv6"]) }).strict()
|
||||
const prepared = z.object({ status: z.literal("prepared"), revision: z.literal(1), serverId: z.number().int().positive(),
|
||||
routeSelectionScope: z.literal("table-afi-community-observation"),
|
||||
candidateId: text, family: z.enum(["ipv4", "ipv6"]), table: text, community: text, expectedGateway: text,
|
||||
expectedImmediate: z.object({ address: ip, interface: text }).strict(), binding: tupleSchema,
|
||||
bfd: z.object({ applicability: z.literal("not-configured"), evidence: z.literal("explicit-use-bfd-false") }).strict(),
|
||||
routes: z.array(z.object({ nativeId: id, prefix: text, originalGateway: text }).strict()).min(1).max(32),
|
||||
probe: z.object({ key: text, serverId: z.number().int().positive(), destination: ip, source: ip, interface: text, probeVrf: text,
|
||||
expectedHops: z.array(ip).min(1).max(8) }).strict(),
|
||||
}).strict()
|
||||
export const originalEffectSelectionSchema = z.union([prepared, z.object({ status: z.literal("unknown"), reason: text }).strict()])
|
||||
export type OriginalEffectSelection = z.infer<typeof originalEffectSelectionSchema>
|
||||
type Prepared = z.infer<typeof prepared>
|
||||
const state = z.enum(["observed-expected", "observed-other", "unknown"])
|
||||
const roundSchema = z.object({ observedAt: z.string().datetime(), routes: z.array(z.object({ prefix: text, status: state }).strict()).max(32),
|
||||
bgp: state, bfd: z.enum(["not-configured", "unknown"]), controlProbe: z.enum(["passed", "failed", "unknown"]),
|
||||
relatedTopicRows: z.number().int().nonnegative().max(1000) }).strict()
|
||||
export const originalEffectReportSchema = z.object({ scope: z.literal("prepared-route-fib-adjacency-control-effects"), status: state,
|
||||
reason: text.nullable(), rounds: z.array(roundSchema).max(3), logSource: z.literal("routeros-rest-ring"), logCoverage: z.literal("unknown"),
|
||||
selectionIdentity: z.string().regex(/^[a-f0-9]{64}$/).nullable(),
|
||||
routeSelectionScope: z.literal("table-afi-community-observation"), transitionAttribution: z.literal("unproven"),
|
||||
switchEffectObserved: z.boolean(),
|
||||
transition: z.object({ baselineObservedAt: z.string().datetime(), changedPrefixes: z.array(text).max(32) }).strict().optional(),
|
||||
budget: z.object({ deadline: z.number().int().positive(), calls: z.number().int().nonnegative().max(256), bytes: z.number().int().nonnegative().max(8 * 1048576),
|
||||
rows: z.number().int().nonnegative().max(10000) }).strict().optional(),
|
||||
semanticProof: z.literal(false), routeOriginVerified: z.literal(false), recursiveChainVerified: z.literal(false), forwardingVerified: z.literal(false), autoRecoveryAllowed: z.literal(false) }).strict()
|
||||
export type OriginalEffectReport = z.infer<typeof originalEffectReportSchema>
|
||||
export const unknownOriginalEffects = (reason: string): OriginalEffectReport => ({ scope: "prepared-route-fib-adjacency-control-effects", status: "unknown", reason,
|
||||
rounds: [], logSource: "routeros-rest-ring", logCoverage: "unknown", selectionIdentity: null, routeSelectionScope: "table-afi-community-observation", transitionAttribution: "unproven", switchEffectObserved: false, semanticProof: false, routeOriginVerified: false, recursiveChainVerified: false, forwardingVerified: false, autoRecoveryAllowed: false })
|
||||
|
||||
function tuple(row: Row, expected: Prepared["binding"], session: boolean) {
|
||||
return row.instance === expected.instance && row["routing-table"] === expected.table && row.vrf === expected.vrf &&
|
||||
row["local.address"] === expected.localAddress && row["remote.address"] === expected.remoteAddress && Number(row["remote.as"]) === expected.remoteAsn &&
|
||||
(session ? row["local.afi"] === expected.afi && row["remote.afi"] === expected.afi : row.afi === expected.afi)
|
||||
}
|
||||
function selectedRows(rows: Row[], selection: Pick<Prepared, "table" | "family" | "community">) {
|
||||
return rows.filter(row => row["routing-table"] === selection.table && family(row) === selection.family && flag(row.bgp) === true && communities(row).includes(selection.community))
|
||||
}
|
||||
|
||||
/** Called only by the real private context reader. This selects observed route
|
||||
* effects by table/AFI/Community, never a route→session provenance relationship.
|
||||
* The initial bounded subset requires explicit flat peer identity, explicit
|
||||
* BFD-off and an already configured explicit probe source. Other manual paths
|
||||
* keep their existing configuration/probe behavior, with effects unknown. */
|
||||
export function prepareOriginalEffectSelection(profile: RouteAiProfile, candidateId: string, binding: { connectionId: string; instance: string | null; vrf: string; table: string } | null,
|
||||
raw: { routes: Row[]; connections: Row[]; sessions: Row[]; candidate: Row | undefined; probe: { destination: string; expected: string[]; source?: string } | undefined }): OriginalEffectSelection {
|
||||
try {
|
||||
if (!binding || !binding.instance) throw Error()
|
||||
const candidate = profile.candidates.find(value => value.id === candidateId), probe = raw.probe
|
||||
if (!candidate?.controlProbe || !probe?.source || !raw.candidate) throw Error()
|
||||
const connection = unique(raw.connections, binding.connectionId)
|
||||
if (connection.length !== 1 || !(connection[0].templates === "" || Array.isArray(connection[0].templates) && connection[0].templates.length === 0) ||
|
||||
flag(connection[0].disabled) !== false || flag(connection[0]["use-bfd"]) !== false) throw Error()
|
||||
const peer = connection[0], afi = profile.family === "ipv4" ? "ip" : "ipv6"
|
||||
const wanted = tupleSchema.parse({ connectionId: peer[".id"], sessionId: "*0", instance: binding.instance, table: binding.table, vrf: binding.vrf,
|
||||
localAddress: peer["local.address"], remoteAddress: peer["remote.address"], remoteAsn: Number(peer["remote.as"]), afi })
|
||||
if (!tuple(peer, wanted, false)) throw Error()
|
||||
const sessions = raw.sessions.filter(row => tuple(row, wanted, true))
|
||||
if (sessions.length !== 1 || flag(sessions[0].established) === undefined) throw Error()
|
||||
wanted.sessionId = id.parse(sessions[0][".id"])
|
||||
const affected = selectedRows(raw.routes, profile)
|
||||
if (!affected.length || affected.length > 32 || new Set(affected.map(row => row["dst-address"])).size !== affected.length || new Set(affected.map(row => row[".id"])).size !== affected.length) throw Error()
|
||||
for (const row of affected) {
|
||||
const [address, mask, extra] = String(row["dst-address"]).split("/")
|
||||
if (extra !== undefined || isIP(address) !== (profile.family === "ipv4" ? 4 : 6) || !/^\d+$/.test(mask ?? "") || Number(mask) > (profile.family === "ipv4" ? 32 : 128)) throw Error()
|
||||
routeGatewayContext(String(row.gateway))
|
||||
}
|
||||
// A selected destination cannot silently choose among competing origins.
|
||||
if (affected.some(row => raw.routes.filter(other => other["routing-table"] === profile.table && other["dst-address"] === row["dst-address"]).length !== 1)) throw Error()
|
||||
const endpoint = candidate.gatewayRef.resource === "gre" ? { address: routeGatewayContext(candidate.gateway).address, interface: String(raw.candidate.name) } : routeGatewayContext(String(raw.candidate["immediate-gw"]))
|
||||
if (!endpoint.interface) throw Error()
|
||||
return prepared.parse({ status: "prepared", revision: 1, serverId: profile.serverId, candidateId, family: profile.family, table: profile.table,
|
||||
routeSelectionScope: "table-afi-community-observation",
|
||||
community: profile.community, expectedGateway: candidate.gateway, expectedImmediate: { address: endpoint.address, interface: endpoint.interface }, binding: wanted,
|
||||
bfd: { applicability: "not-configured", evidence: "explicit-use-bfd-false" },
|
||||
routes: affected.map(row => ({ nativeId: row[".id"], prefix: row["dst-address"], originalGateway: row.gateway })).sort((a, b) => String(a.prefix).localeCompare(String(b.prefix))),
|
||||
probe: { key: candidateId, serverId: profile.serverId, destination: probe.destination, source: probe.source, interface: candidate.wanInterface,
|
||||
probeVrf: profile.probeVrf, expectedHops: probe.expected } })
|
||||
} catch { return { status: "unknown", reason: "prepared-effect-selection-unsupported-or-ambiguous" } }
|
||||
}
|
||||
|
||||
type Snapshot = { observedAt: string; servers: Array<{ serverId: number; routes: { payload: Row[] }; bgp: { payload: Row[]; connectionsPayload: Row[] }; logs: { payload: Row[] } }>;
|
||||
probes: Array<{ key: string; pingPayload: Row[]; tracePayload?: Row[] }> }
|
||||
export function originalEffectBaselineMatches(selection: Prepared, sample: Snapshot) {
|
||||
const source = sample.servers.find(row => row.serverId === selection.serverId)
|
||||
if (!source) return false
|
||||
const actual = selectedRows(source.routes.payload, selection)
|
||||
return actual.length === selection.routes.length && selection.routes.every(wanted => actual.filter(row => row[".id"] === wanted.nativeId && row["dst-address"] === wanted.prefix && row.gateway === wanted.originalGateway).length === 1)
|
||||
}
|
||||
|
||||
/** Actual bounded native captures only; all stronger causal/whole-path claims
|
||||
* remain false. Related log inspection is reported without completeness. */
|
||||
export async function inspectOriginalEffectRounds(rawSelection: unknown, samples: Snapshot[], baseline: Snapshot) {
|
||||
const selection = prepared.parse(rawSelection), rounds: z.infer<typeof roundSchema>[] = []
|
||||
if (!originalEffectBaselineMatches(selection, baseline)) return unknownOriginalEffects("prepared-effect-baseline-drift")
|
||||
const { inspectControlPing, inspectTrace } = await import("./path-verification.js")
|
||||
for (const sample of samples) {
|
||||
const source = sample.servers.find(row => row.serverId === selection.serverId)
|
||||
if (!source) return unknownOriginalEffects("effect-source-missing")
|
||||
const scope = selectedRows(source.routes.payload, selection)
|
||||
const scopeChanged = fingerprint(scope.map(row => row["dst-address"]).sort()) !== fingerprint(selection.routes.map(row => row.prefix).sort())
|
||||
const routes = selection.routes.map(wanted => {
|
||||
const matching = source.routes.payload.filter(row => row["routing-table"] === selection.table && row["dst-address"] === wanted.prefix && family(row) === selection.family)
|
||||
let status: z.infer<typeof state> = "unknown"
|
||||
if (!scopeChanged && matching.length === 1) {
|
||||
const row = matching[0]
|
||||
if (flag(row.bgp) === true && flag(row.connect) !== true && flag(row.static) !== true && flag(row.active) !== undefined && row.ecmp !== undefined && flag(row.ecmp) === false &&
|
||||
["disabled", "filtered", "unreachable", "blackhole", "invalid"].every(key => row[key] === undefined || flag(row[key]) === false)) {
|
||||
try {
|
||||
const final = routeGatewayContext(String(row["immediate-gw"]))
|
||||
status = flag(row.active) === true && row.contribution === "active" && row.gateway === selection.expectedGateway && final.address === selection.expectedImmediate.address && final.interface === selection.expectedImmediate.interface ? "observed-expected" : "observed-other"
|
||||
} catch { /* no final resolution evidence */ }
|
||||
}
|
||||
}
|
||||
return { prefix: wanted.prefix, status }
|
||||
})
|
||||
const connections = unique(source.bgp.connectionsPayload, selection.binding.connectionId)
|
||||
const sessions = source.bgp.payload.filter(row => tuple(row, selection.binding, true))
|
||||
let bgp: z.infer<typeof state> = "unknown"
|
||||
if (connections.length === 1 && tuple(connections[0], selection.binding, false) && flag(connections[0].disabled) === false && flag(connections[0]["use-bfd"]) === false &&
|
||||
sessions.length === 1 && sessions[0][".id"] === selection.binding.sessionId && flag(sessions[0].established) !== undefined) bgp = flag(sessions[0].established) ? "observed-expected" : "observed-other"
|
||||
const probe = sample.probes.find(row => row.key === selection.probe.key)
|
||||
let controlProbe: "passed" | "failed" | "unknown" = "unknown"
|
||||
if (probe) {
|
||||
const ping = inspectControlPing(z.array(z.record(z.string(), z.string())).max(256).parse(probe.pingPayload))
|
||||
if (ping.confirmedFailure) controlProbe = "failed"
|
||||
else if (ping.ping.measured && ping.ping.loss === 0 && inspectTrace(probe.tracePayload, selection.probe.destination, selection.probe.expectedHops).verified) controlProbe = "passed"
|
||||
}
|
||||
rounds.push(roundSchema.parse({ observedAt: sample.observedAt, routes, bgp,
|
||||
bfd: connections.length === 1 && flag(connections[0]["use-bfd"]) === false ? "not-configured" : "unknown", controlProbe,
|
||||
relatedTopicRows: source.logs.payload.filter(row => typeof row.topics === "string" && row.topics.split(",").some(topic => ["bgp", "bfd", "route", "interface"].includes(topic))).length }))
|
||||
}
|
||||
if (rounds.length !== 2) return unknownOriginalEffects("two-effect-rounds-required")
|
||||
const all = rounds.flatMap(round => [...round.routes.map(route => route.status), round.bgp, round.bfd === "unknown" ? "unknown" : "observed-expected", round.controlProbe === "passed" ? "observed-expected" : round.controlProbe === "failed" ? "observed-other" : "unknown"])
|
||||
const before = baseline.servers.find(row => row.serverId === selection.serverId)!
|
||||
// Native IDs alone may churn; they never count as a forwarding transition.
|
||||
// Require an actual selected active destination's final forwarding endpoint
|
||||
// to differ from the expected post-state seen consistently in both rounds.
|
||||
// A changed logical gateway resolving to the SAME endpoint is not a FIB switch.
|
||||
const changedPrefixes = selection.routes.filter(wanted => {
|
||||
if (!rounds.every(round => round.routes.find(row => row.prefix === wanted.prefix)?.status === "observed-expected")) return false
|
||||
const row = before.routes.payload.find(row => row[".id"] === wanted.nativeId && row["dst-address"] === wanted.prefix)!
|
||||
if (flag(row.bgp) !== true || flag(row.active) !== true || row.contribution !== "active" || flag(row.connect) === true || flag(row.static) === true || flag(row.ecmp) !== false ||
|
||||
["disabled", "filtered", "unreachable", "blackhole", "invalid"].some(key => row[key] !== undefined && flag(row[key]) !== false)) return false
|
||||
try {
|
||||
const endpoint = routeGatewayContext(String(row["immediate-gw"]))
|
||||
routeGatewayContext(String(row.gateway))
|
||||
if (!endpoint.interface) return false
|
||||
return endpoint.address !== selection.expectedImmediate.address || endpoint.interface !== selection.expectedImmediate.interface
|
||||
} catch { return false }
|
||||
}).map(row => row.prefix)
|
||||
const postState = all.includes("unknown") ? "unknown" : all.includes("observed-other") ? "observed-other" : "observed-expected"
|
||||
return originalEffectReportSchema.parse({ ...unknownOriginalEffects(""), rounds, reason: null,
|
||||
selectionIdentity: fingerprint(selection),
|
||||
transition: { baselineObservedAt: baseline.observedAt, changedPrefixes }, switchEffectObserved: postState === "observed-expected" && changedPrefixes.length > 0,
|
||||
status: postState === "observed-expected" && !changedPrefixes.length ? "unknown" : postState,
|
||||
...(postState === "observed-expected" && !changedPrefixes.length ? { reason: "poststate-matched-without-selected-fib-transition" } : {}) })
|
||||
}
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
import { assertOwnedRoutingReservationSql, acceptRoutingReservationSql } from "./routing-reservation.sql-helper.js"
|
||||
|
||||
assertOwnedRoutingReservationSql()
|
||||
process.env.AUTH_REQUIRED = "true"
|
||||
process.env.AUTH_JWT_SECRET = "owned-routing-mixed-writer-acceptance-secret"
|
||||
process.env.AUTH_ISSUER = "https://owned-routing-mixed-writer.test"
|
||||
const { pool, closePool } = await import("../../db/index.js")
|
||||
try {
|
||||
const { applySqlMigrations } = await import("../../db/migrate.js")
|
||||
await applySqlMigrations(pool)
|
||||
console.log("private routing reservation runtime admission SQL acceptance:", JSON.stringify(await acceptRoutingReservationSql({ runtimeAdmission: true })))
|
||||
} finally { await closePool() }
|
||||
const actor = { id: "owned-routing-mixed-writer", email: "[email protected]", name: "Owned mixed writer",
|
||||
apps: ["mm"], permissions: ["mm:settings:admin", "mm:mcp:admin", "mm:mcp:approve", "mm:network:read", "mm:network:write", "mm:filters:write", "mm:servers:admin"],
|
||||
issuedAt: Date.now() - 1000, expiresAt: Date.now() + 900000 }
|
||||
await (await import("./store.js")).updateMcpSettings({ enabled: true }, actor)
|
||||
await import("./actions.js")
|
||||
const mixed = await (await import("./routing-community-scoped-acceptance.js")).acceptScopedRouteCommunitySwitch(actor,
|
||||
{ manualInverseChargeOnly: true, manualInverseChargeCase: "mixed-forward" })
|
||||
console.log("private routing mixed forward/manual inverse admission SQL acceptance:", JSON.stringify(mixed))
|
||||
} finally {
|
||||
await (await import("../../services/scheduler.js")).stopSchedulerForDatabaseOperation()
|
||||
await closePool()
|
||||
}
|
||||
Reference in new issue
Block a user