69 lines
6.8 KiB
TypeScript
69 lines
6.8 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { randomUUID } from "node:crypto"
|
|
import { basename, dirname, resolve } from "node:path"
|
|
|
|
/** Real legacy entrypoint/service acceptance, called only by an owned private
|
|
* PostgreSQL profile. Requires EMPTY source/cubes; never clears foreign rows to
|
|
* satisfy this precondition. Uses actual existing-writer drain, never a stub. */
|
|
export async function acceptLegacyFlowFactsRebuildSql() {
|
|
assert.equal(process.env.MMAPP_OWN_PROBE_JOURNAL, "true")
|
|
const url = new URL(process.env.DATABASE_URL ?? "")
|
|
assert.equal(url.hostname, "127.0.0.1"); assert.equal(url.pathname, "/postgres")
|
|
assert(["postgres:", "postgresql:"].includes(url.protocol))
|
|
assert(process.env.MCP_STATE_DIR && basename(dirname(resolve(process.env.MCP_STATE_DIR))).startsWith("mm-mcp-test-"))
|
|
const { pool } = await import("../db/index.js")
|
|
const { ensurePartitionFor } = await import("../db/partitions.js")
|
|
const { rebuildFlowFactsFromBuckets } = await import("./traffic-flow-facts-rebuild.js")
|
|
const { withPartitionWrite } = await import("./partition-write-transaction.js")
|
|
assert.equal((await pool.query("SELECT current_database() AS name")).rows[0].name, "postgres")
|
|
for (const table of ["flow_buckets", "flow_hour_facts", "flow_daily_facts"]) assert.equal((await pool.query(`SELECT count(*)::int AS n FROM ${table}`)).rows[0].n, 0, "Dedicated empty source/cube profile required; foreign fixture rows are never deleted")
|
|
const protectionId = randomUUID(), userId = `legacy-rebuild-${randomUUID()}`, bindingId = randomUUID()
|
|
const day = "2102-02-04", unrelatedDay = "2102-02-03", target = `${day}T10:00:00Z`
|
|
const serverId = Number((await pool.query("INSERT INTO servers(name,host,port,enabled,type,wan_uplinks) VALUES('legacy-rebuild-owned','127.0.0.1',9,false,'jump-host',$1::jsonb) RETURNING id", [JSON.stringify([{ iface: "ether1", ip: "127.0.0.1" }])])).rows[0].id)
|
|
let protectionInserted = false
|
|
const savedFetch = globalThis.fetch
|
|
let networkAttempts = 0
|
|
globalThis.fetch = (async () => { networkAttempts++; throw Error("Owned legacy rebuild acceptance forbids network I/O") }) as typeof fetch
|
|
try {
|
|
for (const [parent, kind, at] of [["flow_buckets", "day", target], ["flow_hour_facts", "day", target], ["flow_daily_facts", "month", target], ["flow_hour_facts", "day", `${unrelatedDay}T10:00:00Z`], ["server_snapshots", "week", target]] as const) await ensurePartitionFor(pool, parent, kind, new Date(at))
|
|
await withPartitionWrite(async ({ client }) => {
|
|
await client.query("INSERT INTO app_users(id,login,name) VALUES($1,$1,'Owned legacy rebuild fixture')", [userId])
|
|
await client.query("INSERT INTO user_interface_bindings(id,user_id,server_id,interface_name,interface_type) VALUES($1,$2,$3,'legacy-client','gre')", [bindingId, userId, serverId])
|
|
await client.query("INSERT INTO server_snapshots(server_id,polled_at,status,raw_interfaces) VALUES($1,$2,'online',$3::jsonb)", [serverId, target, JSON.stringify([{ name: "legacy-client", type: "gre" }, { name: "ether1", type: "ether" }])])
|
|
for (const [minute, bytes, packets] of [["10:01", 10, 1], ["10:02", 5, 2]] as const) await client.query("INSERT INTO flow_buckets(server_id,bucket_at,src,dst,proto,src_port,dst_port,bytes,packets,in_iface,out_iface) VALUES($1,$2,'95.167.1.10','8.8.8.8',6,1234,443,$3,$4,'legacy-client','ether1')", [serverId, `${day}T${minute}:00Z`, bytes, packets])
|
|
for (const [at, service, bytes] of [[target, "legacy-target-sentinel", 999], [`${unrelatedDay}T10:00:00Z`, "legacy-unrelated-sentinel", 55]] as const) {
|
|
await client.query("INSERT INTO flow_hour_facts(server_id,bucket_at,iface,country,service,asn,bytes,packets) VALUES($1,$2,'legacy-client','XX',$3,0,$4,9)", [serverId, at, service, bytes])
|
|
await client.query("INSERT INTO flow_daily_facts(server_id,day,iface,country,service,asn,bytes,packets) VALUES($1,$2::timestamptz::date,'legacy-client','XX',$3,0,$4,9)", [serverId, at, service, bytes])
|
|
}
|
|
})
|
|
const beforeReceipts = (await pool.query("SELECT count(*)::int AS n FROM flow_write_receipts WHERE kind='rebuild'")).rows[0].n
|
|
const result = await rebuildFlowFactsFromBuckets()
|
|
assert.deepEqual(result, { ok: true, buckets: 2, facts: 1, days: [day] })
|
|
assert.equal(Object.keys(result).length, 4, "Public legacy result contract remains unchanged")
|
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM flow_write_receipts WHERE kind='rebuild'")).rows[0].n, beforeReceipts + 1)
|
|
const receipt = (await pool.query("SELECT batch_id,result FROM flow_write_receipts WHERE kind='rebuild' ORDER BY committed_at DESC LIMIT 1")).rows[0]
|
|
assert(receipt && receipt.result.jobId === receipt.batch_id)
|
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM events WHERE id=$1 AND event_type='traffic.flow.rebuild_facts'", [receipt.batch_id])).rows[0].n, 1)
|
|
for (const table of ["flow_hour_facts", "flow_daily_facts"]) {
|
|
const total = (await pool.query(`SELECT sum(bytes)::int AS bytes,sum(packets)::int AS packets FROM ${table} WHERE server_id=$1 AND service<>'legacy-unrelated-sentinel'`, [serverId])).rows[0]
|
|
assert.deepEqual(total, { bytes: 15, packets: 3 })
|
|
assert.equal((await pool.query(`SELECT sum(bytes)::int AS n FROM ${table} WHERE server_id=$1 AND service='legacy-unrelated-sentinel'`, [serverId])).rows[0].n, 55)
|
|
}
|
|
// A future leaf protection is part of the actual service's full closure;
|
|
// it is rejected without any fake local approval/MCP principal.
|
|
await pool.query("INSERT INTO mcp_protections(id,object_ref,created_by) VALUES($1,$2::jsonb,'legacy-rebuild-owned-acceptance')", [protectionId, JSON.stringify({ kind: "database-partition", id: "flow_hour_facts/flow_hour_facts_d_21990101", protection: "deny" })])
|
|
protectionInserted = true
|
|
const beforeDenied = (await pool.query("SELECT count(*)::int AS n FROM flow_write_receipts WHERE kind='rebuild'")).rows[0].n
|
|
await assert.rejects(rebuildFlowFactsFromBuckets(), /защищённый объект|защит|protec/i)
|
|
assert.equal((await pool.query("SELECT count(*)::int AS n FROM flow_write_receipts WHERE kind='rebuild'")).rows[0].n, beforeDenied)
|
|
assert.equal(networkAttempts, 0)
|
|
return { cases: 3, actualLegacyEntrypoint: true, actualSafeService: true, actualExistingWriterDrain: true, noWorkerStartedByHelper: true, futureLeafProtectionRefused: true, unknownCommitPassthrough: "inert wrapper only", nativeNetworkIo: false }
|
|
} finally {
|
|
globalThis.fetch = savedFetch
|
|
// Exact-ID fixture cleanup is explicitly authorized by the parent task.
|
|
// Append-only audit, history, events and durable receipts remain untouched.
|
|
if (protectionInserted) await pool.query("DELETE FROM mcp_protections WHERE id=$1 AND created_by='legacy-rebuild-owned-acceptance'", [protectionId])
|
|
await pool.query("UPDATE servers SET enabled=false WHERE id=$1", [serverId])
|
|
}
|
|
}
|