diff --git a/README.md b/README.md index 5d339d7..69ac437 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,8 @@ If you also keep a written record of each drill for your team or an audit (which Backups record your installed Postgres extensions in the manifest, and the drill pre-installs them in the sandbox before restoring — including switching to a pgvector-enabled sandbox image when your database uses `vector` columns. +Every drill first pulls the sandbox image (`postgres:-alpine`, or `pgvector/pgvector:pg`) from Docker Hub, so an image you already have is updated to the latest published build of that tag. After the November 2026 PostgreSQL security fix, older versions of `pg_dump` can write `pg_attver` into a backup, and a sandbox without the fix rejects that option. If you already have the image and the update fails or takes more than 5 minutes, the drill uses your copy and prints a warning. + The sandbox restore runs up to 4 parallel `pg_restore` jobs, sized from the CPUs and memory Docker reports, so a 2 vCPU / 8 GB machine gets 2. Table data and index builds run in parallel. Foreign keys, triggers and policies run on a single connection to keep their error messages separate, including errors about Supabase-managed objects such as `auth.users`. `backupdrill restore` into a real Supabase project stays on a single connection. For a snapshot with Auth users, the drill does more once its usual checks are done. In the same sandbox it restores the two Auth tables and compares their row counts with the backup. It adds the foreign keys into them that it otherwise skips, recreates the triggers on them that a restore would recreate (the rest are listed as manual steps), and simulates an email sign-up as `supabase_auth_admin`, the role Supabase Auth uses, then rolls it back. If a trigger fails on that test sign-up (an email sign-up with no user metadata), the report says so. The result is an `auth` section in the report. For now it doesn't change whether the drill passes. diff --git a/package.json b/package.json index 98c1141..9a53bc9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "backupdrill", - "version": "2.11.1", + "version": "2.11.2", "description": "Open-source CLI to back up a Supabase project to your own S3/R2/B2 bucket (the Postgres database, Auth users when your role can read them, and Storage files once you add the project's Storage S3 keys), then run a restore drill that proves the backup restores.", "type": "module", "bin": { diff --git a/src/auth-restore.ts b/src/auth-restore.ts index 49e4d49..b4c3386 100644 --- a/src/auth-restore.ts +++ b/src/auth-restore.ts @@ -245,6 +245,17 @@ const STAGE_TEXT: Record = { committed: "committing", }; +/** + * 失败说明 "<阶段> failed: <主错误>" 里的主错误(按已知阶段前缀去掉);别的形状的失败原样返回。 + * 给 restoreFailureAdvice 用:它只看主错误开头,语句正文里碰巧出现的字不能触发建议 + */ +export function primaryAuthRestoreError(failure: string): string { + for (const text of [...Object.values(STAGE_TEXT), "connecting to the target"]) { + if (failure.startsWith(`${text} failed: `)) return failure.slice(text.length + " failed: ".length); + } + return failure; +} + const STAGE_MARK = "backupdrill-stage:"; const XID_MARK = "backupdrill-xid:"; diff --git a/src/drill.ts b/src/drill.ts index b5ed917..c854631 100644 --- a/src/drill.ts +++ b/src/drill.ts @@ -1,4 +1,4 @@ -import { execFile, spawn } from "node:child_process"; +import { execFile, spawn, type ChildProcess } from "node:child_process"; import { randomBytes } from "node:crypto"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -225,21 +225,80 @@ export function sandboxDataVolumeTarget(major: number): string { * 停掉命令也说不准守护进程之后还会不会把容器建出来(交叉审查)。拆开之后,慢的那一步(第一次拉镜像 * 可能好几分钟)什么都不建,中断时直接停掉;docker run 只剩建容器和启动。 */ +/** + * 本地已有镜像也要每次 pull:标签(postgres:17-alpine)跟着小版本走,只拉一次就会永远停在当时的小版本。 + * 2026-11-24 事故:worker 上的沙箱停在 17.10,源库被 Supabase 升到带 CVE-2026-6460 补丁的新小版本, + * 旧 pg_dump 导出的 `ALTER COLUMN ... SET (pg_attver=…)` 在 17.10 上报 unrecognized parameter, + * 整个演练失败;17.12 会接受并忽略这句。镜像没变时 pull 只比一次清单,很快。 + * 已有缓存时刷新失败(断网、仓库限流、超时)不算演练失败:退回本地镜像并提示。 + * + * 收尾不等 stdio 关闭:docker 拉起的凭据助手可能还占着 stderr(交叉审查用卡住的助手复现)。 + * 只等 docker 本身退出;到点或被中断时,连同它的子孙进程(凭据助手)一起 SIGKILL,再把我们这头的 + * 管道关掉,CLI 才能照常退出,也不会每次超时留下一个助手。 + * pull 留在演练所在的进程组里(不 detach):worker 叫停演练时按组结束,连助手一起带走。 + */ +// 测试用的环境变量只为把 5 分钟缩短到几秒;不对用户公开 +const IMAGE_REFRESH_TIMEOUT_MS = Number(process.env.BACKUPDRILL_TEST_IMAGE_REFRESH_TIMEOUT_MS) || 5 * 60_000; + +/** 子孙进程 pid(pgrep -P 逐层往下找);没有 pgrep(Windows)时返回空,只停进程本身 */ +async function descendantPids(pid: number): Promise { + const children = await execFileAsync("pgrep", ["-P", String(pid)], { timeout: 5_000 }).then( + ({ stdout }) => stdout.split("\n").map(Number).filter((n) => n > 0), + () => [] as number[] + ); + const deeper = await Promise.all(children.map(descendantPids)); + return [...children, ...deeper.flat()]; +} + +/** 先记下子孙再停:父进程一死,子进程就被收养,pgrep -P 再也找不到它们 */ +async function killProcessTree(child: ChildProcess): Promise { + if (!child.pid || child.exitCode !== null || child.signalCode !== null) return; + const descendants = await descendantPids(child.pid); + child.kill("SIGKILL"); + for (const pid of descendants) { + try { + process.kill(pid, "SIGKILL"); + } catch { + // 已经退出 + } + } +} + async function ensureImage(image: string): Promise { const present = await execFileAsync("docker", ["image", "inspect", "--format", "{{.Id}}", image]).then( () => true, () => false ); - if (present) return; throwIfInterrupted(); - log.step(`Pulling ${image}…`); - const pull = execFileAsync("docker", ["pull", "--quiet", image]); - const forget = pull.child ? stopOnInterrupt(pull.child) : () => {}; - try { - await pull; - } finally { - forget(); - } + log.step(present ? `Checking ${image} for updates…` : `Pulling ${image}…`); + const pull = spawn("docker", ["pull", "--quiet", image], { stdio: ["ignore", "ignore", "pipe"] }); + const forget = onInterrupt(() => killProcessTree(pull)); + // 只留开头一段用来说明失败原因,其余照样读掉,别让吵闹的 docker 把内存撑大 + let stderr = ""; + pull.stderr?.on("data", (chunk) => { + if (stderr.length < 4096) stderr += chunk.toString(); + }); + let timer: NodeJS.Timeout | undefined; + const outcome = await new Promise<"ok" | "failed" | "timeout">((resolve) => { + pull.on("error", (error) => { + stderr ||= error.message; + resolve("failed"); + }); + pull.on("exit", (code) => resolve(code === 0 ? "ok" : "failed")); + if (present) timer = setTimeout(() => resolve("timeout"), IMAGE_REFRESH_TIMEOUT_MS); + }); + clearTimeout(timer); + if (outcome === "timeout") await killProcessTree(pull); + pull.stderr?.destroy(); + forget(); + throwIfInterrupted(); + if (outcome === "ok") return; + const reason = + outcome === "timeout" + ? `docker pull timed out after ${Math.round(IMAGE_REFRESH_TIMEOUT_MS / 1000)}s` + : stderr.split("\n").map((line) => line.trim()).find(Boolean) ?? "docker pull failed"; + if (!present) throw new Error(`could not pull ${image}: ${reason}`); + log.warn(`Could not refresh ${image}; using the local copy (${reason})`); } async function startEphemeralPostgres(image: string, major: number, resourceName?: string): Promise { @@ -276,6 +335,8 @@ async function startEphemeralPostgres(image: string, major: number, resourceName "POSTGRES_DB=postgres", "-p", "127.0.0.1:0:5432", // 随机主机端口,避免撞端口 + // 拉镜像只在 ensureImage 里做(有超时、可中断);缓存恰好在刷新时被清掉的话,这里报错而不是悄悄再拉一次 + "--pull=never", `--shm-size=${tuning.shmSize}`, image, "postgres", @@ -604,6 +665,24 @@ interface PostDataResult { const MISSING_EXTENSION_ERROR = /type "[^"]+" does not exist|schema "[^"]+" does not exist|extension "[^"]+" is not available/i; +// 沙箱小版本早于 2026-11 安全更新(CVE-2026-6460):不认识旧 pg_dump 从已更新的源库导出的列参数。 +// 逐段看 pre-data 失败:主错误(段首 ERROR: 之后、Command was: 之前)整句就是这一条才算, +// 语句正文或 DETAIL 里出现这个词不算 +const PG_ATTVER_REJECTED = + /^pg_restore: error: could not execute query: ERROR:\s+unrecognized parameter "pg_attver"\s+Command was:/; + +/** pre-data 失败里有没有"沙箱不认 pg_attver"这一条(导出给测试) */ +export function sandboxRejectsAttver(preDataFailures: string[]): boolean { + return preDataFailures.some((failure) => PG_ATTVER_REJECTED.test(failure)); +} + +/** pre-data 硬失败;sandboxTooOld = 至少一段失败的主错误是沙箱不认 pg_attver */ +class PreDataRestoreError extends Error { + constructor(message: string, readonly sandboxTooOld: boolean) { + super(message); + } +} + /** 兼容层:历史签名保留,分类逻辑的单一权威在统一引擎(restore-engine.ts)。 */ export function classifyPostDataErrors(stderr: string): PostDataResult { const classified = classifyBlocks(stderr, SANDBOX_MANAGED_ERROR); @@ -638,7 +717,10 @@ async function pgRestore( grants: { schemas: dumpedSchemas, recorded: grants }, }); if (result.preData.failures.length) { - throw new Error(`pg_restore failed: ${result.preData.failures.join(" | ")}`); + throw new PreDataRestoreError( + `pg_restore failed: ${result.preData.failures.join(" | ")}`, + sandboxRejectsAttver(result.preData.failures) + ); } return { supabaseSkipped: result.postData.expectedSkips, @@ -1003,7 +1085,8 @@ export async function drillDump( const sourceMajor = parseInt(manifest.database.serverVersion, 10); const toolMajor = await localPgRestoreMajor(); const sandboxMajor = sandboxMajorFor(sourceMajor, toolMajor); - const pg = await startEphemeralPostgres(sandboxImage(manifest, sandboxMajor), sandboxMajor, opts.supervision?.resourceName); + const image = sandboxImage(manifest, sandboxMajor); + const pg = await startEphemeralPostgres(image, sandboxMajor, opts.supervision?.resourceName); let pass = false; // 异常路径视为失败,供 finally 决定 --keep 是否保留沙箱 try { if (sandboxMajor !== sourceMajor) { @@ -1059,6 +1142,16 @@ export async function drillDump( // 沙箱装不上扩展 + 错误特征命中"缺类型/schema/扩展" → 假设式归因到沙箱环境 // (不对备份健康下断言);其余失败与扩展无关,必须原样抛出 const message = (error as Error).message; + // 必须排在缺扩展归因前面:这类失败的连带错误(type "…" does not exist)也会命中 + // MISSING_EXTENSION_ERROR,2026-11-24 的告警就被误指成了 supabase_vault + if (error instanceof PreDataRestoreError && error.sandboxTooOld) { + throw new Error( + `restore failed: the drill sandbox (${image}) rejected "SET (pg_attver=…)". The sandbox needs the ` + + `November 2026 PostgreSQL security fix. Run "docker pull ${image}" and rerun the drill. Older pg_dump ` + + `versions can write this line when the source already has the fix. Use the latest minor version of ` + + `pg_dump for new backups. All errors: ${message}` + ); + } if (unavailable.length && MISSING_EXTENSION_ERROR.test(message)) { throw new Error( `restore failed; likely because the drill sandbox cannot install ` + diff --git a/src/restore.ts b/src/restore.ts index 97dcee0..7bb5a81 100644 --- a/src/restore.ts +++ b/src/restore.ts @@ -36,7 +36,7 @@ import { orphanedForeignKeysCheck, type OrphanedForeignKey } from "./orphaned-fo import { grantsCheck } from "./grants.js"; import { localPgRestoreMajor, restoreToolTargetBlocker } from "./pgbin.js"; import { describeTarget, restoreRecordKey, type RestorePhase, type RestoreRecord, type RestoreRecordStore } from "./restore-record.js"; -import { +import { primaryAuthRestoreError, AUTH_TABLE_KEYS, authRestoreFailureMessage, authRestoreNotes, @@ -556,8 +556,19 @@ async function dryRunPreflight( * 900 张表能过、1200 张表报 out of shared memory(2026-10-23,PG 17)。分区多的库会撞上。 * Supabase 只能用 CLI 调这个参数(会重启数据库),照官方文档的命令给出来。 */ -export function restoreFailureAdvice(failure: string): string { - if (!/max_locks_per_transaction/.test(failure)) return ""; +export function restoreFailureAdvice(failures: string[]): string { + // 2026-11 安全更新(CVE-2026-6460)后:更新前的 pg_dump 导出已更新的源库,会写出 + // `SET (pg_attver=…)`;已更新的目标会忽略它,没更新的目标直接拒绝。 + // 传进来的每一项都以服务端主错误开头(firstRestoreError / 去掉阶段前缀的 psql 错误), + // 只看开头:语句正文或 DETAIL 里出现这个词不算 + if (failures.some((failure) => /^unrecognized parameter "pg_attver"(?:\s|$)/.test(failure))) { + return ( + ' The target rejected "SET (pg_attver=…)" from the snapshot. Older pg_dump versions can write this ' + + "line when the source has the November 2026 PostgreSQL security fix. Update the target to the latest " + + "minor release for its current PostgreSQL major version and retry." + ); + } + if (!failures.some((failure) => /max_locks_per_transaction/.test(failure))) return ""; return ( " The target ran out of lock slots: a single-transaction restore holds a lock on every table, index " + "and sequence until it commits. Raise max_locks_per_transaction on the target and retry. On Supabase " + @@ -1048,7 +1059,7 @@ export async function runRestore( if (run.transaction === "committed" && run.afterCommit!.pass.failures.length === 0) await advance("done"); if (run.transaction !== "committed") { // 结果由事务本身说了算(没写 COMMIT,或 pg_xact_status 的回答),不再数 schema 里的对象去推断 - throw new Error(authRestoreFailureMessage(run) + restoreFailureAdvice(run.failure ?? "")); + throw new Error(authRestoreFailureMessage(run) + restoreFailureAdvice(run.failure ? [primaryAuthRestoreError(run.failure)] : [])); } const committed = run.transaction === "committed"; const pass = committed ? run.afterCommit!.pass : { expectedSkips: 0, failures: [run.failure!] }; @@ -1094,7 +1105,7 @@ export async function runRestore( " Check the target before doing anything else; restore won't write into it again while those " + "objects are there." : await targetStateAfterFailure(targetUrl, manifest.database.schemas)) + - restoreFailureAdvice(failures.join(" ")) + restoreFailureAdvice(failures) ); } result.restoredToDatabase = true; diff --git a/test/drill-interrupt.test.js b/test/drill-interrupt.test.js index 4b6704e..18791ea 100644 --- a/test/drill-interrupt.test.js +++ b/test/drill-interrupt.test.js @@ -11,6 +11,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { startFakeS3 } from "./fake-s3.js"; +import { parsePgDumpMajor, sandboxMajorFor } from "../dist/pgbin.js"; const x = promisify(execFile); const pgDump = process.env.BACKUPDRILL_PG_DUMP || "pg_dump"; @@ -127,6 +128,19 @@ function startDrill(s3, tmp, args, { ownGroup = false, env = {} } = {}) { return { child, exited, stderr: () => stderr }; } +/** 和 drill 选沙箱的规则一致:主版本取 max(源库 17, 本机 pg_restore 主版本),没有向量扩展就是 alpine 镜像 */ +async function sandboxImageForTest() { + const pgRestore = process.env.BACKUPDRILL_PG_RESTORE || "pg_restore"; + const toolMajor = parsePgDumpMajor((await x(pgRestore, ["--version"])).stdout.trim()); + return `postgres:${sandboxMajorFor(17, toolMajor)}-alpine`; +} + +/** 本地没有才拉:离线或被限流的机器上,只要镜像已在本地,回退路径照样测得了 */ +async function ensureLocalImage(image) { + const present = await x("docker", ["image", "inspect", image]).then(() => true, () => false); + if (!present) await x("docker", ["pull", "--quiet", image]); +} + const leftovers = (tmp) => readdirSync(tmp).filter((name) => name.startsWith("backupdrill-")); // target "process":只发给 CLI(`kill `、systemd 的 SIGTERM),子进程收不到; @@ -252,7 +266,10 @@ test( /** * 假的 docker:放在 PATH 最前面,别的子命令照转真 docker。 * mode "slow-pull":image inspect 说镜像不在,pull 挂 10 分钟(模拟第一次拉镜像); - * mode "late-create":run 先等 4 秒再真的去建容器(模拟守护进程晚一点才把容器建出来)。 + * mode "late-create":run 先等 4 秒再真的去建容器(模拟守护进程晚一点才把容器建出来); + * mode "pull-fails":镜像在本地(真 image inspect),pull 直接失败(模拟断网、仓库限流); + * mode "pull-ok":pull 记下标记后成功退出,不真的去拉; + * mode "pull-hangs":pull 拉起一个占着 stderr 的子进程(模拟卡住的凭据助手),自己也不理 SIGTERM、一直不退出。 * 每次 pull / run 把自己的 pid 和容器名写进 mark 文件。 */ async function fakeDocker(tmp, mode) { @@ -269,9 +286,17 @@ const args = process.argv.slice(2); const real = () => process.exit(spawnSync(${JSON.stringify(realDocker)}, args, { stdio: "inherit" }).status ?? 1); const mode = ${JSON.stringify(mode)}; if (mode === "slow-pull" && args[0] === "image" && args[1] === "inspect") process.exit(1); -if (mode === "slow-pull" && args[0] === "pull") { +if (args[0] === "pull" && mode !== "late-create") { fs.writeFileSync(${JSON.stringify(marks.pull)}, String(process.pid)); - setTimeout(() => process.exit(0), 600000); + if (mode === "slow-pull") setTimeout(() => process.exit(0), 600000); + else if (mode === "pull-fails") { console.error("Error response from daemon: toomanyrequests"); process.exit(1); } + else if (mode === "pull-hangs") { + const helper = require("child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: ["ignore", "ignore", "inherit"] }); + fs.writeFileSync(${JSON.stringify(marks.pull)}, process.pid + " " + helper.pid); + process.on("SIGTERM", () => {}); + setInterval(() => {}, 1000); + } + else process.exit(0); } else if (args[0] === "run") { fs.writeFileSync(${JSON.stringify(marks.run)}, process.pid + " " + args[args.indexOf("--name") + 1]); if (mode === "late-create") setTimeout(real, 4000); else real(); @@ -311,6 +336,76 @@ test( } ); +// 2026-11-24:worker 上的沙箱镜像拉过一次就再没更新,停在 17.10,恢复不了 Supabase 升到 2026-11 +// 安全更新之后导出的 dump。本地已有镜像也要去刷新;刷新失败退回本地镜像,演练照常 +for (const mode of ["pull-ok", "pull-fails", "pull-hangs"]) { + test( + `drill: with the sandbox image already local, it still checks for a newer one (${mode})`, + { skip: canRun ? false : "requires Docker + pg_dump", timeout: 180_000 }, + async () => { + const tmp = mkdtempSync(join(tmpdir(), "bd-sig-test-")); + const s3 = await startFakeS3({ bucket: "backups" }); + let helper = null; + try { + await seedBucket(s3, await makeDump(tmp)); + // 沙箱用哪个镜像跟着本机 pg_restore 的主版本走(18+ 就是 postgres:18-alpine),先确保它在本地 + const sandbox = await sandboxImageForTest(); + await ensureLocalImage(sandbox); + const docker = await fakeDocker(tmp, mode); + const run = startDrill(s3, tmp, [], { + env: { PATH: docker.PATH, ...(mode === "pull-hangs" ? { BACKUPDRILL_TEST_IMAGE_REFRESH_TIMEOUT_MS: "3000" } : {}) }, + }); + const { code } = await run.exited; + assert.equal(code, 0, `exit code; stderr:\n${run.stderr()}`); + assert.ok(existsSync(docker.marks.pull), "docker pull was run although the image was local"); + if (mode === "pull-hangs") { + assert.match(run.stderr(), /Could not refresh \S+; using the local copy \(docker pull timed out after 3s\)/); + const [dockerPid, helperPid] = readFileSync(docker.marks.pull, "utf8").split(" ").map(Number); + helper = helperPid; + assert.equal(alive(dockerPid), false, "the hung docker pull was stopped"); + assert.equal(alive(helperPid), false, "its credential helper was stopped too"); + } + if (mode === "pull-fails") { + assert.ok(run.stderr().includes(`Could not refresh ${sandbox}; using the local copy (Error response from daemon: toomanyrequests)`), run.stderr()); + } + if (mode === "pull-ok") assert.doesNotMatch(run.stderr(), /Could not refresh/); + } finally { + // 断言失败时别把助手留在机器上 + if (helper && alive(helper)) process.kill(helper, "SIGKILL"); + await s3.close(); + rmSync(tmp, { recursive: true, force: true }); + } + } + ); +} + +// worker 叫停演练是给整个进程组发 SIGKILL(killDrillProcessGroup):卡住的 pull 和它拉起的助手 +// 必须在这个组里,不能自成一组漏掉 +test( + "drill: killing the drill's process group also ends a hung image refresh and its helper", + { skip: canRun ? false : "requires Docker + pg_dump", timeout: 120_000 }, + async () => { + const tmp = mkdtempSync(join(tmpdir(), "bd-sig-test-")); + const s3 = await startFakeS3({ bucket: "backups" }); + let pids = []; + try { + await seedBucket(s3, await makeDump(tmp)); + await ensureLocalImage(await sandboxImageForTest()); + const docker = await fakeDocker(tmp, "pull-hangs"); + const run = startDrill(s3, tmp, [], { ownGroup: true, env: { PATH: docker.PATH } }); + await waitFor("docker pull to start", () => existsSync(docker.marks.pull) && readFileSync(docker.marks.pull, "utf8").includes(" "), 120_000); + pids = readFileSync(docker.marks.pull, "utf8").split(" ").map(Number); + process.kill(-run.child.pid, "SIGKILL"); + await run.exited; + await waitFor("pull and helper to exit", () => pids.every((pid) => !alive(pid)), 10_000); + } finally { + for (const pid of pids) if (alive(pid)) process.kill(pid, "SIGKILL"); + await s3.close(); + rmSync(tmp, { recursive: true, force: true }); + } + } +); + test( "drill: SIGINT while docker run is still creating the sandbox waits for it, then removes it", { skip: canRun ? false : "requires Docker + pg_dump", timeout: 120_000 }, diff --git a/test/dump-sql.test.js b/test/dump-sql.test.js index 2655a8f..0bdef9d 100644 --- a/test/dump-sql.test.js +++ b/test/dump-sql.test.js @@ -14,6 +14,8 @@ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { restoreFailureAdvice } from "../dist/restore.js"; +import { primaryAuthRestoreError } from "../dist/auth-restore.js"; +import { sandboxRejectsAttver } from "../dist/drill.js"; // 夹具:pg_restore 17.11 对 supabase/postgres:17.6.1.084 源库转储(--schema=public)的原样输出 // (`pg_restore -f - -L `,注释和 SET 行去掉了) @@ -139,8 +141,44 @@ test("restoreFailureAdvice:锁槽用完时告诉用户怎么调 max_locks_per_tr "Command was: CREATE TABLE public.t1015 (id bigint NOT NULL);\n" ); assert.match(lockFailure, /out of shared memory HINT: You might need to increase "max_locks_per_transaction"\./); - assert.match(restoreFailureAdvice(lockFailure), /supabase postgres-config update --config max_locks_per_transaction=256/); - assert.equal(restoreFailureAdvice('schema "private" does not exist'), ""); + assert.match(restoreFailureAdvice([lockFailure]), /supabase postgres-config update --config max_locks_per_transaction=256/); + assert.equal(restoreFailureAdvice(['schema "private" does not exist']), ""); +}); + +test("restoreFailureAdvice:目标库早于 2026-11 安全更新、拒绝 pg_attver 时说清楚要升级目标", () => { + const failure = firstRestoreError( + 'pg_restore: error: could not execute query: ERROR: unrecognized parameter "pg_attver"\n' + + "Command was: CREATE TABLE public.t (id bigint NOT NULL);\nALTER TABLE ONLY public.t ALTER COLUMN id SET (pg_attver=171396040);\n" + ); + assert.match(restoreFailureAdvice([failure]), /November 2026 PostgreSQL security fix/); + assert.match(restoreFailureAdvice([failure]), /latest minor release/); + // 带 Auth 的恢复:失败说明带阶段前缀,去掉前缀后才是主错误 + assert.match( + restoreFailureAdvice([primaryAuthRestoreError('restoring the database failed: unrecognized parameter "pg_attver"')]), + /November 2026/ + ); + assert.equal( + restoreFailureAdvice([primaryAuthRestoreError('restoring the database failed: relation "x" does not exist DETAIL: failed: unrecognized parameter "pg_attver"')]), + "" + ); + // 词只出现在语句正文里、主错误是别的:不能叫用户去升级 PostgreSQL + const unrelated = firstRestoreError( + 'pg_restore: error: could not execute query: ERROR: relation "public.x" does not exist\n' + + "Command was: COMMENT ON TABLE public.t IS 'unrecognized parameter \"pg_attver\"';\n" + ); + assert.equal(restoreFailureAdvice([unrelated]), ""); +}); + +test("sandboxRejectsAttver:2026-11-24 告警那种 pre-data 失败(pg_attver 加连带的缺类型)认得出;词只在语句里不算", () => { + const attver = + 'pg_restore: error: could not execute query: ERROR: unrecognized parameter "pg_attver" Command was: CREATE TABLE public.t ( id uuid NOT NULL ); ALTER TABLE ONLY public.t ALTER COLUMN id SET (pg_attver=171396040);'; + const cascade = + 'pg_restore: error: could not execute query: ERROR: type "public.t" does not exist Command was: CREATE FUNCTION public.f() RETURNS SETOF public.t LANGUAGE sql AS $$ select * from public.t $$;'; + assert.equal(sandboxRejectsAttver([attver, cascade]), true); + assert.equal(sandboxRejectsAttver([cascade]), false); + const quoted = + "pg_restore: error: could not execute query: ERROR: relation \"public.x\" does not exist Command was: COMMENT ON TABLE public.t IS 'ERROR: unrecognized parameter \"pg_attver\" Command was:';"; + assert.equal(sandboxRejectsAttver([quoted]), false); }); test("parseTableColumns:pg_dump 建表语句里的列类型(修饰符、COLLATE、DEFAULT、生成列、CHECK 行、跨行的名字)", () => { diff --git a/test/plugin-workflow.test.js b/test/plugin-workflow.test.js index 6eaadd7..0b839c7 100644 --- a/test/plugin-workflow.test.js +++ b/test/plugin-workflow.test.js @@ -11,7 +11,7 @@ import { fileURLToPath } from "node:url"; const ROOT = fileURLToPath(new URL("..", import.meta.url)); const WORKFLOW = join(ROOT, "plugin/skills/supabase-backup/assets/scheduled-backup.yml"); -// 不属于 `backup` 的设置:恢复目标和恢复用的 pg_restore / psql、演练沙箱、Storage 回传阈值;pg_dump 路径由前一步写进 $GITHUB_ENV +// 不属于 `backup` 的设置:恢复目标和恢复用的 pg_restore / psql、演练沙箱、Storage 回传阈值、只给测试用的开关;pg_dump 路径由前一步写进 $GITHUB_ENV const NOT_BACKUP_SETTINGS = new Set([ "BACKUPDRILL_TARGET_DATABASE_URL", "BACKUPDRILL_TARGET_SERVICE_ROLE_KEY", @@ -21,6 +21,7 @@ const NOT_BACKUP_SETTINGS = new Set([ "BACKUPDRILL_SANDBOX_URL", "BACKUPDRILL_TUS_THRESHOLD", "BACKUPDRILL_PG_DUMP", + "BACKUPDRILL_TEST_IMAGE_REFRESH_TIMEOUT_MS", ]); function settingsTheCliReads() {