210 lines
13 KiB
TypeScript
210 lines
13 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { test } from "node:test"
|
|
import { randomUUID } from "node:crypto"
|
|
import { mkdtemp, rm } from "node:fs/promises"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import type { PoolClient } from "pg"
|
|
import { countLegacyRoutingSwitches, routingReservationDeadline, transitionRoutingReservation, type RoutingReservationState } from "./routing-reservation-contract.js"
|
|
import { bindRoutingChargeAdmission, routingReservationTransaction, RoutingReservationCommitUnknown, stageRoutingChargeWitness } from "./routing-reservation-transaction.js"
|
|
import { readRoutingChargeJournal } from "./routing-charge-journal.js"
|
|
import { fingerprint, privateSecretFingerprint } from "./security.js"
|
|
import { temporaryGrantOriginSql } from "./temporary-grant-origin.js"
|
|
import { createRoutingReservationStore, withRoutingReservationAdmission } from "./routing-reservation-store.js"
|
|
|
|
test("legacy switch history counts each recent entry and fails closed on malformed/future/unbounded data", () => {
|
|
const now = Date.parse("2026-10-25T12:00:00.000Z"), recent = "2026-10-25T11:59:00.000Z"
|
|
assert.equal(countLegacyRoutingSwitches({}, now), 0)
|
|
assert.equal(countLegacyRoutingSwitches({ switches: [recent, recent, "2026-10-25T11:00:00.000Z"] }, now), 2)
|
|
for (const state of [null, [], { switches: null }, { switches: ["invalid"] }, { switches: ["2026-10-25T12:00:00.001Z"] }, { switches: Array(2049).fill(recent) }]) assert.throws(() => countLegacyRoutingSwitches(state, now), /legacy/)
|
|
})
|
|
|
|
test("reservation deadline never restarts its original120-second/grant/channel clocks", () => {
|
|
const start = 1000000
|
|
assert.equal(routingReservationDeadline(start, start + 600000, start + 500000), start + 120000)
|
|
assert.equal(routingReservationDeadline(start, start + 600000, start + 90000), start + 90000)
|
|
assert.equal(routingReservationDeadline(start, start + 600000, start + 90000, start + 30000), start + 30000)
|
|
assert.equal(routingReservationDeadline(start, start + 10000, start + 90000), start + 10000)
|
|
for (const bad of [NaN, Infinity, -Infinity]) {
|
|
assert.throws(() => routingReservationDeadline(bad, start, start))
|
|
assert.throws(() => routingReservationDeadline(start, bad, start))
|
|
assert.throws(() => routingReservationDeadline(start, start, bad))
|
|
}
|
|
})
|
|
|
|
test("held allocation consumes once; unknown cannot be retried or refunded", () => {
|
|
const held: RoutingReservationState = { revision: 1, forward: "held", inverse: "held" }
|
|
const spent = transitionRoutingReservation(held, "forward", "attempt")
|
|
assert.equal(held.forward, "held"); assert.equal(spent.forward, "spent")
|
|
assert.throws(() => transitionRoutingReservation(spent, "forward", "attempt"))
|
|
const unknown = transitionRoutingReservation(spent, "forward", "unknown")
|
|
assert.equal(unknown.forward, "unknown")
|
|
for (const event of ["attempt", "prove-unused", "unknown"] as const) assert.throws(() => transitionRoutingReservation(unknown, "forward", event))
|
|
assert.throws(() => transitionRoutingReservation(held, "inverse", "attempt"))
|
|
assert.throws(() => transitionRoutingReservation(held, "inverse", "prove-unused"))
|
|
})
|
|
|
|
test("server-proven passed versus failed outcomes authorize distinct inverse allocation transitions", () => {
|
|
const base: RoutingReservationState = { revision: 2, forward: "spent", inverse: "held" }
|
|
const passed: RoutingReservationState = { ...base, outcome: { status: "passed", configurationProof: "proof", networkProof: "proof" } }
|
|
assert.equal(transitionRoutingReservation(passed, "inverse", "prove-unused").inverse, "proven-unused")
|
|
assert.throws(() => transitionRoutingReservation(passed, "inverse", "attempt"))
|
|
const failed: RoutingReservationState = { ...base, outcome: { ...passed.outcome!, status: "failed" } }
|
|
assert.equal(transitionRoutingReservation(failed, "inverse", "attempt").inverse, "spent")
|
|
assert.throws(() => transitionRoutingReservation(failed, "inverse", "prove-unused"))
|
|
})
|
|
|
|
function sqlFixture(failure?: "commit" | "work" | "rollback") {
|
|
const calls: string[] = [], released: boolean[] = []
|
|
const db = { query: async (sql: string) => { calls.push(sql); if (sql === "COMMIT" && failure === "commit" || sql === "ROLLBACK" && failure === "rollback") throw Error("transport lost"); return { rows: [], command: sql } },
|
|
release: (destroy: boolean) => { released.push(destroy) } } as unknown as PoolClient
|
|
return { db, calls, released, connect: async () => db }
|
|
}
|
|
|
|
test("uncertain COMMIT destroys its owner without rollback or automatic retry", async () => {
|
|
const f = sqlFixture("commit")
|
|
await assert.rejects(routingReservationTransaction(async () => "value", f.connect), RoutingReservationCommitUnknown)
|
|
assert.equal(f.calls.filter(sql => sql === "COMMIT").length, 1)
|
|
assert.equal(f.calls.includes("ROLLBACK"), false); assert.deepEqual(f.released, [true])
|
|
})
|
|
|
|
test("host charge witness is durable before COMMIT and survives loss of its acknowledgement", async () => {
|
|
const root = await mkdtemp(join(tmpdir(), "mmapp-routing-witness-")), saved = process.env.MCP_STATE_DIR
|
|
process.env.MCP_STATE_DIR = root
|
|
const profileId = randomUUID(), now = Date.now()
|
|
const witness = { allocationId: randomUUID(), createdAt: new Date(now).toISOString(), auditMac: "a".repeat(64) }
|
|
const aborted = { ...witness, allocationId: randomUUID() }
|
|
try {
|
|
await privateSecretFingerprint("owned fixture", "owned fixture")
|
|
const beforeCommit = sqlFixture()
|
|
await assert.rejects(routingReservationTransaction(async db => {
|
|
stageRoutingChargeWitness(db, profileId, aborted, now + 60_000)
|
|
throw new Error("refused before COMMIT")
|
|
}, beforeCommit.connect), /refused before COMMIT/)
|
|
assert.deepEqual(await readRoutingChargeJournal(profileId, now), [])
|
|
const lost = sqlFixture("commit"), query = lost.db.query.bind(lost.db)
|
|
lost.db.query = (async (sql: string) => {
|
|
if (sql === "COMMIT") assert.deepEqual(await readRoutingChargeJournal(profileId, now), [witness])
|
|
return query(sql)
|
|
}) as PoolClient["query"]
|
|
await assert.rejects(routingReservationTransaction(async db => {
|
|
stageRoutingChargeWitness(db, profileId, witness, now + 60_000)
|
|
}, lost.connect), RoutingReservationCommitUnknown)
|
|
assert.deepEqual(await readRoutingChargeJournal(profileId, now), [witness])
|
|
assert.deepEqual(lost.released, [true])
|
|
} finally {
|
|
if (saved === undefined) delete process.env.MCP_STATE_DIR; else process.env.MCP_STATE_DIR = saved
|
|
await rm(root, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
test("expiry before or during publication rolls back without sending COMMIT", async t => {
|
|
const root = await mkdtemp(join(tmpdir(), "mmapp-routing-expired-witness-")), saved = process.env.MCP_STATE_DIR
|
|
process.env.MCP_STATE_DIR = root
|
|
const now = Date.now(), deadline = now + 1_000
|
|
const witness = { allocationId: randomUUID(), createdAt: new Date(now).toISOString(), auditMac: "b".repeat(64) }
|
|
try {
|
|
await privateSecretFingerprint("owned fixture", "owned fixture")
|
|
for (const passes of [1, 2]) {
|
|
const profileId = randomUUID(), fixture = sqlFixture()
|
|
let checked = 0
|
|
const clock = t.mock.method(Date, "now", () => ++checked <= passes ? now : deadline)
|
|
try {
|
|
await assert.rejects(routingReservationTransaction(async db => {
|
|
stageRoutingChargeWitness(db, profileId, witness, deadline)
|
|
}, fixture.connect), { code: "STATE_CONFLICT", message: "Исходный срок допуска переключения истёк" })
|
|
} finally {
|
|
clock.mock.restore()
|
|
}
|
|
assert.equal(fixture.calls.includes("COMMIT"), false)
|
|
assert.equal(fixture.calls.at(-1), "ROLLBACK")
|
|
assert.deepEqual(await readRoutingChargeJournal(profileId, now), passes === 2 ? [witness] : [])
|
|
}
|
|
} finally {
|
|
if (saved === undefined) delete process.env.MCP_STATE_DIR; else process.env.MCP_STATE_DIR = saved
|
|
await rm(root, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
test("charge publication keeps the original monotonic lifetime and rechecks the grant before COMMIT", async () => {
|
|
const root = await mkdtemp(join(tmpdir(), "mmapp-routing-grant-witness-")), saved = process.env.MCP_STATE_DIR
|
|
process.env.MCP_STATE_DIR = root
|
|
const now = Date.now(), connectionId = randomUUID(), credentialId = randomUUID()
|
|
const witness = { allocationId: randomUUID(), createdAt: new Date(now).toISOString(), auditMac: "c".repeat(64) }
|
|
const grant = { proof: fingerprint({ credentialId, grant: null }), expiresAt: null, monotonicEnd: Infinity,
|
|
admissionExpiresAt: now + 60_000, admissionMonotonicEnd: performance.now() + 60_000 }
|
|
try {
|
|
await privateSecretFingerprint("owned fixture", "owned fixture")
|
|
for (const mode of ["expired", "changed", "current"] as const) {
|
|
const profileId = randomUUID(), fixture = sqlFixture()
|
|
const query = fixture.db.query.bind(fixture.db)
|
|
fixture.db.query = (async (sql: string, values?: unknown[]) => {
|
|
if (sql === temporaryGrantOriginSql) {
|
|
assert.deepEqual(values, [connectionId, credentialId])
|
|
assert.deepEqual(await readRoutingChargeJournal(profileId, now), [witness])
|
|
}
|
|
return query(sql)
|
|
}) as PoolClient["query"]
|
|
const tx = routingReservationTransaction(async db => {
|
|
bindRoutingChargeAdmission(db, connectionId, credentialId, { ...grant,
|
|
proof: mode === "changed" ? "old grant proof" : grant.proof,
|
|
admissionMonotonicEnd: mode === "expired" ? performance.now() - 1 : grant.admissionMonotonicEnd })
|
|
stageRoutingChargeWitness(db, profileId, witness, now + 60_000)
|
|
}, fixture.connect)
|
|
if (mode === "current") await tx
|
|
else await assert.rejects(tx, { code: "GRANT_INACTIVE" })
|
|
assert.equal(fixture.calls.includes(temporaryGrantOriginSql), mode !== "expired")
|
|
assert.equal(fixture.calls.at(-1), mode === "current" ? "COMMIT" : "ROLLBACK")
|
|
assert.deepEqual(await readRoutingChargeJournal(profileId, now), mode === "expired" ? [] : [witness])
|
|
}
|
|
} finally {
|
|
if (saved === undefined) delete process.env.MCP_STATE_DIR; else process.env.MCP_STATE_DIR = saved
|
|
await rm(root, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
test("precommit error rolls back; failed rollback destroys connection; readonly uses same owner", async () => {
|
|
for (const failure of ["work", "rollback"] as const) {
|
|
const f = sqlFixture(failure)
|
|
await assert.rejects(routingReservationTransaction(async () => { throw Error("precommit") }, f.connect), /precommit/)
|
|
assert.equal(f.calls.includes("COMMIT"), false); assert.equal(f.calls.filter(sql => sql === "ROLLBACK").length, 1)
|
|
assert.deepEqual(f.released, [failure === "rollback"])
|
|
}
|
|
const f = sqlFixture()
|
|
assert.equal(await routingReservationTransaction(async db => { await db.query("SELECT 1"); return "readonly" }, f.connect, true), "readonly")
|
|
assert.equal(f.calls[0], "BEGIN READ ONLY"); assert.deepEqual(f.released, [false])
|
|
})
|
|
|
|
test("a serialized object cannot forge the internal inverse allocation capability", async () => {
|
|
const store = createRoutingReservationStore()
|
|
await assert.rejects(store.beginInverseAttempt(JSON.parse('{"kind":"routing-reserved-inverse-allocation"}')), /capability/)
|
|
})
|
|
|
|
test("forward allocation rejects caller IDs and serialized lookalikes before acquiring SQL ownership", async () => {
|
|
let connects = 0
|
|
const store = createRoutingReservationStore(async () => { connects++; throw Error("must not connect") })
|
|
for (const forged of ["00000000-0000-4000-8000-000000000000", { kind: "routing-reserved-forward-allocation" }]) {
|
|
await assert.rejects(store.beginForwardAttempt(JSON.parse(JSON.stringify(forged))), /capability/)
|
|
}
|
|
assert.equal(connects, 0)
|
|
})
|
|
|
|
test("outer runtime admission owns exactly one transaction and cannot return a value after lost ACK", async () => {
|
|
const confirmed = sqlFixture()
|
|
const result = await withRoutingReservationAdmission(async db => { await db.query("owned operation admission"); return { operationId: "synthetic" } }, confirmed.connect)
|
|
assert.deepEqual(result, { value: { operationId: "synthetic" }, reservation: undefined })
|
|
assert.equal(confirmed.calls.filter(sql => sql === "BEGIN").length, 1)
|
|
assert.equal(confirmed.calls.filter(sql => sql === "COMMIT").length, 1)
|
|
const lost = sqlFixture("commit")
|
|
await assert.rejects(withRoutingReservationAdmission(async db => { await db.query("owned operation admission"); return "must not escape" }, lost.connect), RoutingReservationCommitUnknown)
|
|
assert.equal(lost.calls.includes("ROLLBACK"), false)
|
|
assert.deepEqual(lost.released, [true])
|
|
})
|
|
|
|
test("inverse execution capability cannot be forged to read a running source", async () => {
|
|
let connects = 0
|
|
const store = createRoutingReservationStore(async () => { connects++; throw Error("must not connect") })
|
|
await assert.rejects(store.inspectInverseExecution(JSON.parse('{"kind":"routing-reserved-inverse-execution"}')), /capability/)
|
|
assert.equal(connects, 0)
|
|
})
|