74 lines
7.4 KiB
TypeScript
74 lines
7.4 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import test from "node:test"
|
|
import { readFile } from "node:fs/promises"
|
|
import { randomUUID } from "node:crypto"
|
|
import ts from "typescript"
|
|
import { z } from "zod"
|
|
import { routeAiControllerBlockReason, routeAiProfileSchema, usesScopedRouteAiContext } from "@mmapp/contracts/mcp-routing"
|
|
import { fingerprint, McpError } from "./security.js"
|
|
|
|
type Handler = { prepare?: (input: Record<string, unknown>, context: unknown) => Promise<Record<string, unknown>>; execute?: (input: Record<string, unknown>) => Promise<unknown> }
|
|
async function load(name: string, providers: Record<string, unknown>) {
|
|
const exports: Record<string, unknown> = {}
|
|
const source = await readFile(new URL(name, import.meta.url), "utf8")
|
|
new Function("exports", "require", ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText)(exports, (key: string) => { assert.ok(providers[key], key); return providers[key] })
|
|
return exports
|
|
}
|
|
/** Actual overlap and actual profile action bodies; baseline/authority/CAS are
|
|
* explicit inert adapters. SQL predicates separately run on owned PostgreSQL. */
|
|
async function fixture() {
|
|
const profile = routeAiProfileSchema.parse({ name: "overlap", serverId: 1, family: "ipv4", community: "1:1", candidates: [{ id: "a", wanInterface: "wan", downstreamInterface: "gre", jumpHostId: 2, exitNodeId: 3, gateway: "192.0.2.1", gatewayRef: { resource: "gre", id: "*1" } }] })
|
|
const principal = { connectionId: randomUUID(), credentialId: randomUUID(), credentialExpiresAt: new Date(Date.now() + 600000).toISOString() }
|
|
const connection = { id: principal.connectionId, owner_id: "owner", owner_valid_until: new Date(principal.credentialExpiresAt), policy: { version: 1, expiresAt: principal.credentialExpiresAt, scope: { operationIds: ["routing.analyze", "routing.community.switch", "routing.path.verify"] } } }
|
|
let conflict = false, overlapReads = 0, casWrites = 0, baselinePreparations = 0
|
|
let lastParameters: unknown[] = []
|
|
const grantTimes: string[] = []
|
|
const pool = { query: async (sql: string, values: unknown[] = []) => {
|
|
if (sql.startsWith("SELECT id FROM mcp_routing_profiles WHERE enabled")) { overlapReads++; lastParameters = values; assert.ok(sql.includes("LIMIT 1")); assert.ok(sql.includes("id<>$1::uuid")); return { rows: conflict ? [{ id: randomUUID() }] : [] } }
|
|
if (sql.startsWith("SELECT id,connection_id,version")) return { rows: [] }
|
|
throw new Error("Unexpected unit SQL")
|
|
} }
|
|
const overlap = await load("./routing-controller-overlap.ts", { "../../db/index.js": { pool }, "@mmapp/contracts/mcp-routing": { routeAiProfileSchema }, "./security.js": { McpError } })
|
|
const services = new Map<string, Handler>(), operations = new Map<string, Handler>()
|
|
const profileModule = await load("./routing-profiles.ts", {
|
|
"./routing-controller-overlap.js": overlap, "./security.js": { fingerprint, McpError, accessGeneration: async () => "g" },
|
|
"./routing-controller-baseline.js": {
|
|
prepareRoutingControllerBaseline: async (_id: unknown, _version: unknown, _profile: unknown, expiresAt: string) => {
|
|
baselinePreparations++; grantTimes.push(z.string().datetime().parse(expiresAt))
|
|
return { packet: {}, proof: "inert-baseline" }
|
|
},
|
|
assertRoutingControllerBaseline: async (_baseline: unknown, _id: unknown, _version: unknown, _profile: unknown, expiresAt: string) => { grantTimes.push(expiresAt) },
|
|
routingControllerBaselinePrincipal: async () => principal, advanceRoutingControllerBaseline: async () => {},
|
|
},
|
|
"./routing-community-public.js": { publicRoutingControllerState: () => ({}) }, "node:crypto": { randomUUID }, zod: { z }, "@mmapp/contracts/mcp-routing": { routeAiControllerBlockReason, routeAiProfileSchema, usesScopedRouteAiContext }, "../../db/index.js": { pool },
|
|
"./service-registry.js": { registerMcpService: (name: string, handler: Handler) => services.set(name, handler) },
|
|
"./database-request-lease.js": { withMcpDatabaseRequest: () => { throw new Error("Profile-only fixture must not tick the controller") } },
|
|
"./store.js": { audit: async () => {}, validatePrincipal: async () => connection }, "./routing-model.js": { decideRoutingSwitch: () => ({}) },
|
|
"./path-proof-purpose.js": { COMMUNITY_PATH_MAX_AGE_MS: 90000 },
|
|
"./routing-controller-fence.js": { saveControllerProfileCas: async () => { casWrites++; return { id: "saved", version: 1 } } },
|
|
"./routing-reservation-store.js": { createRoutingReservationStore: () => { throw new Error("Overlap-only fixture must not read or mutate routing charges") } },
|
|
})
|
|
const register = profileModule.registerRoutingProfileActions as (register: (...args: unknown[]) => void) => void
|
|
register((...args) => operations.set(String(args[0]), args.at(-1) as Handler))
|
|
const input = { profileId: randomUUID(), profile, enabled: true, expiresAt: new Date(Date.now() + 120000).toISOString() }
|
|
const prepare = () => operations.get("routing.profiles.save")!.prepare!(input, { principal, connection })
|
|
const execute = (value: Record<string, unknown>) => services.get("routing.profile.save")!.execute!(value)
|
|
return { input, prepare, execute, conflict: (value: boolean) => { conflict = value }, reads: () => overlapReads, cas: () => casWrites, baselines: () => baselinePreparations, parameters: () => lastParameters, grantTimes }
|
|
}
|
|
function serviceInput(evidence: Record<string, unknown>) { return (evidence.steps as Array<{ input: Record<string, unknown> }>)[0].input }
|
|
test("enabled prepare reports role overlap before baseline issuance", async () => { const value = await fixture(); value.conflict(true); await assert.rejects(value.prepare, error => error instanceof McpError && error.code === "STATE_CONFLICT"); assert.equal(value.baselines(), 0); assert.equal(value.cas(), 0) })
|
|
test("execute rechecks overlap committed after preparation and refuses before CAS", async () => { const value = await fixture(); const evidence = await value.prepare(); value.conflict(true); await assert.rejects(() => value.execute(serviceInput(evidence))); assert.equal(value.reads(), 2); assert.equal(value.cas(), 0) })
|
|
test("disjoint activation prepares and executes with normal CAS", async () => { const value = await fixture(); const evidence = await value.prepare(); await value.execute(serviceInput(evidence)); assert.equal(value.reads(), 2); assert.equal(value.cas(), 1) })
|
|
test("current profile is excluded and role IDs remain exactly home jump exit", async () => { const value = await fixture(); await value.prepare(); assert.equal(value.parameters()[0], value.input.profileId); assert.deepEqual(value.parameters()[1], ["1", "2", "3"]) })
|
|
test("disabled saves do not acquire overlap admission or issue a baseline", async () => { const value = await fixture(); value.input.enabled = false; value.conflict(true); const evidence = await value.prepare(); await value.execute(serviceInput(evidence)); assert.equal(value.reads(), 0); assert.equal(value.baselines(), 0); assert.equal(value.cas(), 1) })
|
|
test("enabled profiles bind offset grant expiry to the exact UTC instant before approval", async () => {
|
|
const value = await fixture()
|
|
const expiry = value.input.expiresAt
|
|
value.input.expiresAt = new Date(Date.parse(expiry) + 3 * 3600000).toISOString().replace(/Z$/, "+03:00")
|
|
const input = serviceInput(await value.prepare())
|
|
assert.equal(input.expiresAt, expiry)
|
|
await value.execute(input)
|
|
assert.deepEqual(value.grantTimes, [expiry, expiry])
|
|
assert.equal(value.cas(), 1)
|
|
})
|