Files
MikrotikManager/backend/src/test/mcp-flow-live.ts
T

113 lines
8.8 KiB
TypeScript

import assert from "node:assert/strict"
import { randomUUID } from "node:crypto"
import Fastify from "fastify"
import { serializerCompiler, validatorCompiler } from "@fastify/type-provider-zod"
import { mcpConnectionCreateSchema } from "@mmapp/contracts/mcp"
import type { FlowAnalyticsDto } from "@mmapp/contracts/traffic-flow"
import type { AuthUser } from "../lib/permissions.js"
import { pool } from "../db/index.js"
import { ensurePartitionFor } from "../db/partitions.js"
import { createMcpConnection, authenticateMcpToken, setConnectionStatus } from "../modules/mcp/store.js"
import { invokeMcpTool } from "../modules/mcp/runtime.js"
import { invalidateFlowAnalyticsCache } from "../services/traffic-flow-analytics.js"
import trafficFlowRoutes, { flowSseDiagnostics } from "../routes/traffic-flow.js"
import { invalidateFlowCatalogCache } from "../services/traffic-flow-topology.js"
import { resetFlowRingsForTests } from "../services/traffic-flow-ingest.js"
import { tryAcquireFlowLiveSlot, releaseFlowLiveSlot } from "../services/traffic-flow-live-slots.js"
import { disableRipeEnqueueForTests, resetRipeCacheForTests } from "../services/traffic-flow-ripe.js"
import { duringFlowSourceQuery } from "./mcp-flow-query-race.js"
type Observation = { events: Array<{ event: string; data: FlowAnalyticsDto; pages: Record<string, { total: number; nextOffset: number | null }> }>; observationComplete: boolean; forwardingVerified: boolean }
export async function verifyMcpFlowLive(actor: AuthUser) {
const owner = { ...actor, id: "flow-live-owner", permissions: [...actor.permissions, "mm:traffic:read"] }
const user = "flow-live-mixed", local = "flow-live-local", bucket = new Date(Date.now()-60000)
await pool.query("INSERT INTO servers(id,name,host,password) VALUES(114,'live-visible','192.0.2.114','NEVER_LIVE_PASSWORD'),(115,'NEVER_LIVE_SERVER','192.0.2.115','NEVER_LIVE_PASSWORD')")
const access = await createMcpConnection(mcpConnectionCreateSchema.parse({ name: "Scoped live", mode: "observer", expiresAt: new Date(Date.now()+1800000).toISOString(), permissions: ["mm:traffic:read"], scope: { serverIds: [114], operationIds: ["traffic.flow.live.read"], allowGlobal: false }, limits: { callsPerMinute: 120 } }), owner)
const principal = await authenticateMcpToken(access.token)
const http = Fastify(); http.setValidatorCompiler(validatorCompiler); http.setSerializerCompiler(serializerCompiler)
await http.register(trafficFlowRoutes,{prefix:"/api"})
const address = await http.listen({host:"127.0.0.1",port:0})
const read = (input: Record<string, unknown> = {}, signal?: AbortSignal) => invokeMcpTool(principal, "mm_netflow_live_observe", { serverId: 114, ...input }, signal) as Promise<Observation>
const put = (sid: number, iface: string, bytes: number, src: string) => pool.query("INSERT INTO flow_buckets(server_id,bucket_at,src,dst,proto,src_port,dst_port,bytes,packets,in_iface) VALUES($1,$2,$3,'8.8.8.8',6,12345,443,$4,1,$5)",[sid,bucket,src,bytes,iface])
try {
await ensurePartitionFor(pool,"flow_buckets","day",bucket)
for (const id of [user,local]) await pool.query("INSERT INTO app_users(id,login,name) VALUES($1,$1,$2)",[id,id === user ? "NEVER_LIVE_MIXED_USER" : id])
for (const [uid,sid,iface] of [[user,114,"live-mixed"],[user,115,"NEVER_LIVE_INTERFACE"],[local,114,"live-in"]] as const)
await pool.query("INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name) VALUES($1,$2,$3,$4)",[randomUUID(),uid,sid,iface])
resetFlowRingsForTests(); invalidateFlowCatalogCache(); invalidateFlowAnalyticsCache()
disableRipeEnqueueForTests()
await put(114,"live-in",100,"198.18.245.1"); await put(114,"live-mixed",200,"198.18.245.2"); await put(115,"NEVER_LIVE_INTERFACE",999,"198.18.245.3")
// Read the real SSE endpoint, including its event envelope and live engine defaults.
const httpAbort = new AbortController(), timeout = setTimeout(()=>httpAbort.abort(),10000)
let rest: { event: string; data: FlowAnalyticsDto }
const stages: unknown[] = []
const captureStage = (event: unknown) => stages.push(event)
flowSseDiagnostics.subscribe(captureStage)
try {
const response = await fetch(`${address}/api/traffic/flow/live?serverId=114`,{signal:httpAbort.signal})
assert.equal(response.status,200)
const diagnosticId = response.headers.get("x-mm-netflow-stream")
assert.match(diagnosticId ?? "", /^[a-f0-9-]{36}$/)
const reader = response.body!.getReader(), decoder = new TextDecoder(); let body = ""
for (;;) {
const chunk = await reader.read(); assert.equal(chunk.done,false)
body += decoder.decode(chunk.value,{stream:true})
const match = /event: (sample|error)\ndata: ([^\n]+)\n\n/.exec(body)
if (match) { rest={event:match[1],data:JSON.parse(match[2])}; break }
}
const events = stages as {streamId: string; stage: string; atUnixMs: number; monotonicMs: number}[]
assert.deepEqual(events.map(event => event.stage), ["open", "build-start", "build-ready", "write-start", "write-complete"])
for (const event of events) {
assert.deepEqual(Object.keys(event).sort(), ["atUnixMs", "monotonicMs", "stage", "streamId"])
assert.equal(event.streamId, diagnosticId)
assert.ok(Number.isSafeInteger(event.atUnixMs) && Number.isFinite(event.monotonicMs))
}
} finally {
flowSseDiagnostics.unsubscribe(captureStage)
clearTimeout(timeout)
httpAbort.abort()
}
assert.equal(rest!.event,"sample"); assert.ok(JSON.stringify(rest!).includes("NEVER_LIVE_MIXED_USER"))
let result = await read()
assert.equal(result.events[0].data.bytes,300); assert.equal(result.events[0].event,"sample")
assert.equal(result.observationComplete,true); assert.equal(result.forwardingVerified,false)
assert.ok(!JSON.stringify(result).includes("NEVER_"))
assert.deepEqual(result.events[0].data.protocols,rest!.data.protocols)
result = await read({limit:1}); assert.equal(result.events[0].data.conversationsList.length,1); assert.equal(result.events[0].pages.conversationsList.nextOffset,1)
assert.equal((await read({offset:1,limit:1})).events[0].data.conversationsList.length,1)
assert.equal((await read({userId:local})).events[0].data.bytes,100)
assert.equal((await read({interface:"live-in"})).events[0].data.bytes,100)
await assert.rejects(read({userId:user})); await assert.rejects(read({serverId:115})); await assert.rejects(read({samples:4})); await assert.rejects(read({minutes:15})); await assert.rejects(read({skipHeavy:true}))
// Actual source changes between live ticks must appear in the next event, bypassing REST cache.
// Inject after the bounded data projection. The scalar preflight checks its size.
result = await duringFlowSourceQuery(pool, ["FROM flow_buckets", 'AS "__flowPresent"'],
() => put(114, "live-in", 50, "198.18.245.4"), () => read({ samples: 2 }))
assert.equal(result.events.length, 2)
assert.equal(result.events[0].data.bytes, 300)
assert.equal(result.events[1].data.bytes, 350)
// A finished sample cannot be published after authorization is revoked during its SQL read.
await duringFlowSourceQuery(pool, "FROM flow_buckets",
() => setConnectionStatus(access.connection.id, "paused", owner), () => assert.rejects(read()))
await setConnectionStatus(access.connection.id,"active",owner)
// Abort after a real source read started: a completed SQL result is still unpublished.
const duringReadAbort = new AbortController()
await duringFlowSourceQuery(pool, "FROM flow_buckets", async () => duringReadAbort.abort(),
() => assert.rejects(read({}, duringReadAbort.signal)))
const abort = new AbortController(); abort.abort(); await assert.rejects(read({},abort.signal))
let acquired = 0
try { while (tryAcquireFlowLiveSlot()) acquired++; assert.equal(acquired,4); await assert.rejects(read()) }
finally { while (acquired-- > 0) releaseFlowLiveSlot() }
assert.equal((await read()).events[0].data.bytes,350)
assert.equal((await pool.query("SELECT count(*)::int AS n FROM mcp_plans WHERE connection_id=$1",[access.connection.id])).rows[0].n,0)
console.log("✓ NetFlow live: actual shared REST engine, uncached changing ticks, complete DTO paging, SQL scope/mixed user exclusion, pause/cancel publication fences, shared slots and no plans")
} finally {
await http.close()
await setConnectionStatus(access.connection.id,"paused",owner)
await pool.query("DELETE FROM user_interface_bindings WHERE user_id=ANY($1::text[])",[[user,local]])
await pool.query("DELETE FROM app_users WHERE id=ANY($1::text[])",[[user,local]])
await pool.query("DELETE FROM flow_buckets WHERE server_id IN (114,115)"); await pool.query("DELETE FROM servers WHERE id IN (114,115)")
resetFlowRingsForTests(); invalidateFlowCatalogCache(); invalidateFlowAnalyticsCache()
resetRipeCacheForTests()
}
}