Files
MikrotikManager/backend/src/modules/mcp/administration-admission-acceptance.ts
T

173 lines
9.7 KiB
TypeScript

import assert from "node:assert/strict"
import { createHash, randomUUID } from "node:crypto"
import { readdir, readFile } from "node:fs/promises"
import path from "node:path"
import { SignJWT } from "jose"
import type { PoolClient } from "pg"
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import { pool } from "../../db/index.js"
import { SYSTEM_DATABASE_OPERATION_LOCK, withOperationLock } from "../../db/operation-lock.js"
import type { AuthUser } from "../../lib/permissions.js"
import { PARTITION_WRITER_ADVISORY_KEY } from "../../services/partition-write-transaction.js"
import { withApplicationCollectorLock } from "../../services/config-mutation-lock.js"
import { buildApp } from "../../index.js"
import { createMcpConnection, setConnectionStatus } from "./store.js"
import { decryptBinary, decryptSecret, mcpStateDirectory } from "./security.js"
async function loseArchiveCommitAcknowledgement<T>(actorId: string, upload: () => PromiseLike<T>) {
const originals = new Map<PoolClient, PoolClient["query"]>()
let commitCount = 0
const disarm = (_error: Error | undefined, client: PoolClient) => {
const query = originals.get(client)
if (query) {
client.query = query
originals.delete(client)
}
}
const arm = (client: PoolClient) => {
const query = client.query
originals.set(client, query)
let archiveAudit = false
client.query = ((...args: unknown[]) => {
const [statement, values] = args
if (statement === "INSERT INTO mcp_audit(actor_id,action,connection_id,payload) VALUES($1,$2,$3,$4::jsonb)" &&
Array.isArray(values) && values[0] === actorId && values[1] === "database.archive.upload") archiveAudit = true
const result = Reflect.apply(query, client, args)
if (statement !== "COMMIT" || !archiveAudit) return result
return Promise.resolve(result).then(commit => {
assert.equal(commit.command, "COMMIT")
commitCount++
if (commitCount === 1) throw new Error("Owned fixture lost the archive COMMIT acknowledgement")
return commit
})
}) as PoolClient["query"]
}
pool.on("acquire", arm)
pool.on("release", disarm)
try {
const result = await upload()
assert.equal(commitCount, 1, "The upload must issue exactly one COMMIT")
return result
} finally {
pool.off("acquire", arm)
pool.off("release", disarm)
for (const client of originals.keys()) disarm(undefined, client)
}
}
export async function verifyAdministrationAdmission(actor: AuthUser) {
const app = await buildApp({ startScheduler: false, logger: false })
try {
const reader = { ...actor, permissions: [...actor.permissions, "mm:servers:read"] }
const { connection } = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Owned admin admission", mode: "observer",
expiresAt: new Date(Date.now() + 600_000).toISOString(), permissions: ["mm:servers:read"],
scope: { serverIds: [], operationIds: ["logs.query"], allowGlobal: true } }), reader)
await setConnectionStatus(connection.id, "paused", reader)
const profiles = [randomUUID(), randomUUID()]
await pool.query(`INSERT INTO mcp_routing_profiles(id,connection_id,config,enabled,grant_expires_at)
SELECT id,$2,'{}'::jsonb,true,now()+interval '10 minutes' FROM unnest($1::uuid[]) AS p(id)`, [profiles, connection.id])
const token = await new SignJWT({ sub: reader.id, apps: reader.apps, permissions: reader.permissions })
.setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("15m").setIssuer(process.env.AUTH_ISSUER!)
.sign(new TextEncoder().encode(process.env.AUTH_JWT_SECRET!))
const post = (path: string, payload?: object) => app.inject({ method: "POST", url: `/api/mcp${path}`,
headers: { authorization: `Bearer ${token}` }, payload })
const check = () => post(`/connections/${connection.id}/check`)
const pause = () => post(`/routing-profiles/${profiles[0]}/pause`)
const stop = () => post("/stop-automation")
const secretValue = "owned-admission-synthetic-secret"
const secret = () => post("/secrets", { purpose: "owned-admission-fixture", value: secretValue })
const snapshot = () => pool.query(`SELECT (SELECT enabled FROM mcp_settings WHERE id=1) AS enabled,
(SELECT count(*)::int FROM mcp_routing_profiles WHERE enabled) AS active,
(SELECT count(*)::int FROM mcp_secrets) AS secrets,
(SELECT coalesce(jsonb_agg(action ORDER BY id),'[]') FROM mcp_audit WHERE actor_id=$1) AS audit`, [actor.id]).then(result => result.rows[0])
const before = await snapshot()
assert(before.enabled && before.active === 2 && before.secrets === 0)
await withOperationLock(() => pool.connect(), SYSTEM_DATABASE_OPERATION_LOCK, async () => {
for (const response of await Promise.all([check(), pause(), stop()])) {
assert.equal(response.statusCode, 503)
assert.equal(response.json().code, "PROTOCOL_STORAGE_BUSY")
}
assert.deepEqual(await snapshot(), before)
})
await withOperationLock(() => pool.connect(), PARTITION_WRITER_ADVISORY_KEY, async () => {
assert.equal((await secret()).statusCode, 503)
assert.deepEqual(await snapshot(), before)
const checked = await check()
assert.equal(checked.statusCode, 200)
assert.equal(checked.json().protocolProbe.status, "skipped")
assert.equal((await pause()).statusCode, 200)
assert.equal((await snapshot()).active, 1)
assert.equal((await stop()).statusCode, 200)
})
const stored = await secret()
assert.equal(stored.statusCode, 200)
const { rows: [record] } = await pool.query("SELECT ciphertext FROM mcp_secrets WHERE id=$1", [stored.json().secretRef])
assert.notEqual(record.ciphertext, secretValue)
assert.equal(await decryptSecret(record.ciphertext), secretValue)
const after = await snapshot()
assert.deepEqual([after.enabled, after.active, after.secrets], [false, 0, 1])
assert.deepEqual(after.audit, [...before.audit, "connection.check", "controller.pause", "automation.emergency-stop", "secret.create"])
const vault = path.join(mcpStateDirectory(), "restore-vault")
const files = async () => (await readdir(vault).catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return []
throw error
})).sort()
const originalFiles = await files()
const dump = Buffer.from("PGDMP owned archive admission fixture")
const upload = () => app.inject({ method: "POST", url: "/api/mcp/database/archives",
headers: { authorization: `Bearer ${token}`, "content-type": "application/octet-stream" }, payload: dump })
for (const key of [SYSTEM_DATABASE_OPERATION_LOCK, PARTITION_WRITER_ADVISORY_KEY]) {
await withOperationLock(() => pool.connect(), key, async () => {
const blocked = await upload()
assert.equal(blocked.statusCode, 503)
assert.equal(blocked.json().code, "PROTOCOL_STORAGE_BUSY")
assert.deepEqual(await files(), originalFiles)
assert.deepEqual(await snapshot(), after)
})
}
await withApplicationCollectorLock(async () => {
assert.equal((await upload()).statusCode, 503)
assert.deepEqual(await files(), originalFiles)
assert.deepEqual(await snapshot(), after)
})
await pool.query("ALTER TABLE mcp_audit ADD CONSTRAINT owned_archive_audit_refusal CHECK (action <> 'database.archive.upload') NOT VALID")
try {
assert.equal((await upload()).statusCode, 503)
assert.deepEqual(await files(), originalFiles)
assert.deepEqual(await snapshot(), after)
} finally {
await pool.query("ALTER TABLE mcp_audit DROP CONSTRAINT owned_archive_audit_refusal")
}
const uploaded = await upload()
assert.equal(uploaded.statusCode, 200)
const receipt = uploaded.json()
assert.equal(receipt.sha256, createHash("sha256").update(dump).digest("hex"))
assert.equal(receipt.sizeBytes, dump.length)
assert(!(await readFile(path.join(vault, receipt.archiveRef + ".archive.bin"))).includes(dump))
const uploads = async () => (await pool.query("SELECT payload FROM mcp_audit WHERE actor_id=$1 AND action='database.archive.upload' ORDER BY id", [actor.id])).rows
assert.deepEqual(await uploads(), [{ payload: receipt }])
const beforeLostAck = await files()
const responseWithoutReceipt = await loseArchiveCommitAcknowledgement(actor.id, upload)
assert.equal(responseWithoutReceipt.statusCode, 503)
assert.equal(responseWithoutReceipt.json().code, "AUDIT_UNAVAILABLE")
const recordedUploads = await uploads()
assert.equal(recordedUploads.length, 2)
assert.deepEqual(recordedUploads[0], { payload: receipt })
const retained = recordedUploads[1].payload
assert(!responseWithoutReceipt.body.includes(retained.archiveRef))
assert.equal(retained.sha256, receipt.sha256)
assert.equal(retained.sizeBytes, dump.length)
assert(Date.parse(retained.expiresAt) > Date.now())
assert.deepEqual(await files(), [...beforeLostAck, retained.archiveRef + ".archive.bin", retained.archiveRef + ".archive.json"].sort())
const ciphertext = await readFile(path.join(vault, retained.archiveRef + ".archive.bin"))
assert(!ciphertext.includes(dump))
assert.deepEqual(await decryptBinary(ciphertext), dump)
const metadata = JSON.parse(await readFile(path.join(vault, retained.archiveRef + ".archive.json"), "utf8"))
assert.deepEqual({ archiveRef: metadata.id, sha256: metadata.sha256, sizeBytes: metadata.sizeBytes, expiresAt: metadata.expiresAt }, retained)
console.log("MCP restore archive: one committed audit and encrypted archive retained after lost COMMIT acknowledgement")
console.log("MCP administration admission: audit, pause, emergency stop, secret storage and restore archive upload passed")
} finally { await app.close() }
}