87 lines
6.9 KiB
TypeScript
87 lines
6.9 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { mkdtemp, rm, readFile, writeFile, unlink } from "node:fs/promises"
|
|
import { join, resolve, dirname, basename } from "node:path"
|
|
import { tmpdir } from "node:os"
|
|
import { randomUUID, randomBytes } from "node:crypto"
|
|
import type { PoolClient } from "pg"
|
|
import { pool, closePool } from "../../db/index.js"
|
|
import { createRoutingSourceContext, type RoutingSourceRecord } from "./routing-observation-source.js"
|
|
import { invalidateMcpAccess, accessGeneration } from "./security.js"
|
|
|
|
const directory = await mkdtemp(join(tmpdir(), "mm-routing-source-")), previous = process.env.MCP_STATE_DIR
|
|
process.env.MCP_STATE_DIR = directory
|
|
const originalQuery = pool.query, originalConnect = pool.connect
|
|
let realSqlCalls = 0, credentialQueries = 0, endpointQueryHook: (() => Promise<void>) | undefined
|
|
pool.query = (() => { realSqlCalls++; throw Error("Routing source unit cannot use real database SQL") }) as never
|
|
pool.connect = (() => { realSqlCalls++; throw Error("Routing source unit cannot acquire a database connection") }) as never
|
|
let originalKey: Buffer | undefined, rotatedKey: Buffer | undefined
|
|
try {
|
|
const endpoint = { id: 1, host: "127.0.0.1", port: 80, username: "fixture", password: "PRIVATE_FIXTURE", useSsl: false, verifySsl: true, enabled: true, routingEndpointEpoch: randomUUID() }
|
|
const peer = { ...endpoint, id: 2, routingEndpointEpoch: randomUUID() }
|
|
const endpoints = [endpoint, peer], context = await createRoutingSourceContext(endpoints)
|
|
const row: RoutingSourceRecord = { id: randomUUID(), srcServerId: 1, dstServerId: 2, srcInterface: "gre", dstInterface: "gre", family: "ipv6", table: "main", pingMs: 1, lossPct: 0, dlMbps: null, ulMbps: null, pingAt: "2026-10-21T10:00:00.123Z", bandwidthAt: null, contextVerified: true, source: "routeros", createdAt: "2026-10-21T10:00:00.123456Z" }
|
|
const proof = context.signRecord(row)
|
|
assert.equal(context.verifyRecord(row, proof), true)
|
|
assert.equal((await createRoutingSourceContext([...endpoints].reverse())).verifyRecord(row, proof), true)
|
|
assert.equal(context.verifyRecord({ ...row, pingAt: "2026-10-21T10:00:00.123000Z" }, proof), true)
|
|
for (const changed of [{ pingMs: 0 }, { lossPct: 1 }, { dlMbps: 1 }, { srcInterface: "other" }, { dstInterface: "other" }, { family: "ipv4" }, { table: "other" }, { contextVerified: false }, { source: "fixture" }, { createdAt: "2026-10-21T10:00:00.123457Z" }, { pingMs: NaN }, { dlMbps: Infinity }]) {
|
|
assert.equal(context.verifyRecord({ ...row, ...changed } as RoutingSourceRecord, proof), false)
|
|
}
|
|
for (const id of [1, 2]) for (const changed of [{ password: "CHANGED" }, { host: "192.0.2.1" }, { enabled: false }, { routingEndpointEpoch: randomUUID() }]) {
|
|
const changedContext = await createRoutingSourceContext(endpoints.map(value => value.id === id ? { ...value, ...changed } : value))
|
|
assert.equal(changedContext.verifyRecord(row, proof), false)
|
|
}
|
|
assert.equal(context.verifyRecord(row, null), false)
|
|
assert.ok(!JSON.stringify(context.expected).includes(endpoint.password))
|
|
const fakeQuery = { async query(text: string, values: unknown[]) {
|
|
credentialQueries++; assert.match(text, /WITH chosen AS MATERIALIZED/); assert.match(text, /FROM servers WHERE id=ANY\(\$1::bigint\[\]\)/)
|
|
assert.deepEqual(values, [[1, 2]]); await endpointQueryHook?.()
|
|
return { rows: endpoints.map(value => ({ id: value.id, endpoint: structuredClone(value), overflow: false })) }
|
|
} } as unknown as Pick<PoolClient, "query">
|
|
const keyPath = join(directory, "encryption-key"), generationBefore = await accessGeneration()
|
|
originalKey = await readFile(keyPath); rotatedKey = randomBytes(32)
|
|
assert.equal(originalKey.length, 32); assert.equal(rotatedKey.length, 32)
|
|
await context.assertCurrent(fakeQuery)
|
|
try {
|
|
await writeFile(keyPath, rotatedKey)
|
|
assert.equal(await accessGeneration(), generationBefore, "Rotate encryption-key itself, never access-generation")
|
|
const fresh = await createRoutingSourceContext(endpoints)
|
|
assert.equal(fresh.verifyRecord(row, proof), false, "Positive control: new purpose key rejects original MAC")
|
|
const before = credentialQueries
|
|
await assert.rejects(context.assertCurrent(fakeQuery), error => !!error && typeof error === "object" && "code" in error && error.code === "STATE_CONFLICT")
|
|
assert.equal(credentialQueries, before, "Changed key must refuse BEFORE reading source credentials")
|
|
} finally { await writeFile(keyPath, originalKey) }
|
|
// Restoring exactly the original bytes is an isolated control, not a key
|
|
// migration or reset of the application generation/ongoing operation.
|
|
await context.assertCurrent(fakeQuery)
|
|
assert.equal((await createRoutingSourceContext(endpoints)).verifyRecord(row, proof), true)
|
|
try {
|
|
endpointQueryHook = async () => { await writeFile(keyPath, rotatedKey!) }
|
|
const before = credentialQueries
|
|
await assert.rejects(context.assertCurrent(fakeQuery), error => !!error && typeof error === "object" && "code" in error && error.code === "STATE_CONFLICT")
|
|
assert.equal(credentialQueries, before + 1, "Rotation occurs DURING the awaited endpoint SQL seam")
|
|
assert.equal(await accessGeneration(), generationBefore)
|
|
} finally { endpointQueryHook = undefined; await writeFile(keyPath, originalKey) }
|
|
await context.assertCurrent(fakeQuery)
|
|
try {
|
|
await unlink(keyPath)
|
|
const before = credentialQueries
|
|
await assert.rejects(context.assertCurrent(fakeQuery), error => !!error && typeof error === "object" && "code" in error && error.code === "STATE_UNAVAILABLE")
|
|
assert.equal(credentialQueries, before)
|
|
await assert.rejects(readFile(keyPath), error => !!error && typeof error === "object" && "code" in error && error.code === "ENOENT", "Read-only epoch check must not recreate a deleted key")
|
|
} finally { await writeFile(keyPath, originalKey) }
|
|
await context.assertCurrent(fakeQuery); assert.equal(context.verifyRecord(row, proof), true)
|
|
await invalidateMcpAccess()
|
|
assert.equal((await createRoutingSourceContext(endpoints)).verifyRecord(row, proof), false)
|
|
const beforeGenerationRefusal = credentialQueries
|
|
await assert.rejects(context.assertCurrent(fakeQuery)); assert.equal(credentialQueries, beforeGenerationRefusal)
|
|
assert.equal(realSqlCalls, 0)
|
|
console.log("Routing source attestation: original endpoint/MAC/microsecond/generation checks preserved; real isolated same-generation encryption-key rotation before/during fake credential SQL, deletion without recreation, original-byte restore controls; 0 real DB/native calls")
|
|
} finally {
|
|
endpointQueryHook = undefined; originalKey?.fill(0); rotatedKey?.fill(0)
|
|
pool.query = originalQuery; pool.connect = originalConnect; await closePool()
|
|
if (previous === undefined) delete process.env.MCP_STATE_DIR; else process.env.MCP_STATE_DIR = previous
|
|
const target = resolve(directory); assert.equal(dirname(target), resolve(tmpdir())); assert.match(basename(target), /^mm-routing-source-/)
|
|
await rm(target, { recursive: true, force: true })
|
|
}
|