132 lines
12 KiB
TypeScript
132 lines
12 KiB
TypeScript
import { MIGRATION_MANIFEST } from "../../db/migration-manifest.js"
|
|
/** Disposable ordinary MCP/REST manual collector acceptance. Real application
|
|
* SQL, localhost HTTP and deferred global alert engine; no notifier recipients. */
|
|
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import { createServer } from "node:http"
|
|
import { basename, dirname, isAbsolute, resolve } from "node:path"
|
|
import { performance } from "node:perf_hooks"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
import { SignJWT } from "jose"
|
|
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
|
|
|
|
async function main() {
|
|
assert.equal(process.env.MMAPP_OWN_MANUAL_API_PING, "true")
|
|
const target = new URL(process.env.DATABASE_URL ?? "")
|
|
assert(["postgres:", "postgresql:"].includes(target.protocol)); assert.equal(target.hostname, "127.0.0.1")
|
|
assert.equal(target.username, "mcp_test"); assert(target.password); assert.equal(target.pathname, "/postgres")
|
|
assert(Number.isSafeInteger(Number(target.port)) && Number(target.port) > 0 && Number(target.port) <= 65535)
|
|
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-"))
|
|
process.env.AUTH_REQUIRED = "true"; process.env.AUTH_JWT_SECRET = "owned-manual-api-ping-acceptance-secret"; process.env.AUTH_ISSUER = "https://owned-api-ping.test"
|
|
const { pool, closePool } = await import("../../db/index.js"), { applySqlMigrations } = await import("../../db/migrate.js")
|
|
const { ensurePartitionsAround } = await import("../../db/partitions.js"), { buildApp } = await import("../../index.js")
|
|
const { createMcpConnection, authenticateMcpToken, updateMcpSettings } = await import("./store.js")
|
|
const { invokeMcpTool, approvePlan, applyPlan } = await import("./runtime.js")
|
|
const hooks = await import("../../services/alert-collector-hooks.js"), { executeSchedulerJob } = await import("../../services/scheduler.js")
|
|
const { manualDataCollection } = await import("../../services/manual-data-collection.js")
|
|
const owner = { id: "owned-manual-api-ping-owner", email: "[email protected]", name: "Owned API Ping", apps: ["mm"], permissions: ["mm:settings:admin", "mm:servers:write"], expiresAt: Date.now() + 3600000 }
|
|
let gets = 0, disabledGets = 0, fixtureFailed = false, hold = false, releaseHold: (() => void) | undefined, barrier: Promise<void> | undefined
|
|
let engineRuns = 0, engineFailed = false
|
|
const engines = new Set<Promise<unknown>>(), groups: string[] = []
|
|
const responders = [1, 2].map(index => createServer((request, response) => {
|
|
void (async () => {
|
|
if (request.headers.authorization === "Basic " + Buffer.from("owned-disabled:owned-disabled-password").toString("base64")) disabledGets++
|
|
else { assert.equal(request.headers.authorization, "Basic " + Buffer.from(`owned-${index}:owned-local-password`).toString("base64")); gets++ }
|
|
assert.equal(request.method, "GET"); assert.equal(request.url?.split("?")[0], "/rest/system/identity")
|
|
if (hold) await barrier
|
|
response.setHeader("content-type", "application/json"); response.end(JSON.stringify({ name: "owned-router-" + index }))
|
|
})().catch(() => { fixtureFailed = true; response.destroy() })
|
|
}))
|
|
let app: Awaited<ReturnType<typeof buildApp>> | undefined, busyRun: Promise<unknown> | undefined
|
|
const samples = async () => Number((await pool.query("SELECT count(*)::int AS n FROM servers_rest_ping_samples")).rows[0].n)
|
|
const settings = async () => (await pool.query("SELECT enabled,last_collected_at,last_duration_ms,last_error FROM servers_api_ping_settings WHERE id=1")).rows[0]
|
|
const until = async (check: () => Promise<boolean> | boolean) => { const end = performance.now() + 20000; while (!await check()) { assert(performance.now() < end, "Owned manual collector did not finish; never replay"); await delay(25) } }
|
|
const terminal = async (id: string) => { let state = ""; await until(async () => { state = (await pool.query("SELECT state FROM mcp_operations WHERE id=$1", [id])).rows[0].state; return !["pending", "running"].includes(state) }); return state }
|
|
try {
|
|
await applySqlMigrations(pool); assert.equal(Number((await pool.query("SELECT count(*) AS n FROM schema_migrations")).rows[0].n), MIGRATION_MANIFEST.length)
|
|
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM servers")).rows[0].n), 0)
|
|
await ensurePartitionsAround(pool)
|
|
// Deliberately exercise an absent singleton in this verified disposable DB;
|
|
// normal migrations may already seed defaults. Planning must stay read-only.
|
|
await pool.query("DELETE FROM servers_api_ping_settings WHERE id=1")
|
|
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM servers_api_ping_settings")).rows[0].n),0,"Missing settings must be initialized by the shared executor, not planning")
|
|
await pool.query("INSERT INTO alert_telegram_settings(id,bot_token,chat_id) VALUES(1,'','') ON CONFLICT(id) DO UPDATE SET bot_token='',chat_id='' ")
|
|
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM alert_outbox")).rows[0].n), 0)
|
|
for (const responder of responders) await new Promise<void>(resolve => responder.listen(0, "127.0.0.1", resolve))
|
|
const ids: number[] = []
|
|
for (let index = 0; index < 3; index++) ids.push(Number((await pool.query("INSERT INTO servers(name,host,port,use_ssl,verify_ssl,username,password,enabled) VALUES($1,'127.0.0.1',$2,false,false,$3,$4,$5) RETURNING id",
|
|
["owned-api-ping-" + index, (responders[index % 2].address() as { port: number }).port, index === 2 ? "owned-disabled" : "owned-" + (index + 1), index === 2 ? "owned-disabled-password" : "owned-local-password", index < 2])).rows[0].id))
|
|
await pool.query("INSERT INTO alert_rules(id,name,type,target,condition,severity,enabled,rule_chat_id) VALUES($1,'owned-api-ping-rule','server','owned-api-ping-0','offline','warning',true,'')", [randomUUID()])
|
|
await updateMcpSettings({ enabled: true }, owner); app = await buildApp({ startScheduler: false }); await app.ready()
|
|
hooks.wireAlertEngineRunner(async () => {
|
|
const pending = (async () => {
|
|
await executeSchedulerJob("alert_engine")
|
|
const row = (await pool.query("SELECT status,result_json FROM scheduler_runs WHERE job_key='alert_engine' ORDER BY finished_at DESC LIMIT 1")).rows[0]
|
|
assert(row); assert.equal(row.status, "ok"); assert.equal(row.result_json.skippedNoTelegram, true); engineRuns++
|
|
})(); engines.add(pending)
|
|
try { await pending }
|
|
catch { engineFailed = true; throw Error("Owned actual alert engine failed") }
|
|
finally { engines.delete(pending) }
|
|
})
|
|
const issue = async (serverIds: number[], allowGlobal: boolean) => authenticateMcpToken((await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Owned manual API Ping", mode: "approval",
|
|
expiresAt: new Date(Date.now() + 1800000).toISOString(), permissions: ["mm:servers:write"], scope: { serverIds, operationIds: ["servers.api-ping.collect"], allowGlobal }, limits: { callsPerMinute: 120, mutationsPerHour: 100 } }), owner)).token)
|
|
const principal = await issue(ids, true)
|
|
const prepare = () => invokeMcpTool(principal, "mm_api_ping_collect_plan", {}) as Promise<{ planId: string; state: string }>
|
|
const approve = async () => { const plan = await prepare(); await approvePlan(plan.planId, owner, true); return plan }
|
|
console.log("Owned manual API Ping stage:", "global-catalog-approval")
|
|
await assert.rejects(invokeMcpTool(await issue(ids, false), "mm_api_ping_collect_plan", {}))
|
|
await assert.rejects(invokeMcpTool(await issue(ids.slice(0, 2), true), "mm_api_ping_collect_plan", {}))
|
|
const unapproved = await prepare(); assert.equal(unapproved.state, "awaiting-approval"); await assert.rejects(applyPlan(principal, unapproved.planId, randomUUID()))
|
|
assert.equal(gets, 0); assert.equal(await samples(), 0)
|
|
groups.push("GLOBAL, all catalog IDs including disabled server and human approval are enforced before HTTP")
|
|
|
|
console.log("Owned manual API Ping stage:", "full-mcp-collector")
|
|
const plan = await approve(), key = randomUUID(), operation = await applyPlan(principal, plan.planId, key)
|
|
assert.equal(await terminal(operation.id), "applied"); assert.equal(gets, 2); assert.equal(disabledGets, 0); assert.equal(await samples(), 2)
|
|
const row = await settings(); assert.equal(row.enabled,false);assert(row.last_collected_at); assert(Number.isFinite(row.last_duration_ms)); assert.equal(row.last_error, "")
|
|
const receipt = (await pool.query("SELECT result FROM mcp_operation_steps WHERE operation_id=$1", [operation.id])).rows[0].result
|
|
assert.equal(receipt.acknowledged, true); assert.equal(receipt.skipped, false); assert(receipt.lastCollectedAt); assert.equal(receipt.lastError, false)
|
|
assert.equal(receipt.globalAlertHookRequested, true); assert.equal(receipt.alertDeliveryConfirmed, false)
|
|
assert(Buffer.byteLength(JSON.stringify(receipt)) < 16384)
|
|
await until(() => engineRuns >= 1); assert.equal(engineFailed, false)
|
|
groups.push("ordinary MCP collector GETs enabled servers only, persists samples/settings and invokes actual deferred global alert engine without recipients")
|
|
assert.equal((await applyPlan(principal, plan.planId, key)).id, operation.id)
|
|
assert.equal((await applyPlan(principal, plan.planId, randomUUID())).id, operation.id)
|
|
assert.equal(gets, 2); assert.equal(await samples(), 2)
|
|
groups.push("reapplying the same plan returns its journal operation without fresh collection")
|
|
|
|
console.log("Owned manual API Ping stage:", "rest-parity")
|
|
const token = await new SignJWT({ sub: owner.id, apps: owner.apps, permissions: owner.permissions }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("1h").setIssuer(process.env.AUTH_ISSUER!).sign(new TextEncoder().encode(process.env.AUTH_JWT_SECRET))
|
|
const response = await app.inject({ method: "POST", url: "/api/servers-api-ping/collect-now", headers: { authorization: "Bearer " + token }, payload: {} })
|
|
assert.equal(response.statusCode, 200); const rest = response.json(); assert.equal(rest.ok, true); assert.equal(rest.skipped, false)
|
|
assert(rest.lastCollectedAt); assert.equal(typeof rest.lastDurationMs, "number"); assert.equal(rest.lastError, null)
|
|
assert.equal(gets, 4); assert.equal(disabledGets, 0); assert.equal(await samples(), 4)
|
|
await until(() => engineRuns >= 2)
|
|
groups.push("signed-JWT REST uses the same complete collector and receipt fields")
|
|
|
|
console.log("Owned manual API Ping stage:", "busy-is-not-fresh")
|
|
hold = true; barrier = new Promise<void>(resolve => { releaseHold = resolve })
|
|
busyRun = manualDataCollection.collectServersRestPing(); await until(() => gets === 6)
|
|
const busyPlan = await approve(), busyOperation = await applyPlan(principal, busyPlan.planId, randomUUID())
|
|
assert.equal(await terminal(busyOperation.id), "unknown"); assert.equal(gets, 6); assert.equal(await samples(), 4)
|
|
hold = false; assert(releaseHold); releaseHold(); await busyRun; busyRun = undefined
|
|
await until(() => engineRuns >= 3); assert.equal(await samples(), 6); assert.equal(disabledGets, 0)
|
|
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM alert_outbox")).rows[0].n), 0)
|
|
assert.equal(fixtureFailed, false); assert.equal(engineFailed, false)
|
|
groups.push("shared busy collector is not reported as fresh MCP success and is not retried; existing active collector completes normally")
|
|
console.log("Owned manual API Ping accepted:", JSON.stringify({ groups: groups.length, checks: groups, identityGets: gets, disabledGets, sampleRows: await samples(), actualGlobalAlertRuns: engineRuns, notifierDelivery: false }))
|
|
} finally {
|
|
hold = false; releaseHold?.(); await busyRun?.catch(() => {})
|
|
hooks.clearAlertCollectorHooksTimer()
|
|
await (await import("../../services/scheduler.js")).stopSchedulerForDatabaseOperation()
|
|
await Promise.allSettled([...engines]); hooks.clearAlertCollectorHooksTimer()
|
|
await (await import("../../services/traffic-flow-ingest.js")).stopTrafficFlowListenerForDatabaseOperation()
|
|
await app?.close()
|
|
for (const responder of responders) { responder.closeAllConnections(); await new Promise<void>(resolve => responder.close(() => resolve())) }
|
|
await closePool()
|
|
}
|
|
}
|
|
void main().catch(() => { console.error("Owned manual API Ping acceptance failed; no real RouterOS/notifier action"); process.exitCode = 1 })
|