36 lines
2.8 KiB
TypeScript
36 lines
2.8 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { mkdtemp, readFile, rm } from "node:fs/promises"
|
|
import os from "node:os"
|
|
import path from "node:path"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
import { boundedDatabaseCommand, MAX_DATABASE_DUMP_BYTES } from "./bounded-database-dump.js"
|
|
|
|
const run = (script: string, options: Parameters<typeof boundedDatabaseCommand>[2] = {}) => boundedDatabaseCommand(process.execPath, ["-e", script], options)
|
|
assert.deepEqual(await run("process.stdout.write(Buffer.from([80,71,68,77,80,0,255,128]))"), Buffer.from([80,71,68,77,80,0,255,128]))
|
|
assert.throws(() => run("", { maxBytes: MAX_DATABASE_DUMP_BYTES + 1 }))
|
|
const cancelled = new AbortController(); cancelled.abort()
|
|
await assert.rejects(run("throw Error('must not run')", { signal: cancelled.signal }), /отменён/)
|
|
await assert.rejects(run("process.stderr.write('postgresql://user:password@host/database');process.exit(2)"), error => error instanceof Error && !/password|postgresql|database/.test(error.message))
|
|
await assert.rejects(boundedDatabaseCommand(path.join(os.tmpdir(), "missing-db-command-" + Date.now()), []), /недоступна/)
|
|
const directory = await mkdtemp(path.join(os.tmpdir(), "mm-bounded-dump-"))
|
|
try {
|
|
for (const reason of ["cancel", "timeout", "stdout", "stderr", "authority"] as const) {
|
|
const pidfile = path.join(directory, reason), controller = new AbortController()
|
|
let checks = 0
|
|
const pending = run(`require('node:fs').writeFileSync(${JSON.stringify(pidfile)},String(process.pid));setInterval(()=>{${reason === "stdout" ? "process.stdout.write(Buffer.alloc(4096))" : reason === "stderr" ? "process.stderr.write(Buffer.alloc(4096))" : ""}},10)`, {
|
|
signal: controller.signal, maxBytes: reason === "stdout" ? 1024 : undefined, timeoutMs: reason === "timeout" ? 1500 : 10000,
|
|
authorize: reason === "authority" ? async () => { checks++; throw Error("credential secret must never surface") } : undefined,
|
|
})
|
|
// Attach immediately so a fast child failure is never an unhandled rejection.
|
|
const rejected = assert.rejects(pending, error => error instanceof Error && !error.message.includes("secret"))
|
|
let pid = 0
|
|
for (let i = 0; i < 100; i++) { try { pid = Number(await readFile(pidfile, "utf8")); break } catch { await delay(10) } }
|
|
assert.ok(pid > 0, "Real child reached startup")
|
|
if (reason === "cancel") controller.abort()
|
|
await rejected
|
|
assert.throws(() => process.kill(pid, 0), "Cancellation must settle only after the child has closed")
|
|
if (reason === "authority") assert.ok(checks > 0)
|
|
}
|
|
} finally { await rm(directory, { recursive: true, force: true }) }
|
|
console.log("bounded database dump real-child tests passed: binary, limits, cancellation, deadline, authority, sanitized diagnostics and drained child")
|