371 lines
21 KiB
JSON
371 lines
21 KiB
JSON
{
|
|
"schemaVersion": 1,
|
|
"kind": "read-only-service-audit",
|
|
"auditId": "mcp-flow-facts-rebuild-20261024T120321Z",
|
|
"createdAt": "2026-10-24T12:03:21Z",
|
|
"immutableSnapshot": true,
|
|
"fullPlanComplete": false,
|
|
"adapterImplemented": false,
|
|
"route": {
|
|
"method": "POST",
|
|
"path": "/api/traffic/flow/rebuild-facts",
|
|
"handler": "backend/src/routes/traffic-flow.ts:171",
|
|
"service": "rebuildFlowFactsFromBuckets"
|
|
},
|
|
"conclusion": "Current REST service is not a safe completed MCP adapter. Exact intended REST semantics require a shared executor fix; wrapping the current implementation would retain partial flush, races and non-atomic publication.",
|
|
"activity": {
|
|
"productSourceModified": false,
|
|
"auditArtifactOnly": true,
|
|
"sqlExecuted": false,
|
|
"networkRequestsExecuted": false,
|
|
"nativeCommandsExecuted": false,
|
|
"collectorsStarted": false,
|
|
"alertsExecuted": false,
|
|
"telegramMessagesSent": false,
|
|
"testsExecuted": false,
|
|
"methods": [
|
|
"Read local source text",
|
|
"Search local source references",
|
|
"Compute SHA-256 of source files"
|
|
],
|
|
"limitation": "Static call-path audit; no runtime or SQL acceptance evidence is claimed. Existing earlier acceptance runs and unrelated agent activity are outside this audit."
|
|
},
|
|
"sourceHashes": {
|
|
"algorithm": "SHA-256",
|
|
"capturedAt": "2026-10-24T12:03:21Z",
|
|
"files": [
|
|
{
|
|
"path": "backend/src/services/traffic-flow-facts-rebuild.ts",
|
|
"sha256": "291b3fab8d240ea0ba65d46ad77f3c48246483c303e8dbab395232db13bc8395"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-engine.ts",
|
|
"sha256": "fbd414e30b45f0deab774c2a0c8350d49990c8eed6d169efdfa885f917ebe5e3"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-facts.ts",
|
|
"sha256": "0f2adbe6ed2bbf1ae884df523913ab31799f1b5658049d5dc6a5ac16f3466cd7"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-ingest.ts",
|
|
"sha256": "1a393b2db70a4e4bf964119f00e1200ed7bdb28469ddb2dd7e30760cb4ed2a7a"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-collector-worker.ts",
|
|
"sha256": "7ae25aa008505c43dd4f55454468506372901e26c8ba533cde4a65a46f1def57"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-topology.ts",
|
|
"sha256": "fc85bc2c4568361c240e7c9f33bf7d0d1dac728a05ca1a4f8abe8b3bfeedca87"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-ifindex.ts",
|
|
"sha256": "fbd7e46c38c3b145ef5e6aa723a32d88aa23548017743618d5f48d2af8c293a4"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-dest.ts",
|
|
"sha256": "45c08fff0bb6a984ae1322762c9a5df193c7086e19c20c23a25555e2f64ca158"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-classify.ts",
|
|
"sha256": "6c4c9fcb2ed1011a305580a60ab2dcb2a4e60fce359fa7324be59a7350dc13d2"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-geoip.ts",
|
|
"sha256": "f856cd9dc3a4c671eb7c5f10d3d62411777273f110226b25cd18f4a8fec8e01b"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-ripe.ts",
|
|
"sha256": "a178223bb42f6690250f42109776c48c268b11d68a11d92e023b53a1b8c12607"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-facts-filter.ts",
|
|
"sha256": "981032350a7a0792fe695ec540c9c60e93530d4c5f0dc75a01c6fa6e9b80d201"
|
|
},
|
|
{
|
|
"path": "backend/src/routes/traffic-flow.ts",
|
|
"sha256": "0053cb3ff5fe0530e81dad31178eff00d1a8b649a96b813f641cc0a3250db379"
|
|
},
|
|
{
|
|
"path": "backend/src/lib/permissions.ts",
|
|
"sha256": "ab97b8902c916233d68f0cf18adcf68f4ea589d754957e48c7a35053fbf9001b"
|
|
},
|
|
{
|
|
"path": "backend/src/db/index.ts",
|
|
"sha256": "b76334b2a912d016c0505b9eafb04d1dec2cce8a3e5e5dfdc85ad93b99996ea0"
|
|
},
|
|
{
|
|
"path": "backend/src/modules/events/service/events-service.ts",
|
|
"sha256": "5b6494dcf1fc347efc91b2f20b0b264464cb772499b6a6c1c976e4698643fa9b"
|
|
},
|
|
{
|
|
"path": "backend/src/modules/events/repository/events-repository.ts",
|
|
"sha256": "06c1d50df803878581d4a81284b4cf6043e7bb224cfcd694a0d17f56839d3318"
|
|
},
|
|
{
|
|
"path": "backend/src/services/config-mutation-policy.ts",
|
|
"sha256": "17e7080b376b65ba8195f67469858e6ea3cb92540b2292e0e4b2f576565ddd7e"
|
|
},
|
|
{
|
|
"path": "backend/src/services/alert-engine/execution-access.ts",
|
|
"sha256": "f2c562ed35abe1ef5388dfd00622ae19403e5d2f9f706472ba5b41c85dc76687"
|
|
}
|
|
]
|
|
},
|
|
"actualSideEffects": [
|
|
{
|
|
"stage": "Initial engine flush",
|
|
"file": "backend/src/services/traffic-flow-facts-rebuild.ts",
|
|
"function": "rebuildFlowFactsFromBuckets",
|
|
"line": 32,
|
|
"calls": "flushEngineNow({ prune: false })",
|
|
"effects": [
|
|
"Prunes in-memory recent entries and rolls rings",
|
|
"Persists traffic_flow_settings runtime counters, errors, exporter and updated_at through persistListenerStats",
|
|
"Sanitizes/top-N selects main-isolate pending flows, clears pending, merges recent and writes flow_buckets",
|
|
"Writes flow_minute_stats, flow_minute_dims and flow_daily_dims; clears minute accumulators",
|
|
"capDailyAsn can DELETE and merge today's ASN tail in flow_daily_dims across servers",
|
|
"Flushes shared main-isolate hourFacts into flow_hour_facts and flow_daily_facts; may create partitions"
|
|
],
|
|
"notPerformed": "pruneStored SQL retention pruning is disabled for this explicit flush by prune:false",
|
|
"sourceFunctions": [
|
|
"traffic-flow-engine.ts:flushPendingInternal",
|
|
"traffic-flow-engine.ts:persistListenerStats",
|
|
"traffic-flow-engine.ts:upsertFlowBuckets",
|
|
"traffic-flow-engine.ts:upsertMinuteAndDaily",
|
|
"traffic-flow-engine.ts:capDailyAsn"
|
|
]
|
|
},
|
|
{
|
|
"stage": "Fact replacement",
|
|
"file": "backend/src/services/traffic-flow-facts-rebuild.ts",
|
|
"function": "rebuildFlowFactsFromBuckets",
|
|
"effects": [
|
|
"discardPendingFacts clears the process-local shared hourFacts map",
|
|
"Finds all UTC calendar days present anywhere in flow_buckets",
|
|
"If no bucket days exist, returns without deleting old facts",
|
|
"Deletes flow_hour_facts and flow_daily_facts for those days across every server, including servers with no bucket rows of their own",
|
|
"Scans all retained buckets in batches of 4000 with LIMIT/OFFSET and ORDER BY bucket_at,server_id",
|
|
"Uses current topology/catalog/interface-name and classification state, filters eligible flows, and adds them to the shared accumulator",
|
|
"flushFlowFacts performs additive hour UPSERT then additive daily UPSERT in separate SQL requests",
|
|
"Returns final all-bucket COUNT, emitted capped fact-tuple count, and initial day list; these are not a transactional source snapshot"
|
|
],
|
|
"partitionEffects": "ensurePartitionFor may execute partition DDL before fact publication"
|
|
},
|
|
{
|
|
"stage": "HTTP journal publication",
|
|
"file": "backend/src/routes/traffic-flow.ts",
|
|
"function": "POST /traffic/flow/rebuild-facts handler",
|
|
"effects": [
|
|
"After service success appends one traffic.flow.rebuild_facts event with a fresh ID",
|
|
"A journal failure becomes HTTP 500 even if cube mutations already committed"
|
|
],
|
|
"eventPath": [
|
|
"modules/events/service/events-service.ts:appendEvent",
|
|
"modules/events/repository/events-repository.ts:insertEventsBatch"
|
|
],
|
|
"directNotifications": "These functions insert events only; no direct alert-engine run, outbox dispatch or Telegram send is present in this route call path."
|
|
}
|
|
],
|
|
"readAndClassificationDependencies": [
|
|
"loadFlowTopology(): global servers, app_users, user_interface_bindings, current snapshot-derived interface types and process topology cache",
|
|
"getServerCatalog(): global server catalog and process cache",
|
|
"canonicalFactIface(): process-local ifIndex/name cache; does not itself refresh RouterOS",
|
|
"resolveInternetDest/shouldWriteFlowFact: NAT, endpoint, plane, WAN/tunnel/client filtering",
|
|
"resolveFlowIp(): loaded local GeoIP readers followed by RIPE memory cache",
|
|
"lookupRipeCached may initiate tracked asynchronous SQL loadPg of flow_ip_meta; rebuild does not await a stable cold-cache load",
|
|
"classifyFlowDst reads cached EvoBGP classification data; its classifier does not itself call refreshFlowCatalogInBackground or fetch the catalog",
|
|
"No direct call to startTrafficFlowListener, restartTrafficFlowListenerAfterDatabaseOperation, scheduler refresh/run, alert run or Telegram send was found in rebuild."
|
|
],
|
|
"scopeAndAuthorization": {
|
|
"existingRestPermission": "mm:traffic:write",
|
|
"mcpEffect": "write",
|
|
"mcpScope": "global",
|
|
"requiresHuman": true,
|
|
"allowGlobalRequired": true,
|
|
"completeScope": "Require full current server catalog before protected source reads or draining. Validate union of server IDs in all affected retained/derived/pending inputs, including facts on bucket days for servers with no matching buckets. Orphan/ungranted IDs must fail closed; current-server scope must not silently authorize historical foreign rows.",
|
|
"protectionObjects": [
|
|
"netflow-facts/global",
|
|
"netflow-settings/1",
|
|
"events-journal/global",
|
|
"Each affected server and its registered protections",
|
|
"Affected NetFlow stores/partitions if domain protections cover them"
|
|
],
|
|
"minimumPermission": "mm:traffic:write plus global/full-server policy, owner and temporary-grant checks; no collector/alert/Telegram capability is implied by this permission.",
|
|
"rawSecrets": "No router passwords, WG keys, EvoBGP API key, user peer keys or raw traffic rows should be placed in public plan/audit/result. Use bounded metadata and purpose-HMAC source/configuration proofs."
|
|
},
|
|
"failureAndRaceFindings": [
|
|
{
|
|
"id": "flush-errors-swallowed",
|
|
"sources": [
|
|
"traffic-flow-engine.ts:956-1038"
|
|
],
|
|
"finding": "Stats, bucket persistence, rollup/cap and fact flush failures can be swallowed; bucket persistence also has partial per-row fallback. flushEngineNow resolving does not prove all pending data persisted."
|
|
},
|
|
{
|
|
"id": "pending-cleared-before-success",
|
|
"sources": [
|
|
"traffic-flow-engine.ts:995",
|
|
"traffic-flow-facts.ts:collectCappedFacts"
|
|
],
|
|
"finding": "Engine clears pending before persistence; collectCappedFacts clears hourFacts before partition creation/inserts. Later failures have no durable replay/restore acknowledgement."
|
|
},
|
|
{
|
|
"id": "no-atomic-hour-daily-replacement",
|
|
"sources": [
|
|
"traffic-flow-facts-rebuild.ts:45-51",
|
|
"traffic-flow-facts.ts:flushFlowFacts"
|
|
],
|
|
"finding": "Two deletes, partition work, hour UPSERT and daily UPSERT are not one transaction. Failures can leave empty/partial/mismatched cubes; additive replay can duplicate data."
|
|
},
|
|
{
|
|
"id": "same-isolate-accumulator-race",
|
|
"sources": [
|
|
"traffic-flow-facts-rebuild.ts:discardPendingFacts/bumpFlowFact/flushFlowFacts",
|
|
"traffic-flow-engine.ts:onEngineTick"
|
|
],
|
|
"finding": "Any main-isolate ingestion/tick can interleave with awaited rebuild SQL and use the same hourFacts map; rebuild may discard live increments or flush increments that were not in its source snapshot."
|
|
},
|
|
{
|
|
"id": "worker-is-separate-writer",
|
|
"sources": [
|
|
"traffic-flow-collector-worker.ts:128",
|
|
"traffic-flow-ingest.ts:spawnWorker",
|
|
"traffic-flow-engine.ts:flushPendingInternal"
|
|
],
|
|
"finding": "Production worker owns separate isolate-local engine/fact maps and periodically flushes to the same PostgreSQL tables. Main-isolate flushEngineNow does not drain that worker. The rebuild advisory lock is not acquired by ordinary worker/timer writes."
|
|
},
|
|
{
|
|
"id": "moving-offset-and-day-window",
|
|
"sources": [
|
|
"traffic-flow-facts-rebuild.ts:35-40,84",
|
|
"traffic-flow-collector-worker.ts:128"
|
|
],
|
|
"finding": "Concurrent ingestion and ordinary retention pruning can change rows between OFFSET pages and after day enumeration. ORDER BY bucket_at,server_id is not a unique order. Final COUNT can describe different data from processed rows."
|
|
},
|
|
{
|
|
"id": "changing-classification-inputs",
|
|
"sources": [
|
|
"traffic-flow-topology.ts:loadFlowTopology",
|
|
"traffic-flow-ifindex.ts:canonicalFactIface",
|
|
"traffic-flow-ripe.ts:lookupRipeCached/loadPg"
|
|
],
|
|
"finding": "Process caches, asynchronous cold RIPE load, ifIndex updates and topology changes can alter classification during one rebuild without a sealed classifier snapshot."
|
|
},
|
|
{
|
|
"id": "locking-and-outcome",
|
|
"sources": [
|
|
"db/index.ts:withAdvisoryLock",
|
|
"traffic-flow-facts-rebuild.ts:FACT_REBUILD_LOCK_KEY"
|
|
],
|
|
"finding": "Current rebuild waits on a session advisory lock without bounded try-lock admission. Purge now shares the rebuild exclusion key, but normal engine/worker writes do not. There is no durable commit receipt to distinguish lost response from no effect."
|
|
}
|
|
],
|
|
"proposedSharedExecutor": {
|
|
"status": "Design only; not implemented by this audit",
|
|
"preservedSemantics": [
|
|
"Global all-retained-buckets rebuild after explicitly acknowledged pending ingestion drain",
|
|
"Replace only UTC days represented by the authoritative source snapshot",
|
|
"No bucket days means no cube deletion",
|
|
"Keep same filtering/NAT/plane/classification rules and ASN/tuple caps",
|
|
"One REST-equivalent completion event and truthful counts; report reconstruction from retained/top-N data rather than full original traffic"
|
|
],
|
|
"requiredRestFix": "Both REST and MCP must delegate to the corrected executor. The existing sequence of swallowed flushes, shared accumulator and separately committed deletes/inserts must not be advertised as exact safe parity.",
|
|
"files": [
|
|
{
|
|
"path": "backend/src/services/traffic-flow-facts-rebuild-execution.ts",
|
|
"change": "New shared staged executor with injectable, narrow transaction/ingest-barrier/classification/event dependencies"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-facts-rebuild.ts",
|
|
"change": "Production dependency adapter delegating to executor"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-facts.ts",
|
|
"change": "Extract pure capped aggregation over an isolated accumulator; keep legacy live accumulator adapter separate"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-engine.ts",
|
|
"change": "Strict drain receipt, owned pending batches retained until commit acknowledgement, writer fence integration"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-collector-worker.ts",
|
|
"change": "Explicit writer-barrier handshake and epoch/token fencing covering timer, stop/final flush and batch SQL dispatch"
|
|
},
|
|
{
|
|
"path": "backend/src/services/traffic-flow-ingest.ts",
|
|
"change": "Bounded barrier orchestration; do not reuse unconditional stop/restart controller lifecycle"
|
|
},
|
|
{
|
|
"path": "backend/src/routes/traffic-flow.ts",
|
|
"change": "Delegate rebuild plus event to shared executor; preserve API result fields and expose partial/unknown truthfully"
|
|
},
|
|
{
|
|
"path": "backend/src/modules/mcp/flow-facts-rebuild-actions.ts",
|
|
"change": "New global human-approved action/service with current, execute, verify and read-only reconcile"
|
|
},
|
|
{
|
|
"path": "backend/src/test/mcp-flow-facts-rebuild.ts",
|
|
"change": "Disposable SQL/actual HTTP acceptance with effect traps and fault injection"
|
|
}
|
|
],
|
|
"stages": [
|
|
{
|
|
"order": 1,
|
|
"name": "Authorize and admit",
|
|
"work": "Recheck principal, owner/policy/grant generation, full affected server scope and all protections before any drain. Acquire application mutation lock and bounded try-lock shared with rebuild/purge; validate row/day/time/output limits without truncation."
|
|
},
|
|
{
|
|
"order": 2,
|
|
"name": "Fence existing writers",
|
|
"work": "Install a flow-specific writer lease/barrier honored by main engine and every worker/timer/final-flush path; wait boundedly for already-dispatched SQL. New batches remain owned/bounded and cannot write across the publication epoch. Never implicitly start/restart a collector or invoke alert/notification execution."
|
|
},
|
|
{
|
|
"order": 3,
|
|
"name": "Strict pending drain",
|
|
"work": "Drain only existing authorized ingestion with explicit batch identifiers and durable commit acknowledgement. Failure stops before destructive replacement. Unacknowledged pending batches are not cleared or replayed blindly; record unknown and release only safe leases."
|
|
},
|
|
{
|
|
"order": 4,
|
|
"name": "Capture stable source",
|
|
"work": "Use one transaction/client snapshot and deterministic cursor, not moving OFFSET pages. Capture topology/bindings/snapshot-ifIndex, GeoIP/RIPE/catalog versions or immutable bounded classification snapshots; do not initiate background enrichment. Recheck source/grant proof and limits on each batch."
|
|
},
|
|
{
|
|
"order": 5,
|
|
"name": "Build isolated result",
|
|
"work": "Aggregate into private job-owned state/staging using the same pure normalization/filter/capping engine. Reject unsafe integers/invalid rows/overflow and cap exceedance explicitly. No shared hourFacts mutation and no live cube deletion yet."
|
|
},
|
|
{
|
|
"order": 6,
|
|
"name": "Atomic publication",
|
|
"work": "Under the writer lease, revalidate source/config/protections/grant on the same transaction client. Create required partitions safely before publication, then atomically delete/replace both cubes for source days, insert the predetermined completion event ID and durable job receipt with source/result proofs. Commit once; never retry an unconfirmed COMMIT."
|
|
},
|
|
{
|
|
"order": 7,
|
|
"name": "Verify and release",
|
|
"work": "Read receipt and bounded result proofs, preserve unrelated days and tables, then release only the existing writer barrier. Unconfirmed outcome stays unknown; read-only reconcile checks durable receipt/proofs without rerunning rebuild or resuming ungranted controllers."
|
|
}
|
|
],
|
|
"classificationAndBudgetNotes": "Plan counts are bounded estimates unless exact data is sealed. State clearly whether approval authorizes all retained data at execution or a fixed source snapshot; do not silently substitute a partial/stale snapshot. Budget includes drain, publication, one event and bounded partition work. Capture classifier changes before destructive publication."
|
|
},
|
|
"productionSideEffectFences": {
|
|
"noImplicitPermissionExpansion": true,
|
|
"mandatory": [
|
|
"Enforce actor/grant/protection checks at strict drain SQL, partition DDL and cube/event commit boundaries",
|
|
"Collector/timer writer paths must check an active lease and current generation before dispatch; inherited closed contexts and stale leases fail closed",
|
|
"Rebuild must not call collector start/restart, scheduler refresh/run, alert run/outbox dispatch, Telegram send, RIPE HTTP enqueue or EvoBGP refresh as cleanup/recovery",
|
|
"Existing optional alert execution-access and provider/send fences remain intact; do not replace them with no-op callbacks, flags or test-only bypasses",
|
|
"A background controller that already has separate authorization may continue outside the audited job; the job cannot manufacture or extend that authorization"
|
|
],
|
|
"automaticAcceptanceChecks": [
|
|
"Production boundaries for collector start/restart, scheduler/alerts/outbox/Telegram are trapped/observed; a rebuild without those grants causes zero such effects",
|
|
"Use restrictive no-collector/no-alert/no-Telegram grants and retain their real authorization checks; assert denied/stale inherited work cannot dispatch",
|
|
"Assert no outbound HTTP/RouterOS/SSH/agent calls; isolated local fixtures only when separately testing a boundary",
|
|
"Snapshot collector enabled/configuration, worker generation/listener identity, scheduler runs, alert/outbox/delivery rows and Telegram dispatch counts before and after",
|
|
"Inject deny/revoke/cancel before drain, during batch reads, before commit and after commit response loss; assert no hidden recovery start or notification",
|
|
"Actual SQL/HTTP parity tests cover concurrent timer/worker writer barriers, flush failure, empty source, same-day foreign facts, caps/overflow, classifier drift, atomic hour/daily rollback, event failure, lost COMMIT and no replay",
|
|
"Verify unrelated rows/days/configuration and key/peer material stay unchanged; public plan/results/audit contain no raw secrets or traffic"
|
|
]
|
|
}
|
|
}
|