Files
MikrotikManager/backend/src/services/traffic-flow-active-services.owned.test.ts
T

363 lines
24 KiB
TypeScript

import { MIGRATION_MANIFEST } from "../db/migration-manifest.js"
/** Production settings/purge with an active worker on owned PostgreSQL and
* localhost UDP/HTTP. The public profile exercises REST and MCP authorization.
* No service, Worker, IPC or SQL adapters are replaced. */
import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import { createSocket } from "node:dgram"
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 { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"
async function main() {
assert.equal(process.env.MMAPP_OWN_FLOW_ACTIVE_SERVICES, "true")
assert.equal(process.env.NODE_ENV, "test")
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.isInteger(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.FLOW_LISTEN_HOST = "127.0.0.1"
// Inherit neither a production host-agent socket nor an alternative bind.
process.env.FLOW_AGENT_SOCKET = ""
const { pool, closePool } = await import("../db/index.js")
const { applySqlMigrations } = await import("../db/migrate.js")
const { ensurePartitionsAround } = await import("../db/partitions.js")
const ingest = await import("./traffic-flow-ingest.js")
const settings = await import("./traffic-flow-settings.js")
const { updateTrafficFlowSettingsWithListener } = await import("./traffic-flow-settings-service.js")
const { purgeTrafficFlowWithEvent } = await import("./flow-purge-service.js")
const { flowPurgeTables } = await import("./traffic-flow-purge-execution.js")
const { pauseRipeBackgroundWork } = await import("./traffic-flow-ripe.js")
let app: Awaited<ReturnType<typeof import("../index.js").buildApp>> | undefined
const sender = createSocket("udp4")
let fixtureError: unknown, ifaceGets = 0, serverId: number | undefined, mainStarted = false
const groups: string[] = []
const native = createServer((request, response) => {
try {
assert.equal(request.method, "GET"); assert.equal(request.url, "/rest/interface")
assert.equal(request.headers.authorization, "Basic " + Buffer.from("owned-active:owned-password").toString("base64"))
ifaceGets++; response.setHeader("content-type", "application/json"); response.end("[]")
} catch (error) { fixtureError = error; response.destroy() }
})
const until = async (predicate: () => boolean | Promise<boolean>, description: string, timeoutMs = 15000) => {
const deadline = performance.now() + timeoutMs
while (!await predicate()) {
if (fixtureError) throw fixtureError
assert(performance.now() < deadline, description)
await delay(20)
}
}
const reservePort = async () => {
const socket = createSocket("udp4")
try {
await new Promise<void>((done, reject) => { socket.once("error", reject); socket.bind(0, "127.0.0.1", done) })
return socket.address().port
} finally { await new Promise<void>(done => socket.close(done)) }
}
const portFree = async (port: number) => {
const socket = createSocket("udp4")
try { await new Promise<void>((done, reject) => { socket.once("error", reject); socket.bind(port, "127.0.0.1", done) }) }
finally { try { await new Promise<void>(done => socket.close(done)) } catch { /* failed bind */ } }
}
// Private endpoints keep the genuine worker's RIPE enqueue path inactive.
const send = async (port: number, bytes: number, sequence: number) => {
const buffer = Buffer.alloc(72)
buffer.writeUInt16BE(5, 0); buffer.writeUInt16BE(1, 2)
buffer.writeUInt32BE(Math.floor(Date.now() / 1000), 8); buffer.writeUInt32BE(sequence, 16)
buffer.set([10, 145, 0, 10], 24); buffer.set([10, 145, 0, 20], 28)
buffer.writeUInt16BE(1, 36); buffer.writeUInt32BE(3, 40); buffer.writeUInt32BE(bytes, 44)
buffer.writeUInt16BE(49152, 56); buffer.writeUInt16BE(443, 58); buffer.writeUInt8(6, 62)
await new Promise<void>((done, reject) => sender.send(buffer, port, "127.0.0.1", error => error ? reject(error) : done()))
}
const authorize = async () => { if (fixtureError) throw fixtureError }
const configuration = async () => (await pool.query(`SELECT to_jsonb(s) - ARRAY[
'last_datagram_at','last_exporter_ip','last_error','packets_received','updated_at'] AS value
FROM traffic_flow_settings s WHERE id=1`)).rows[0].value
const totals = async () => (await pool.query("SELECT coalesce(sum(bytes),0)::bigint AS bytes,coalesce(sum(packets),0)::bigint AS packets FROM flow_buckets WHERE server_id=$1", [serverId])).rows[0]
let inFlightSqlFlushes = 0
const duringBlockedFlush = async <T>(port: number, bytes: number, sequence: number,
start: () => { task: Promise<T>; admitted: () => boolean | Promise<boolean> }) => {
const blocker = await pool.connect()
let task: Promise<{ ok: true; value: T } | { ok: false; error: unknown }> | undefined
let outcome: Awaited<typeof task>, settled = false
try {
await blocker.query("BEGIN")
await blocker.query("SET LOCAL lock_timeout='3s'")
await blocker.query("LOCK TABLE flow_buckets IN ACCESS EXCLUSIVE MODE")
const blockerPid = Number((await blocker.query("SELECT pg_backend_pid() AS pid")).rows[0].pid)
await send(port, bytes, sequence)
// A real production flush must reach SQL and wait on our table lock.
// No heartbeat/pending-size assumption: heartbeats follow awaited flush.
await until(async () => Number((await pool.query(`SELECT count(*) AS n FROM pg_stat_activity
WHERE datname=current_database() AND usename='mcp_test' AND pid<>pg_backend_pid()
AND state='active' AND wait_event_type='Lock'
AND $1::int=ANY(pg_blocking_pids(pid))
AND (query ~* 'INSERT INTO flow_buckets' OR query ~* 'PARTITION OF flow_buckets')`, [blockerPid])).rows[0].n) > 0,
"Genuine production worker SQL did not block at owned flow_buckets lock")
inFlightSqlFlushes++
const active = start()
// Attach both outcomes before awaiting admission; no unhandled service
// rejection can strand the blocker or the production worker.
task = active.task.then(value => { settled = true; return { ok: true as const, value } }, error => { settled = true; return { ok: false as const, error } })
await until(active.admitted, "Shared service did not enter while genuine worker SQL was in flight", 3000)
assert.equal(settled, false, "Shared service must not finish ahead of blocked actual worker SQL")
} finally {
// Release the genuine SQL blocker BEFORE joining a service that owns or
// waits for this worker. Terminal entry cleanup runs only after this join.
try {
try { await blocker.query("ROLLBACK") } finally { blocker.release() }
} finally {
if (task) outcome = await task
}
}
assert(outcome)
if (!outcome.ok) throw outcome.error
return outcome.value
}
const settingsDuringFlush = (port: number, bytes: number, sequence: number,
patch: Parameters<typeof updateTrafficFlowSettingsWithListener>[0]) => {
const receiptId = randomUUID()
return duringBlockedFlush(port, bytes, sequence, () => ({
task: updateTrafficFlowSettingsWithListener(patch, { authorize, receiptId }),
admitted: async () => Number((await pool.query("SELECT count(*) AS n FROM flow_settings_intents WHERE receipt_id=$1 AND phase='configuration' AND state='claimed'", [receiptId])).rows[0].n) === 1,
}))
}
const intentReceipt = async (receipt: Awaited<ReturnType<typeof updateTrafficFlowSettingsWithListener>>) => {
assert.equal(receipt.status, "applied"); assert.equal(receipt.configurationConfirmed, true)
assert.equal(receipt.listener, "request-acknowledged"); assert.equal(receipt.listenerReadinessConfirmed, false)
assert.equal(receipt.receiptConfirmed, true); assert.equal(receipt.automaticReplay, false)
assert.equal(receipt.privateMaterialExported, false); assert.equal(receipt.attempts, 2)
assert.equal(receipt.retries, 0); assert.equal(receipt.listenerError, undefined)
const rows = (await pool.query("SELECT phase,state,result FROM flow_settings_intents WHERE receipt_id=$1 ORDER BY phase", [receipt.receiptId])).rows
assert.equal(rows.length, 2)
assert.deepEqual(rows.map(row => row.phase), ["configuration", "listener"])
for (const row of rows) {
assert.equal(row.state, "completed"); assert.equal(row.result.receiptId, receipt.receiptId)
assert.equal(row.result.receiptConfirmed, true)
assert(!JSON.stringify(row.result).includes("owned-private-sentinel"))
}
}
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)
await new Promise<void>(done => native.listen(0, "127.0.0.1", done))
const nativePort = (native.address() as { port: number }).port
serverId = Number((await pool.query(`INSERT INTO servers(name,host,port,use_ssl,verify_ssl,username,password,enabled)
VALUES('owned-active-services','127.0.0.1',$1,false,false,'owned-active','owned-password',false) RETURNING id`, [nativePort])).rows[0].id)
await settings.getTrafficFlowSettingsRow()
// An unknown configuration column exercises the complete production CAS.
await pool.query("ALTER TABLE traffic_flow_settings ADD COLUMN owned_active_opaque jsonb NOT NULL DEFAULT '{\"preserve\":true}'::jsonb")
const port = await reservePort()
await pool.query(`UPDATE traffic_flow_settings SET enabled=true,collector_ip='127.0.0.1',flow_listen_port=$1,
host_private_key='owned-private-sentinel',host_public_key='owned-public-sentinel',
peers_json=$2::jsonb WHERE id=1`, [port, JSON.stringify([{ serverId, name: "Owned active peer", publicKey: "owned-peer-sentinel", address: "127.0.0.1", allowedIps: ["127.0.0.1/32"] }])])
settings.invalidateTrafficFlowSettingsCache()
const original = await configuration()
const untouched = async () => (await pool.query(`SELECT
(SELECT count(*) FROM alert_outbox)::int AS alerts,
(SELECT count(*) FROM scheduler_runs)::int AS scheduler,
(SELECT count(*) FROM flow_ip_meta)::int AS ripe`)).rows[0]
const baseline = await untouched()
mainStarted = true
await ingest.startTrafficFlowListener(authorize)
await until(() => ingest.getFlowListenerState().bound, "Initial production worker did not bind")
assert.deepEqual(await totals(), { bytes: 0, packets: 0 })
if (process.env.MMAPP_OWN_FLOW_ACTIVE_PUBLIC === "true") {
const { buildApp } = await import("../index.js")
const { env } = await import("../config.js")
const actor = { id: "owned-active-public", email: "", name: "", apps: ["mm"],
permissions: ["mm:traffic:write", "mm:mcp:admin", "mm:mcp:approve"], expiresAt: Date.now() + 300000, issuedAt: Date.now() - 1000 }
await (await import("../modules/mcp/store.js")).updateMcpSettings({ enabled: true }, actor)
const api = app = await buildApp({ startScheduler: false, logger: false })
const origin = await api.listen({ host: "127.0.0.1", port: 0 })
const request = (method: "PUT" | "POST", url: string, permission: string[], payload?: object) => api.inject({
method, url, payload, headers: { authorization: "Bearer " + api.jwt.sign({
sub: actor.id, apps: actor.apps, permissions: permission,
}, { iss: env.authIssuer, expiresIn: "4m" }) },
})
const owner = async (url: string, payload: object) => {
const response = await request("POST", url, actor.permissions, payload)
assert.equal(response.statusCode, 200, response.body)
return response.json()
}
const { connection, token } = await owner("/api/mcp/connections", {
name: "Owned active NetFlow", mode: "approval", permissions: ["mm:traffic:write"],
expiresAt: new Date(Date.now() + 180000).toISOString(),
scope: { allowGlobal: true, serverIds: [serverId],
operationIds: ["netflow.settings.update", "traffic.flow.purge", "changes.apply", "operations.read"] },
limits: { mutationsPerHour: 10000, objectsPerPlan: 10000 },
})
const sdk = new Client({ name: "owned-active-netflow", version: "1.0.0" })
try {
await sdk.connect(new StreamableHTTPClientTransport(new URL("/mcp", origin), {
requestInit: { headers: { authorization: "Bearer " + token } },
}), { timeout: 5000 })
const call = async <T>(name: string, args: Record<string, unknown>) => {
const reply = await sdk.callTool({ name, arguments: args }, undefined, { timeout: 15000 })
assert(!reply.isError, JSON.stringify(reply.content))
return (reply.structuredContent as { result: T }).result
}
const execute = async <T>(tool: string, input: Record<string, unknown>, expectedVerification: "passed" | "inconclusive") => {
const plan = await call<{ planId: string; state: string }>(tool, input)
assert.equal(plan.state, "awaiting-approval")
await owner("/api/mcp/plans/" + plan.planId + "/decision", { approve: true })
const operation = await call<{ id: string }>("mm_change_apply", { planId: plan.planId, idempotencyKey: randomUUID() })
await until(async () => {
const state = (await pool.query("SELECT state FROM mcp_operations WHERE id=$1 AND connection_id=$2", [operation.id, connection.id])).rows[0]?.state
return state && !["pending", "running"].includes(state)
}, tool + " did not finish", 30000)
const terminal = await call<{ id: string; plan_id: string; state: string; verification: string; error_code?: string; steps: { state: string; result: T }[] }>(
"mm_operation_get", { operationId: operation.id })
assert.equal(terminal.id, operation.id)
assert.equal(terminal.plan_id, plan.planId)
assert.equal(terminal.state, "applied", terminal.error_code)
assert.equal(terminal.verification, expectedVerification, terminal.error_code)
assert.equal(terminal.steps.length, 1)
assert.equal(terminal.steps[0].state, expectedVerification === "passed" ? "verified" : "acknowledged")
return terminal.steps[0].result
}
const receive = async (bytes: number, seq: number) => {
const packets = ingest.getFlowWorkerHealth().packetsReceived
await send(port, bytes, seq)
await until(() => ingest.getFlowWorkerHealth().packetsReceived > packets, "Collector did not receive UDP")
await ingest.drainExistingTrafficFlowWriters(authorize, [serverId])
}
const bound = () => until(() => ingest.getFlowListenerState().bound && ingest.getFlowWorkerHealth().alive, "Worker did not resume")
const settingsPath = "/api/traffic/flow/settings", purgePath = "/api/traffic/flow/purge"
const patch = { mapServiceMinSharePct: Number(original.map_service_min_share_pct) }
const eventCount = async () => Number((await pool.query("SELECT count(*) AS n FROM events WHERE event_type='traffic.flow.purge'")).rows[0].n)
await receive(1500, 1)
assert.equal((await request("PUT", settingsPath, ["mm:traffic:read"], patch)).statusCode, 403)
const restSettings = await request("PUT", settingsPath, actor.permissions, patch)
assert.equal(restSettings.statusCode, 200, restSettings.body)
assert.equal(restSettings.json().ok, true)
assert.equal(restSettings.json().listenerError, undefined)
await bound()
assert.deepEqual(await configuration(), original)
assert.deepEqual(await totals(), { bytes: 1500, packets: 3 })
await intentReceipt(await execute<Awaited<ReturnType<typeof updateTrafficFlowSettingsWithListener>>>(
"mm_netflow_settings_update_plan", { settings: patch }, "passed"))
await bound()
assert.deepEqual(await configuration(), original)
assert.deepEqual(await totals(), { bytes: 1500, packets: 3 })
const assertPurged = async (events: number) => {
for (const table of Object.values(flowPurgeTables))
assert.equal(Number((await pool.query(`SELECT count(*) AS n FROM ${table}`)).rows[0].n), 0, table)
assert.equal(await eventCount(), events)
await bound()
assert.deepEqual(await configuration(), original)
}
assert.equal((await request("POST", purgePath, ["mm:traffic:read"])).statusCode, 403)
assert.deepEqual(await totals(), { bytes: 1500, packets: 3 })
const before = await eventCount()
const restPurge = await request("POST", purgePath, actor.permissions)
assert.equal(restPurge.statusCode, 200, restPurge.body)
const restResult = restPurge.json()
assert.equal(restResult.ok, true)
for (const field of ["listenerError", "partitionError", "eventError"]) assert.equal(restResult[field], undefined, field)
await assertPurged(before + 1)
await receive(2500, 2)
assert.deepEqual(await totals(), { bytes: 2500, packets: 3 })
const purged = await execute<Record<string, unknown>>("mm_netflow_purge_plan", {}, "inconclusive")
assert.equal(purged.ok, true)
assert.equal(purged.configurationPreserved, true)
for (const field of ["listenerError", "partitionError", "eventError"]) assert.equal(purged[field], undefined, field)
await assertPurged(before + 2)
await receive(3500, 3)
assert.deepEqual(await totals(), { bytes: 3500, packets: 3 })
assert.deepEqual(await untouched(), baseline)
console.log(JSON.stringify({ publicRestSettings: true, publicMcpSettings: true, publicRestPurge: true,
publicMcpPurge: true, purgeEvents: 2, postPurgeUdpBytes: 3500, localPostgres: true }))
} finally { await sdk.close() }
return
}
await intentReceipt(await settingsDuringFlush(port, 1500, 1, { enabled: false }))
assert.equal(ingest.getFlowListenerState().bound, false)
assert.equal(ingest.getFlowWorkerHealth().alive, false)
await portFree(port)
assert.deepEqual(await totals(), { bytes: 1500, packets: 3 })
assert.deepEqual(await configuration(), { ...original, enabled: false })
groups.push("production shared settings disable admitted during actual worker SQL flush, awaits retirement, conserves UDP and completes both durable phase receipts")
await intentReceipt(await updateTrafficFlowSettingsWithListener({ enabled: true }, { authorize }))
await until(() => ingest.getFlowListenerState().bound, "Shared settings re-enable did not bind a real worker")
assert.deepEqual(await configuration(), original)
assert.deepEqual(await totals(), { bytes: 1500, packets: 3 })
// Even an equal display setting must execute the complete production
// retire/flush/prune/start path. Readiness is proved separately via UDP.
const displayValue = Number(original.map_service_min_share_pct)
await intentReceipt(await settingsDuringFlush(port, 2500, 2, { mapServiceMinSharePct: displayValue }))
await until(() => ingest.getFlowListenerState().bound, "No-op display patch did not restore a real listener")
assert.deepEqual(await totals(), { bytes: 4000, packets: 6 })
assert.deepEqual(await configuration(), original)
groups.push("production settings re-enable and display no-op admitted during real SQL flush; UDP conserved and complete opaque/key/peer configuration unchanged")
assert.deepEqual(await totals(), { bytes: 4000, packets: 6 })
const purgeEventsBefore = Number((await pool.query("SELECT count(*) AS n FROM events WHERE event_type='traffic.flow.purge'")).rows[0].n)
// No sender runs concurrently with deletion. Zero rows is a fixture
// checkpoint, not a promise that a live collector remains empty afterwards.
let drainedBeforeDelete = false, purgeAdmitted = false
const purged = await duringBlockedFlush(port, 3500, 3, () => ({ task: purgeTrafficFlowWithEvent({
beforeDrain: async () => { purgeAdmitted = true },
beforeDelete: async client => {
// Read-only observation inside the genuine delete transaction, after its
// real stop/drain. This hook replaces no SQL, writer, fence or receipt.
const row = (await client.query("SELECT coalesce(sum(bytes),0)::bigint AS bytes,coalesce(sum(packets),0)::bigint AS packets FROM flow_buckets WHERE server_id=$1", [serverId])).rows[0]
assert.deepEqual(row, { bytes: 7500, packets: 9 }); drainedBeforeDelete = true
},
}), admitted: () => purgeAdmitted }))
assert.equal(drainedBeforeDelete, true)
assert.equal(purged.ok, true); assert.equal(purged.listenerError, undefined)
assert.equal(purged.partitionError, undefined); assert.equal(purged.eventError, undefined)
assert(purged.deleted.buckets > 0); assert(purged.deleted.minuteStats > 0)
for (const table of Object.values(flowPurgeTables))
assert.equal(Number((await pool.query(`SELECT count(*) AS n FROM ${table}`)).rows[0].n), 0, table)
assert.equal(Number((await pool.query("SELECT count(*) AS n FROM events WHERE event_type='traffic.flow.purge'")).rows[0].n), purgeEventsBefore + 1)
assert.deepEqual(await configuration(), original); assert.deepEqual(await untouched(), baseline)
await until(() => ingest.getFlowListenerState().bound, "Full shared purge did not restart a real listener")
assert.equal(ingest.getFlowWorkerHealth().alive, true)
groups.push("full production purge admitted during real SQL flush waits for worker drain, deletes all six flow tables, maintains partitions, restarts and journals one purge event")
await send(port, 4500, 4)
await until(() => ingest.getFlowWorkerHealth().packetsReceived >= 1, "Post-purge worker did not publish actual UDP observation")
const drained = await ingest.drainExistingTrafficFlowWriters(authorize, [serverId])
assert.equal(drained.existingWorker.workerPresent, true)
assert.deepEqual(await totals(), { bytes: 4500, packets: 3 })
await ingest.stopTrafficFlowListenerForDatabaseOperation(); mainStarted = false
await portFree(port)
assert.equal(ingest.getFlowWorkerHealth().alive, false)
assert.deepEqual(await configuration(), original); assert.deepEqual(await untouched(), baseline)
assert(ifaceGets > 0); assert.equal(fixtureError, undefined)
assert.equal(inFlightSqlFlushes, 3)
groups.push("post-purge production worker accepts new actual UDP/SQL; terminal tracked stop releases port and preserves configuration without scheduler/outbox/RIPE activity")
console.log(JSON.stringify({ accepted: groups.length, groups, ifaceGets, syntheticUdpDatagrams: 4,
beforePurgeBytes: 7500, afterPurgeBytes: 4500, settingsOperations: 3, inFlightSqlFlushes,
sharedProductionServices: true, publicRestMcpAuthorizationAccepted: false, realRouterInteroperabilityAccepted: false }))
} finally {
try {
if (mainStarted) await ingest.stopTrafficFlowListenerForDatabaseOperation()
await pauseRipeBackgroundWork()
if (serverId !== undefined) await pool.query("DELETE FROM servers WHERE id=$1", [serverId])
} finally {
try { await app?.close() } finally {
try { sender.close() } catch { /* setup failed before first send */ }
try { await new Promise<void>((done, reject) => native.close(error => error && (error as NodeJS.ErrnoException).code !== "ERR_SERVER_NOT_RUNNING" ? reject(error) : done())) }
finally { await closePool() }
}
}
}
}
await main()