Files
MikrotikManager/backend/src/modules/mcp/database-restore-data-equivalence.sql-helper.ts
T

223 lines
15 KiB
TypeScript

import { createHash, randomUUID } from "node:crypto"
import { spawn } from "node:child_process"
import { readFile, realpath, unlink, writeFile } from "node:fs/promises"
import path from "node:path"
import { isDeepStrictEqual } from "node:util"
import { setTimeout as delay } from "node:timers/promises"
import pg from "pg"
import { captureMigrationData, compareMigrationData, type CapturedMigrationData } from "../../db/migration-data-inventory.js"
// Private destructive acceptance helper. No application entry point imports it.
class OwnedRestoreDataError extends Error {}
function refuse(category: string): never { throw new OwnedRestoreDataError(`Owned restore data equivalence refused: ${category}`) }
const identifier = (value: string) => '"' + value.replaceAll('"', '""') + '"'
const literal = (value: string) => "'" + value.replaceAll("'", "''") + "'"
const profileSql = `SELECT pg_catalog.pg_encoding_to_char(d.encoding) AS encoding,
d.datcollate AS collate,d.datctype AS ctype,d.datlocprovider::text AS provider,
pg_catalog.to_jsonb(d)->>'datlocale' AS locale,pg_catalog.to_jsonb(d)->>'daticurules' AS rules,
d.datcollversion AS version,t.spcname AS tablespace,pg_catalog.pg_get_userbyid(d.datdba) AS owner,
d.datacl::text AS acl,pg_catalog.shobj_description(d.oid,'pg_database') AS comment
FROM pg_catalog.pg_database d JOIN pg_catalog.pg_tablespace t ON t.oid=d.dattablespace
WHERE d.datname=pg_catalog.current_database()`
async function snapshot(pool: pg.Pool): Promise<CapturedMigrationData> {
const client = await pool.connect()
try {
await client.query("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY")
await client.query(`SET LOCAL search_path=pg_catalog; SET LOCAL TimeZone='UTC'; SET LOCAL DateStyle='ISO, YMD';
SET LOCAL standard_conforming_strings=on; SET LOCAL statement_timeout='5s'; SET LOCAL row_security=off;
SET LOCAL extra_float_digits=3; SET LOCAL bytea_output='hex'; SET LOCAL IntervalStyle='postgres';
SET LOCAL client_encoding='UTF8'; SET LOCAL lc_monetary='C'; SET LOCAL lc_numeric='C'`)
return await captureMigrationData(client)
} finally {
try { await client.query("ROLLBACK") } finally { client.release() }
}
}
/** pg_restore receives no URI/password argv; discard every diagnostic byte. */
async function restoreClone(file: string, url: URL, database: string) {
const childEnvironment = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^PG/i.test(key)))
Object.assign(childEnvironment, { PGHOST: "127.0.0.1", PGPORT: url.port || "5432", PGUSER: decodeURIComponent(url.username),
PGDATABASE: database, PGPASSWORD: decodeURIComponent(url.password), PGCONNECT_TIMEOUT: "5" })
await new Promise<void>((resolve, reject) => {
const child = spawn("pg_restore", ["--single-transaction", "--exit-on-error", "--no-password", "--dbname", database, file],
{ env: childEnvironment, shell: false, windowsHide: true, stdio: ["ignore", "ignore", "pipe"] })
let failed = false, bytes = 0
const timer = setTimeout(() => { failed = true; child.kill("SIGKILL") }, 120000)
child.stderr.on("data", (chunk: Buffer) => { bytes += chunk.length; if (bytes > 1048576) { failed = true; child.kill("SIGKILL") } })
child.on("error", () => { failed = true })
child.on("close", code => { clearTimeout(timer); if (failed || code !== 0) reject(new OwnedRestoreDataError("Owned restore data equivalence refused: archive restore")); else resolve() })
})
}
function difference(expected: CapturedMigrationData, actual: CapturedMigrationData): string {
if (expected.schemaSha256 !== actual.schemaSha256) return "schema"
for (const name of ["tables", "sequences"] as const) {
const left = expected[name], right = actual[name]
for (let index = 0; index < Math.max(left.length, right.length); index++) {
if (!isDeepStrictEqual(left[index], right[index])) {
const relation = left[index] ?? right[index]
// Catalog names only; never interpolate driver messages or row values.
return `${name}: ${JSON.stringify([relation.namespace, relation.name])}`
}
}
}
return "evidence"
}
export interface OwnedRestoreDataComparisonInput {
operationId: string
receipt: Record<string, unknown>
actorId: string
startedAt: number
}
async function prepareExpectation(archive: Buffer) {
// These checks deliberately precede config/security/configured-pool imports.
if (process.env.MMAPP_OWN_TERMINAL_DATA_EQUIVALENCE !== "true" || process.env.MMAPP_OWN_TERMINAL_RESTORE !== "true") refuse("owned opt-in")
let url: URL
try { url = new URL(process.env.DATABASE_URL ?? "") } catch { refuse("owned connection") }
const state = path.resolve(process.env.MCP_STATE_DIR ?? "")
if (!["postgres:", "postgresql:"].includes(url.protocol) || url.hostname !== "127.0.0.1" || decodeURIComponent(url.username) !== "mcp_test" || url.pathname !== "/postgres" ||
!process.env.MMAPP_OWN_SQL_DB || decodeURIComponent(url.pathname.slice(1)) !== process.env.MMAPP_OWN_SQL_DB || url.search || url.hash ||
!process.env.MCP_STATE_DIR || path.basename(state) !== "state" || !/^mm-mcp-test-[A-Za-z0-9-]+$/.test(path.basename(path.dirname(state)))) refuse("owned connection/state")
if (path.resolve(await realpath(state)).toLowerCase() !== state.toLowerCase()) refuse("owned state path")
if (!Buffer.isBuffer(archive) || archive.length < 5 || archive.length > 64 * 1024 * 1024 || archive.subarray(0, 5).toString() !== "PGDMP") refuse("archive")
const { pool: target } = await import("../../db/index.js")
const { env } = await import("../../config.js")
if (env.DATABASE_URL !== url.toString() && env.DATABASE_URL !== process.env.DATABASE_URL) refuse("configured connection")
const { redact } = await import("./security.js")
const identity = (await target.query("SELECT current_database() AS db,session_user AS owner,current_user AS active_owner")).rows[0]
if (identity.db !== process.env.MMAPP_OWN_SQL_DB || identity.owner !== "mcp_test" || identity.active_owner !== "mcp_test") refuse("target identity")
const profile = (await target.query(profileSql)).rows[0]
if (!profile || profile.owner !== "mcp_test" || profile.comment !== null || profile.acl !== null || profile.tablespace !== "pg_default") refuse("source database profile")
const archiveSha256 = createHash("sha256").update(archive).digest("hex")
const suffix = randomUUID().replaceAll("-", ""), database = `mm_restore_data_${suffix}`
const file = path.join(state, `restore-data-${suffix}.dump`)
const cloneUrl = new URL(url); cloneUrl.pathname = "/" + database
const clone = new pg.Pool({ connectionString: cloneUrl.toString(), max: 1, connectionTimeoutMillis: 5000, statement_timeout: 5000 })
let created = false, fileOwned = false, closed = false, comparing = false
let verifiedReceipt: { context: unknown; audit: unknown } | undefined
let beforeConsumers: Readonly<{
equal: true; equalityPhase: "before-consumers"; evidenceOnly: true; ready: false; enrollmentAuthorized: false;
allReplicaQuiescence: false; externalQuiescence: false; archiveSnapshotValidated: true;
captureStartedAt: number; capturedAt: number; tableCount: number; sequenceCount: number; rowCount: number; sha256: string
}> | undefined
const close = async () => {
if (closed) return
closed = true
let cleanupFailed = false
try { await clone.end() } catch { cleanupFailed = true }
if (created) {
try {
if (!/^mm_restore_data_[a-f0-9]{32}$/.test(database) || database !== `mm_restore_data_${suffix}`) refuse("cleanup database identity")
const row = (await target.query("SELECT datname,pg_catalog.pg_get_userbyid(datdba) AS owner FROM pg_catalog.pg_database WHERE datname=$1", [database])).rows[0]
if (!row || row.datname !== database || row.owner !== "mcp_test") refuse("cleanup database owner")
await target.query(`DROP DATABASE ${identifier(database)}`)
} catch { cleanupFailed = true }
}
if (fileOwned) { try { await unlink(file) } catch { cleanupFailed = true } }
if (cleanupFailed) refuse("owned cleanup")
}
try {
const provider = ({ c: "libc", i: "icu", b: "builtin" } as Record<string, string>)[String(profile.provider)]
if (!provider || typeof profile.encoding !== "string" || typeof profile.collate !== "string" || typeof profile.ctype !== "string") refuse("source locale profile")
let locale = ""
if (provider === "icu" || provider === "builtin") {
if (typeof profile.locale !== "string") refuse("source locale")
locale = ` ${provider === "icu" ? "ICU_LOCALE" : "BUILTIN_LOCALE"} ${literal(profile.locale)}`
}
if (profile.rules !== null) { if (provider !== "icu" || typeof profile.rules !== "string") refuse("source locale rules"); locale += ` ICU_RULES ${literal(profile.rules)}` }
if (profile.version !== null) { if (typeof profile.version !== "string") refuse("source collation version"); locale += ` COLLATION_VERSION ${literal(profile.version)}` }
await target.query(`CREATE DATABASE ${identifier(database)} WITH TEMPLATE template0 OWNER mcp_test ENCODING ${literal(profile.encoding)} LC_COLLATE ${literal(profile.collate)} LC_CTYPE ${literal(profile.ctype)} LOCALE_PROVIDER ${provider}${locale}`)
created = true
await writeFile(file, archive, { flag: "wx", mode: 0o600 }); fileOwned = true
await restoreClone(file, url, database)
if (!isDeepStrictEqual((await clone.query(profileSql)).rows[0], profile)) refuse("clone database profile")
const rawArchive = await snapshot(clone)
compareMigrationData(rawArchive, rawArchive)
return {
async compareBeforeConsumers() {
if (closed || comparing || beforeConsumers) refuse("pre-consumer comparison lifecycle")
comparing = true
try {
const captureStartedAt = Date.now()
// This is the complete raw archive expectation. The caller pauses the
// owned restore after migrations and before any consumer restarts.
// No table/column exception or expected runtime append is applied.
const actual = await snapshot(target)
try { compareMigrationData(rawArchive, actual) } catch { refuse(difference(rawArchive, actual)) }
beforeConsumers = Object.freeze({ equal: true as const, equalityPhase: "before-consumers" as const,
evidenceOnly: true as const, ready: false as const, enrollmentAuthorized: false as const,
allReplicaQuiescence: false as const, externalQuiescence: false as const, archiveSnapshotValidated: true as const,
captureStartedAt, capturedAt: Date.now(), tableCount: actual.tables.length, sequenceCount: actual.sequences.length,
rowCount: actual.rowCount, sha256: actual.sha256 })
return beforeConsumers
} catch (error) {
if (error instanceof OwnedRestoreDataError) throw error
refuse("pre-consumer capture/comparison")
} finally { comparing = false }
},
async compareAfterRestore(input: OwnedRestoreDataComparisonInput) {
if (closed || comparing) refuse("comparison lifecycle")
comparing = true
try {
const { operationId, receipt, actorId, startedAt } = input
if (!/^[a-f0-9-]{36}$/i.test(operationId) || !actorId || !Number.isSafeInteger(startedAt) || startedAt > Date.now() ||
receipt.operationId !== operationId || receipt.state !== "applied" || receipt.accessRevoked !== true || receipt.automaticRetry !== false) refuse("expected receipt")
const finishedAt = typeof receipt.finishedAt === "string" ? Date.parse(receipt.finishedAt) : NaN
if (!beforeConsumers || !Number.isFinite(finishedAt) || finishedAt > Date.now() ||
beforeConsumers.captureStartedAt < startedAt || beforeConsumers.capturedAt > finishedAt ||
beforeConsumers.captureStartedAt > beforeConsumers.capturedAt) refuse("pre-consumer evidence window")
if (typeof receipt.archiveRef !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(receipt.archiveRef)) refuse("receipt archive reference")
const vaultFile = path.join(state, "restore-vault", receipt.archiveRef)
const metadata = JSON.parse(await readFile(vaultFile + ".archive.json", "utf8")) as Record<string, unknown>
const used = JSON.parse(await readFile(vaultFile + ".used", "utf8")) as Record<string, unknown>
if (!metadata || metadata.id !== receipt.archiveRef || metadata.sha256 !== archiveSha256 || metadata.sizeBytes !== archive.length ||
metadata.ownerId !== actorId || !used || used.operationId !== operationId) refuse("archive binding")
const expectedPayload = JSON.parse(JSON.stringify(redact(receipt))) as unknown
const context = { operationId, actorId, startedAt, receipt: expectedPayload }
if (verifiedReceipt && !isDeepStrictEqual(verifiedReceipt.context, context)) refuse("comparison context changed")
const deadline = Date.now() + 10000
let audit: Record<string, unknown> | undefined
for (;;) {
const rows = (await target.query(`SELECT id::text AS id,actor_id,connection_id,payload,created_at::text AS created_at,
(created_at >= to_timestamp($2::double precision/1000) AND created_at <= clock_timestamp()) AS in_window
FROM public.mcp_audit WHERE action='database.restore.receipt' AND payload->>'operationId'=$1 LIMIT 2`, [operationId, startedAt])).rows
if (rows.length > 1) refuse("audit multiplicity")
if (rows.length === 1) { audit = rows[0]; break }
if (Date.now() >= deadline) refuse("audit timeout")
await delay(50)
}
if (!audit || audit.actor_id !== actorId || audit.connection_id !== null || audit.in_window !== true || typeof audit.created_at !== "string" ||
typeof audit.id !== "string" || !/^[1-9]\d*$/.test(audit.id) || !isDeepStrictEqual(audit.payload, expectedPayload)) refuse("audit validation")
const auditIdentity = { id: audit.id, createdAt: audit.created_at }
if (verifiedReceipt && !isDeepStrictEqual(verifiedReceipt.audit, auditIdentity)) refuse("audit receipt changed")
verifiedReceipt = { context, audit: auditIdentity }
// Consumers have resumed by this point. Report the frozen full-data
// observation at its actual phase, then independent receipt evidence;
// do not recapture or manufacture a post-consumer expected database.
return Object.freeze({ ...beforeConsumers, dataEqualBeforeConsumers: true as const,
postAuditReceiptExact: true as const, archiveShaBound: true as const, auditRecordsObserved: 1 as const })
} catch (error) {
if (error instanceof OwnedRestoreDataError) throw error
refuse("capture/comparison")
} finally { comparing = false }
},
close,
}
} catch (error) {
try { await close() } catch { /* Preserve the primary sanitized failure. */ }
if (error instanceof OwnedRestoreDataError) throw error
refuse("preparation")
}
}
export async function prepareOwnedRestoreDataExpectation(archive: Buffer) {
try { return await prepareExpectation(archive) }
catch (error) {
if (error instanceof OwnedRestoreDataError) throw error
refuse("preparation")
}
}