34 lines
2.0 KiB
TypeScript
34 lines
2.0 KiB
TypeScript
import pg from "pg"
|
|
import { X509Certificate } from "node:crypto"
|
|
import { checkServerIdentity } from "node:tls"
|
|
import { readRuntimeDatabaseArchivePeer } from "../db/index.js"
|
|
import { captureRuntimeRestoreData, DatabaseRestoreDataRefused } from "../db/database-restore-data.js"
|
|
import type { DatabaseOperationLockClient } from "../db/operation-lock.js"
|
|
import { readDatabaseArchivePassword } from "./database-dump-connection.js"
|
|
import { withDatabaseRestoreTarget } from "./database-restore-target.js"
|
|
|
|
export async function inspectProtectedDatabaseData(runtime: DatabaseOperationLockClient, discard: () => void, passwordFile: string) {
|
|
const peer = readRuntimeDatabaseArchivePeer(runtime), leaf = new X509Certificate(peer.leaf)
|
|
const password = await readDatabaseArchivePassword(passwordFile)
|
|
return withDatabaseRestoreTarget(runtime, discard, async targetCheckSql => {
|
|
const client = new pg.Client({
|
|
host: peer.host, port: peer.port, database: peer.database, user: peer.capture.name, password,
|
|
connectionTimeoutMillis: 5_000, statement_timeout: 10_000, options: "-c default_transaction_read_only=on",
|
|
ssl: { ca: peer.leaf, servername: peer.host, rejectUnauthorized: true, checkServerIdentity(host, certificate) {
|
|
if (!certificate.raw.equals(leaf.raw)) return new DatabaseRestoreDataRefused()
|
|
return checkServerIdentity(host, certificate)
|
|
} },
|
|
})
|
|
try {
|
|
await client.connect()
|
|
const { rows } = await client.query(`SELECT oid::text AS role_oid FROM pg_catalog.pg_roles
|
|
WHERE rolname=$1::pg_catalog.name AND rolname=SESSION_USER AND rolname=CURRENT_USER`, [peer.capture.name])
|
|
if (rows.length !== 1 || rows[0].role_oid !== peer.capture.signedOid) throw new DatabaseRestoreDataRefused()
|
|
const snapshot = await captureRuntimeRestoreData(client, () => {}, targetCheckSql)
|
|
readRuntimeDatabaseArchivePeer(runtime)
|
|
return snapshot
|
|
} catch { throw new DatabaseRestoreDataRefused() }
|
|
finally { await client.end() }
|
|
})
|
|
}
|