Files
MikrotikManager/backend/src/services/router-configuration-guard.sql-helper.ts
T

163 lines
15 KiB
TypeScript

/** Owned PostgreSQL/localhost acceptance; execution is explicitly root-owned.
* The factory must explicitly provision each isolated source/head/key/role;
* this helper never initializes a source merely because its tables are empty. */
import assert from "node:assert/strict"
import { createHash, randomUUID } from "node:crypto"
import type { Pool } from "pg"
import { canonicalBandwidthNodeValue as canonical } from "./bandwidth-node-bootstrap.js"
import { BANDWIDTH_CONTROL_ROLE_SQL } from "./bandwidth-control-role.js"
import { BANDWIDTH_CONTROL_CATALOG_SQL } from "./bandwidth-control-catalog.js"
import { BANDWIDTH_NODE_REGISTRY_ROLE_SQL } from "./bandwidth-node-registry-role.js"
import { BANDWIDTH_NODE_REGISTRY_CATALOG_SQL, BANDWIDTH_PEER_MANAGED_REGISTRY_CATALOG_SQL, BANDWIDTH_PEER_REGISTRY_INCOMING_SQL } from "./bandwidth-node-registry-catalog.js"
import { ROUTER_GUARD_LOCK, ROUTER_GUARD_ARCHIVE_EXCLUSION, ROUTER_GUARD_INTEGRATION_REQUIREMENTS } from "./router-configuration-guard-schema.js"
import { RouterGuardRefused, RouterGuardUnknown, validateRouterGuardDatabaseIsolation, type createConfiguredRouterGuard, type RouterGuardWriteBinding, type RouterGuardNativeBinding } from "./router-configuration-guard.js"
export const ROUTER_GUARD_ACCEPTANCE_STATUS = Object.freeze({ wired: false, actualPgRun: false, appMigrationsChanged: false, unknownGc: false,
archiveExclusionRequired: ROUTER_GUARD_ARCHIVE_EXCLUSION, integrationRequirements: ROUTER_GUARD_INTEGRATION_REQUIREMENTS })
type Guard = ReturnType<typeof createConfiguredRouterGuard>
type Fixture = { guard: Guard; owner: Pool; runtime: Pool; nativeBinding: RouterGuardNativeBinding; applicationBinding: RouterGuardWriteBinding;
/** These setters affect the fixed LOCALHOST native fixture or actual owned
* PG backend. They cannot mint private terminal receipts. */
setNativeFault(fault: "success" | "drop-after-write" | "json-without-request" | "async-post" | "error-json"): void
nativeRequests(): number; applicationCommitQuery: string; close(): Promise<void>
restart(): Promise<Guard>; sampleGuardPid(): Promise<number>; observedGuardPids(): Promise<number[]>;
assertJournalMacs(): Promise<void>; applicationRows(): Promise<number>; commitPacketsDropped(): number }
const scope = () => ({ deadlineAt: Date.now() + 20000 }) // mapping retains its internal original 5s cap
function owned() { if (process.env.MMAPP_TEST_ROUTER_GUARD_OWNED !== "true") throw Error("Explicit owned router-guard fixture required") }
async function head(fixture: Fixture) { return (await fixture.owner.query("SELECT state,sequence::pg_catalog.text,current_attempt::pg_catalog.text FROM mmapp_router_guard.head WHERE id=1")).rows[0] }
/** Same pure constructor validator; no pool, filesystem or network is touched. */
export function assertRouterGuardDsnIsolationRefusals() {
const control = "postgresql://guard_runtime:[email protected]/router_control", app = "postgresql://app_runtime:[email protected]/application"
assert.equal(validateRouterGuardDatabaseIsolation(control, app).runtimeRole, "guard_runtime")
for (const [guardDsn, appDsn] of [
["postgresql://guard_runtime:[email protected]/%61pplication", app],
[control, "postgresql://app_runtime:[email protected]/%72outer_control"],
[control, "postgresql://%67uard_runtime:[email protected]/application"],
["postgresql://%61pp_runtime:[email protected]/router_control", app],
[control + "?user=app_runtime", app], [control, app + "?user=guard_runtime"],
[control, app + "?database=router_control"], [control, app + "?sslmode=require&sslmode=disable"],
]) assert.throws(() => validateRouterGuardDatabaseIsolation(guardDsn, appDsn), RouterGuardRefused)
return { cases: 8, realDatabaseCalls: 0 }
}
/** Every scenario gets a new OWNER-provisioned isolated fixture. In particular,
* no test cleans pending/unknown by DELETE, TRUNCATE, TTL or signature replay. */
export async function acceptOwnedRouterGuard(makeFixture: (name: string) => Promise<Fixture>) {
owned(); assertRouterGuardDsnIsolationRefusals(); const checks: string[] = ["constructor rejects encoded same DB/role and query authority overrides before any checkout"]
for (const scenario of ["shared-exclusion", "physical-commit", "nested-same-pid", "lost-native-ack", "forged-json", "async-post", "error-json", "unknown-persist", "head-forgery", "forged-terminal-idle", "no-send", "shared-cannot-write", "sql-semicolon-control", "sql-comment-control", "sql-caught-error", "intent-commit-loss", "application-commit-loss", "terminal-commit-loss"] as const) {
const fixture = await makeFixture(scenario)
try {
if (scenario === "shared-exclusion") {
const mapping = await fixture.guard.acquireMapping(scope())
try { await mapping.verify(); assert.equal((await fixture.owner.query(`SELECT pg_catalog.pg_try_advisory_lock(${ROUTER_GUARD_LOCK}) AS acquired`)).rows[0].acquired, false) }
finally { mapping.close() }
checks.push("actual held shared mapping ownership excludes the global writer on another backend")
} else if (scenario === "physical-commit") {
await fixture.guard.runApplication(fixture.applicationBinding, scope(), async client => { await client.query(fixture.applicationCommitQuery) })
assert.equal((await head(fixture)).state, "idle")
const mapping = await fixture.guard.acquireMapping(scope()); await mapping.verify(); mapping.close()
checks.push("actual application driver COMMIT is the private terminal source; journal and authenticated head become idle")
} else if (scenario === "nested-same-pid") {
await fixture.guard.runCompound({ ...fixture.applicationBinding, kind: "compound" }, scope(), async () => {
const originalPid = await fixture.sampleGuardPid()
await fixture.guard.runApplication(fixture.applicationBinding, scope(), async client => { await client.query(fixture.applicationCommitQuery); assert.equal(await fixture.sampleGuardPid(), originalPid); await fixture.guard.runNative(fixture.nativeBinding, scope()); assert.equal(await fixture.sampleGuardPid(), originalPid) })
})
assert.equal(new Set(await fixture.observedGuardPids()).size, 1)
assert.equal(fixture.nativeRequests(), 1); assert.equal((await head(fixture)).state, "idle")
const attempts = (await fixture.owner.query("SELECT parent_attempt IS NULL AS root FROM mmapp_router_guard.attempts")).rows
assert.equal(attempts.filter(row => row.root).length, 1); assert.equal(attempts.length, 3)
checks.push("nested compound/application/native work uses one physical exclusive guard lease and records child bindings")
} else if (["lost-native-ack", "forged-json", "async-post", "error-json"].includes(scenario)) {
fixture.setNativeFault(scenario === "lost-native-ack" ? "drop-after-write" : scenario === "forged-json" ? "json-without-request" : scenario === "error-json" ? "error-json" : "async-post")
await assert.rejects(fixture.guard.runNative(fixture.nativeBinding, scope()), RouterGuardUnknown)
assert.equal((await head(fixture)).state, "pending"); await assert.rejects(fixture.guard.acquireMapping(scope()))
if (scenario === "forged-json") assert.equal(fixture.nativeRequests(), 0)
checks.push(scenario + ": no synthetic terminal receipt, unresolved head blocks mapping")
} else if (scenario === "unknown-persist") {
fixture.setNativeFault("drop-after-write"); await assert.rejects(fixture.guard.runNative(fixture.nativeBinding, scope()))
await fixture.guard.close()
assert.equal((await head(fixture)).state, "pending")
assert.equal((await fixture.owner.query("SELECT count(*)::pg_catalog.int4 AS count FROM mmapp_router_guard.attempts")).rows[0].count, 1)
const restarted = await fixture.restart(); await assert.rejects(restarted.acquireMapping(scope()))
checks.push("guard restart/close never erases unresolved WAL-backed intent; separate configured source must refuse it")
} else if (scenario === "head-forgery") {
const client = await fixture.owner.connect()
try { await client.query(`SELECT pg_catalog.pg_advisory_lock(${ROUTER_GUARD_LOCK})`); await assert.rejects(client.query("UPDATE mmapp_router_guard.head SET sequence=sequence-1,state='idle',current_attempt=NULL WHERE id=1")) }
finally { try { await client.query(`SELECT pg_catalog.pg_advisory_unlock(${ROUTER_GUARD_LOCK})`) } finally { client.release(true) } }
checks.push("ALWAYS trigger refuses authenticated-head rewind instead of trusting a filtered empty pending query")
} else if (scenario === "forged-terminal-idle") {
// Create a REAL durable pending intent by losing a REAL native ACK.
fixture.setNativeFault("drop-after-write")
await assert.rejects(fixture.guard.runNative(fixture.nativeBinding, scope()), RouterGuardUnknown)
const client = await fixture.runtime.connect()
try {
await client.query(`SELECT pg_catalog.pg_advisory_lock(${ROUTER_GUARD_LOCK})`)
const before = (await client.query("SELECT sequence::pg_catalog.text,current_attempt::pg_catalog.text,last_event::pg_catalog.text FROM mmapp_router_guard.head WHERE id=1")).rows[0]
const originalEvent = (await client.query("SELECT sequence::pg_catalog.text,transition,attempt_id::pg_catalog.text FROM mmapp_router_guard.events WHERE event_id=$1", [before.last_event])).rows[0]
assert.equal(originalEvent.transition, "intent"); assert.equal(originalEvent.sequence, before.sequence); assert.equal(originalEvent.attempt_id, before.current_attempt)
const sequence = String(Number(before.sequence) + 1), fakeEventId = randomUUID(), invalidMac = "f".repeat(64)
await client.query("INSERT INTO mmapp_router_guard.events(event_id,attempt_id,sequence,transition,evidence_mac,event_mac) VALUES($1,$2,$3,'acknowledged',$4,$4)", [fakeEventId, before.current_attempt, sequence, invalidMac])
const changed = await client.query("UPDATE mmapp_router_guard.head SET sequence=$1,state='idle',current_attempt=NULL,last_event=$2,last_event_mac=$3,head_mac=$3 WHERE id=1 AND sequence=$4 RETURNING id", [sequence, fakeEventId, invalidMac, before.sequence])
assert.equal(changed.rows.length, 1)
const after = (await client.query("SELECT state,sequence::pg_catalog.text,last_event::pg_catalog.text,last_event_mac FROM mmapp_router_guard.head WHERE id=1")).rows[0]
assert.equal(after.state, "idle"); assert.equal(after.sequence, sequence); assert.equal(after.last_event, fakeEventId); assert.equal(after.last_event_mac, invalidMac)
} finally { try { await client.query(`SELECT pg_catalog.pg_advisory_unlock(${ROUTER_GUARD_LOCK})`) } finally { client.release(true) } }
// A filtered pending query is now empty. Source MUST nevertheless
// authenticate and refuse the forged idle head and final event.
await assert.rejects(fixture.guard.acquireMapping(scope()))
checks.push("genuine pending -> DB-role valid-shape forged ACK/idle with preserved sequence/event binding refuses mapping because MAC is invalid")
} else if (scenario === "no-send") {
const before = fixture.nativeRequests()
await fixture.guard.runCompound({ ...fixture.applicationBinding, kind: "compound" }, scope(), async () => ({ claimedAck: true }))
assert.equal(fixture.nativeRequests(), before); assert.equal((await head(fixture)).state, "idle")
assert.equal((await fixture.owner.query("SELECT transition FROM mmapp_router_guard.events ORDER BY sequence DESC LIMIT 1")).rows[0].transition, "no-send")
checks.push("no-send derives from zero private transport/driver activity; returned JSON never becomes an acknowledged receipt")
} else if (scenario.startsWith("sql-")) {
const text = scenario === "sql-semicolon-control" ? fixture.applicationCommitQuery + "; COMMIT; BEGIN" : scenario === "sql-comment-control" ? "/* hidden control */\nCOMMIT" : "SELECT 1/0"
await assert.rejects(fixture.guard.runApplication(fixture.applicationBinding, scope(), async client => { await client.query(text).catch(() => {}) }), RouterGuardUnknown)
assert.equal((await head(fixture)).state, "pending"); await assert.rejects(fixture.guard.acquireMapping(scope()))
checks.push(scenario + ": actual driver command results/ReadyForQuery refuse transaction escape, even when callback catches error")
} else if (scenario.endsWith("commit-loss")) {
if (scenario === "application-commit-loss") await assert.rejects(fixture.guard.runApplication(fixture.applicationBinding, scope(), async client => { await client.query(fixture.applicationCommitQuery) }), RouterGuardUnknown)
else await assert.rejects(fixture.guard.runNative(fixture.nativeBinding, scope()), RouterGuardUnknown)
assert.equal(fixture.commitPacketsDropped(), 1)
if (scenario === "terminal-commit-loss") {
// Actual terminal WAL may have committed although its ACK was lost.
// Private completed native receipt already exists: authentic idle is
// safe, but this caller MUST still get unknown and never replay.
assert.equal((await head(fixture)).state, "idle"); assert.equal(fixture.nativeRequests(), 1)
const mapping = await fixture.guard.acquireMapping(scope()); await mapping.verify(); mapping.close()
} else {
assert.equal((await head(fixture)).state, "pending"); await assert.rejects(fixture.guard.acquireMapping(scope()))
if (scenario === "intent-commit-loss") assert.equal(fixture.nativeRequests(), 0)
else assert.equal(await fixture.applicationRows(), 1)
}
checks.push(scenario + ": real server COMMIT followed by wire ACK loss; no driver-result replacement or automatic replay")
} else {
const mapping = await fixture.guard.acquireMapping(scope())
try { await assert.rejects(mapping.run(() => fixture.guard.runNative(fixture.nativeBinding, scope())), RouterGuardRefused) }
finally { mapping.close() }
checks.push("own mapping-shared context cannot upgrade itself into an exclusive writer or borrow a new pool client")
}
if (scenario !== "forged-terminal-idle") await fixture.assertJournalMacs()
} finally { await fixture.close() }
}
return { checks, actualPgRun: true, activation: false, realChrCalls: 0 }
}
/** Root captures these on existing v1/v2 runtime roles BEFORE and AFTER owner
* installation of the independent guard namespace in the SAME control DB.
* Exact digest equality is the compatibility proof; this function itself is
* not a claim that the future owned acceptance has already been executed. */
export async function captureExistingBandwidthCompatibility(input: { core: Pool; nodes: Pool; databaseName: string; coreRuntime: string; coreOwner: string; nodeRuntime: string; nodeOwner: string; v2: boolean }) {
owned(); const values = [input.databaseName, input.coreRuntime, input.coreOwner]
const snapshots = [
(await input.core.query(BANDWIDTH_CONTROL_ROLE_SQL, values)).rows,
(await input.core.query(BANDWIDTH_CONTROL_CATALOG_SQL)).rows,
(await input.nodes.query(BANDWIDTH_NODE_REGISTRY_ROLE_SQL, [input.databaseName, input.nodeRuntime, input.nodeOwner])).rows,
(await input.nodes.query(input.v2 ? BANDWIDTH_PEER_MANAGED_REGISTRY_CATALOG_SQL : BANDWIDTH_NODE_REGISTRY_CATALOG_SQL)).rows,
input.v2 ? (await input.nodes.query(BANDWIDTH_PEER_REGISTRY_INCOMING_SQL)).rows : [],
]
return createHash("sha256").update(canonical(snapshots)).digest("hex")
}