Files
MikrotikManager/backend/src/services/bandwidth-public-registry.sql-helper.ts
T

147 lines
9.6 KiB
TypeScript

import { MIGRATION_MANIFEST } from "../db/migration-manifest.js"
/** Owned PostgreSQL acceptance for PUBLIC metadata leases only.
* No Docker Q, secret-key verification, native observation or enrollment authority. */
import assert from "node:assert/strict"
import { readFile, rename, writeFile } from "node:fs/promises"
import { resolve } from "node:path"
import { performance } from "node:perf_hooks"
import { setImmediate as immediate } from "node:timers/promises"
import { assertOwnedBandwidthSql } from "./bandwidth-admission-process.sql-helper.js"
import type { createOwnedExternalRegistryHarness } from "./bandwidth-external-node-registry.sql-helper.js"
type Harness = Awaited<ReturnType<typeof createOwnedExternalRegistryHarness>>
type Signed = Awaited<ReturnType<Harness["createSignedSource"]>>
export async function acceptOwnedPublicRegistryMetadata(f: Harness, signed: Signed): Promise<readonly string[]> {
assertOwnedBandwidthSql()
assert.equal(process.env.MMAPP_OWN_PUBLIC_REGISTRY_METADATA, "true")
assert.equal(process.env.MMAPP_OWN_BANDWIDTH_EXTERNAL_REGISTRY, "true")
const state = resolve(process.env.MCP_STATE_DIR!)
const path = (name: string) => resolve(state, "external-source-" + name)
const secrets = [path("event.key"), path("issuer.key")]
const moved: string[] = [], checks: string[] = []
const rootTables = ["bandwidth_source_identity", "bandwidth_node_authority", "bandwidth_nodes", "bandwidth_node_aliases", "bandwidth_node_events", "bandwidth_external_node_aliases", "bandwidth_external_node_events"]
const before = await f.digest(rootTables), gets = f.nativeGets(), posts = f.nativePosts()
const { pool: application } = await import("../db/index.js")
const migrationCount = async () => Number((await application.query("SELECT count(*) AS n FROM public.schema_migrations")).rows[0].n)
assert.equal(await migrationCount(), MIGRATION_MANIFEST.length)
const privileges = async () => (await f.owner!.query(`SELECT pg_catalog.md5(pg_catalog.jsonb_build_object(
'schema',(SELECT pg_catalog.jsonb_agg(pg_catalog.jsonb_build_array(nspname,nspacl::text) ORDER BY nspname) FROM pg_catalog.pg_namespace WHERE nspname='mmapp_control'),
'relations',(SELECT pg_catalog.jsonb_agg(pg_catalog.jsonb_build_array(c.relname,c.relacl::text) ORDER BY c.relname) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='mmapp_control' AND c.relkind IN ('r','S')),
'functions',(SELECT pg_catalog.jsonb_agg(pg_catalog.jsonb_build_array(p.proname,p.proacl::text) ORDER BY p.proname,p.oid) FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='mmapp_control')
)::text) AS digest`)).rows[0].digest
const beforePrivileges = await privileges()
const scope = (signal?: AbortSignal) => ({ deadlineAt: Date.now() + 5000, ...(signal ? { signal } : {}) })
const gone = async (pid: number) => {
const end = performance.now() + 2000
for (;;) {
await f.owner!.query("SELECT pg_catalog.pg_stat_clear_snapshot()")
const result = await f.owner!.query("SELECT count(*)::int AS n FROM pg_catalog.pg_stat_activity WHERE pid=$1", [pid])
if (result.rows[0].n === 0) return
assert(performance.now() < end, "retired public lease physical PID must disappear within bounded cleanup")
await immediate()
}
}
const held = async (pid: number) => {
const result = await f.owner!.query("SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_locks WHERE pid=$1 AND locktype='advisory' AND classid=0::pg_catalog.oid AND objid=8723116::pg_catalog.oid AND objsubid=1 AND mode='ExclusiveLock' AND granted) AS held", [pid])
assert.equal(result.rows[0].held, true)
}
const assertPublic = (value: Awaited<ReturnType<Awaited<ReturnType<Signed["node"]["openPublicRegistryMetadata"]>>["inspect"]>>) => {
assert.equal(value.format, "mmapp-bandwidth-public-registry-metadata-v1")
assert(Number.isSafeInteger(value.backendPid) && value.backendPid > 0)
assert(Object.isFrozen(value)); assert(Object.isFrozen(value.metadata))
assert.equal(value.metadata.source.controlGeneration, signed.controlGeneration)
assert.equal(value.metadata.bootstrap.installationId, f.root.installationId)
assert(!Object.keys(value).some(key => /quiescence|credential|dispatch|keyCurrent/i.test(key)))
}
try {
// These paths belong exclusively to this harness; move, do not destroy, and
// restore even after a failed assertion. ENOENT proves a real read would fail.
for (const secret of secrets) { await rename(secret, secret + ".public-only-held"); moved.push(secret) }
console.log("Owned public registry stage:", "same-lease-without-secrets")
const lease = await signed.node.openPublicRegistryMetadata(scope())
let pid = 0
try {
assert.deepEqual(Object.keys(lease).sort(), ["close", "inspect"])
const first = await lease.inspect(); assertPublic(first); pid = first.backendPid
const second = await lease.inspect(); assertPublic(second)
assert.equal(second.backendPid, pid); assert.deepEqual(second.metadata, first.metadata)
await held(pid)
// Actual rival exclusive acquisition refuses; no replacement lock result.
const rival = await f.owner!.connect()
try {
const result = await rival.query("SELECT pg_catalog.pg_try_advisory_lock(8723116) AS acquired")
assert.equal(result.rows[0].acquired, false)
} finally { rival.release(true) }
await assert.rejects(signed.node.openPublicRegistryMetadata(scope()))
await held(pid)
assert.equal((await lease.inspect()).backendPid, pid)
} finally { lease.close(); lease.close() }
await gone(pid); await assert.rejects(lease.inspect())
checks.push("actual public node lease: missing both secret files, repeated same PID, real exclusive lock/rival refusal, bounded physical close; no native or SQL mutation")
console.log("Owned public registry stage:", "original-cancellation")
const controller = new AbortController(), canceled = await signed.node.openPublicRegistryMetadata(scope(controller.signal))
const canceledPid = (await canceled.inspect()).backendPid
controller.abort(); await assert.rejects(canceled.inspect()); canceled.close(); await gone(canceledPid)
checks.push("original cancellation permanently retires the real physical public metadata lease")
console.log("Owned public registry stage:", "overlapping-inspect")
const concurrent = await signed.node.openPublicRegistryMetadata(scope())
const concurrentPid = (await concurrent.inspect()).backendPid
const concurrentResults = await Promise.allSettled([concurrent.inspect(), concurrent.inspect()])
assert(concurrentResults.every(result => result.status === "rejected"))
concurrent.close(); await gone(concurrentPid); await assert.rejects(concurrent.inspect())
checks.push("overlapping inspect operations fail closed and retire instead of sharing mutable frame state")
console.log("Owned public registry stage:", "current-source-role-revocation")
const changed = await signed.node.openPublicRegistryMetadata(scope())
const changedPid = (await changed.inspect()).backendPid
// Source identity generation is genuinely immutable. Revoke the existing
// SELECT privilege instead; never disable its ALWAYS trigger for a fixture.
assert(/^bex_source_[a-f0-9]{32}$/.test(signed.runtimeRole))
const sourceRole = '"' + signed.runtimeRole + '"'
try {
await f.owner!.query("REVOKE SELECT ON mmapp_control.bandwidth_source_identity FROM " + sourceRole)
await assert.rejects(changed.inspect())
} finally {
await f.owner!.query("GRANT SELECT ON mmapp_control.bandwidth_source_identity TO " + sourceRole)
changed.close()
}
await gone(changedPid)
checks.push("actual current source-role privilege revocation refuses on the held same lease; exact original SELECT privilege restored without identity-trigger bypass")
console.log("Owned public registry stage:", "current-catalog-drift")
const catalog = await signed.node.openPublicRegistryMetadata(scope())
const catalogPid = (await catalog.inspect()).backendPid
try {
await f.owner!.query("CREATE INDEX owned_public_metadata_drift ON mmapp_control.bandwidth_node_aliases(server_id)")
await assert.rejects(catalog.inspect())
} finally {
await f.owner!.query("DROP INDEX IF EXISTS mmapp_control.owned_public_metadata_drift")
catalog.close()
}
await gone(catalogPid)
checks.push("actual catalog drift is rejected by unchanged registry identity validators, not replaced SQL rows")
console.log("Owned public registry stage:", "current-public-bootstrap-drift")
const file = path("bootstrap.json"), original = await readFile(file)
const rotated = await signed.node.openPublicRegistryMetadata(scope())
const rotatedPid = (await rotated.inspect()).backendPid
try { await writeFile(file, "{}"); await assert.rejects(rotated.inspect()) }
finally { await writeFile(file, original); rotated.close() }
await gone(rotatedPid)
checks.push("current public bootstrap corruption retires the physical lease; original signed bytes restored")
console.log("Owned public registry stage:", "unchanged-final-state")
assert.equal(await f.digest(rootTables), before)
assert.equal(await privileges(), beforePrivileges)
assert.equal(await migrationCount(), MIGRATION_MANIFEST.length)
assert.equal(f.nativeGets(), gets); assert.equal(f.nativePosts(), posts)
checks.push("all registry rows and schema/table/function privileges unchanged after restored owned fault DDL; original 39 migrations unchanged; zero native GET/POST")
return Object.freeze(checks)
} finally {
for (const secret of moved.reverse()) await rename(secret + ".public-only-held", secret)
}
}