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

91 lines
6.7 KiB
TypeScript

/** Opt-in owned acceptance on the genuine existing signed v1/v2 control
* fixture. No substitute core schema, source signature or renewed TTL. */
import assert from "node:assert/strict"
import { createHash, randomBytes } from "node:crypto"
import type { Pool } from "pg"
import { assertOwnedBandwidthSql } from "./bandwidth-admission-process.sql-helper.js"
import type { createConfiguredBandwidthControlSource } from "./bandwidth-control-source.js"
import type { createConfiguredBandwidthNodeSource } from "./bandwidth-node-source.js"
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 { BANDWIDTH_EXTERNAL_NODE_REGISTRY_ROLE_SQL } from "./bandwidth-external-node-registry-role.js"
import { BANDWIDTH_EXTERNAL_NODE_REGISTRY_CATALOG_SQL } from "./bandwidth-external-node-registry-catalog.js"
import { ROUTER_GUARD_DDL } from "./router-configuration-guard-schema.js"
const quote = (value: string) => { assert(/^[a-z_]+[a-f0-9]{16,32}$/.test(value)); return '"' + value + '"' }
const scope = () => ({ deadlineAt: Date.now() + 10000 })
export async function acceptOwnedRouterGuardControlCompatibility(input: {
admin: Pool; databaseName: string; runtimeRole: string; ownerRole: string; v2: boolean
core: ReturnType<typeof createConfiguredBandwidthControlSource>; node: ReturnType<typeof createConfiguredBandwidthNodeSource>
}) {
assertOwnedBandwidthSql(); assert.equal(process.env.MMAPP_TEST_ROUTER_GUARD_COMPATIBILITY, "true")
assert(/^(bns|bex)_control_[a-f0-9]{32}$/.test(input.databaseName))
const target = (await input.admin.query("SELECT current_database() AS name,r.rolsuper AS super FROM pg_catalog.pg_roles r WHERE r.rolname=current_user")).rows[0]
assert.equal(target.name, input.databaseName); assert.equal(target.super, true)
assert.equal((await input.admin.query("SELECT pg_catalog.to_regnamespace('mmapp_router_guard') IS NULL AS absent")).rows[0].absent, true)
const suffix = randomBytes(8).toString("hex"), owner = "rg_compat_owner_" + suffix, runtime = "rg_compat_runtime_" + suffix
let ownerCreated = false, runtimeCreated = false, installed = false, cleaned = false
const cleanup = async () => {
if (cleaned) return; cleaned = true
// This scope owns exactly this fresh namespace and these generated roles;
// it never drops/reseals the genuine pre-existing core/source namespace.
if (installed) {
const actual = (await input.admin.query("SELECT r.rolname AS owner FROM pg_catalog.pg_namespace n JOIN pg_catalog.pg_roles r ON r.oid=n.nspowner WHERE n.nspname='mmapp_router_guard'")).rows
assert.equal(actual.length, 1); assert.equal(actual[0].owner, owner)
await input.admin.query("DROP SCHEMA mmapp_router_guard CASCADE")
}
if (runtimeCreated) await input.admin.query(`DROP ROLE ${quote(runtime)}`)
if (ownerCreated) { await input.admin.query(`REVOKE CREATE ON DATABASE ${quote(input.databaseName)} FROM ${quote(owner)}`); await input.admin.query(`DROP ROLE ${quote(owner)}`) }
}
const observe = async () => {
const window = scope(), connection = await input.core.connect(window)
let snapshot: unknown[]
try {
const values = [input.databaseName, input.runtimeRole, input.ownerRole]
snapshot = [
(await connection.query(BANDWIDTH_CONTROL_ROLE_SQL, values)).rows,
(await connection.query(BANDWIDTH_CONTROL_CATALOG_SQL)).rows,
(await connection.query(BANDWIDTH_NODE_REGISTRY_ROLE_SQL, values)).rows,
(await connection.query(input.v2 ? BANDWIDTH_PEER_MANAGED_REGISTRY_CATALOG_SQL : BANDWIDTH_NODE_REGISTRY_CATALOG_SQL)).rows,
]
if (input.v2) snapshot.push((await connection.query(BANDWIDTH_EXTERNAL_NODE_REGISTRY_ROLE_SQL, values)).rows,
(await connection.query(BANDWIDTH_EXTERNAL_NODE_REGISTRY_CATALOG_SQL)).rows, (await connection.query(BANDWIDTH_PEER_REGISTRY_INCOMING_SQL)).rows)
assert.equal((await connection.query("SELECT 1 AS genuine_control_query")).rows[0].genuine_control_query, 1)
} finally { connection.release(true) }
const identity = await input.core.identity(scope()), session = await input.node.open(scope())
try {
const binding = await session.binding()
assert.equal((await session.connection.query("SELECT 1 AS genuine_node_query")).rows[0].genuine_node_query, 1)
return { digest: createHash("sha256").update(canonical(snapshot)).digest("hex"), identity, binding }
} finally { session.close() }
}
try {
const before = await observe()
await input.admin.query(`CREATE ROLE ${quote(owner)} NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS`); ownerCreated = true
await input.admin.query(`CREATE ROLE ${quote(runtime)} NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS`); runtimeCreated = true
await input.admin.query(`GRANT CREATE ON DATABASE ${quote(input.databaseName)} TO ${quote(owner)}`)
const physical = await input.admin.connect()
try { await physical.query(`SET ROLE ${quote(owner)}`); await physical.query(ROUTER_GUARD_DDL); installed = true }
finally { await physical.query("RESET ROLE"); physical.release(true) }
await input.admin.query(`REVOKE CREATE ON DATABASE ${quote(input.databaseName)} FROM ${quote(owner)}`)
await input.admin.query(`GRANT USAGE ON SCHEMA mmapp_router_guard TO ${quote(runtime)};
GRANT SELECT ON ALL TABLES IN SCHEMA mmapp_router_guard TO ${quote(runtime)};
GRANT INSERT ON mmapp_router_guard.attempts,mmapp_router_guard.events TO ${quote(runtime)};
GRANT UPDATE ON mmapp_router_guard.head TO ${quote(runtime)};
GRANT EXECUTE ON FUNCTION mmapp_router_guard.protect_rows() TO ${quote(runtime)}`)
const role = await input.admin.connect()
try {
await role.query(`SET ROLE ${quote(runtime)}`)
assert.equal((await role.query("SELECT count(*)::integer AS count FROM mmapp_router_guard.head")).rows[0].count, 0)
await assert.rejects(role.query("SELECT * FROM mmapp_control.bandwidth_source_identity"), error => (error as { code?: string }).code === "42501")
} finally { await role.query("RESET ROLE"); role.release(true) }
const after = await observe()
assert.deepEqual(after, before)
return { cleanup, report: { version: input.v2 ? 2 : 1, exactRoleCatalogPinsUnchanged: true, genuineConfiguredCoreAndNodeQueriesPassed: true, guardActivated: false, schemaMigrationsChanged: false } }
} catch (error) { await cleanup(); throw error }
}