diff --git a/.gitignore b/.gitignore index 597c709..5beb3c2 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ backupdrill.config.json # Supabase CLI 本地状态(含项目 ref):公开仓永不提交。 # 只忽略本地状态目录,不要写成 supabase/ —— 那会连迁移/函数一起吞掉。 /supabase/.temp/ + +# git worktree(同一项目的东西只放在项目目录里) +.worktrees/ diff --git a/README.md b/README.md index e72d7e0..96966a9 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ All recognized variables: |---|---|---| | `BACKUPDRILL_DATABASE_URL` | Source connection string (falls back to `DATABASE_URL`) | — (required) | | `BACKUPDRILL_PROJECT_NAME` | Readable name used in object keys and the manifest | `supabase` | -| `BACKUPDRILL_SCHEMAS` | Comma-separated schemas to dump | `public` | +| `BACKUPDRILL_SCHEMAS` | Comma-separated schemas to dump. If the list includes `auth`, `dump.pgcustom` copies the Auth tables as-is, including any pending password-reset and confirmation tokens, and BackupDrill skips the separate `auth.dump`. When BackupDrill writes a separate `auth.dump`, it clears those tokens before upload | `public` | | `BACKUPDRILL_AUTH` | Supabase Auth users (`auth.users` + `auth.identities`) go into `auth.dump` next to the database dump whenever the role can read them. `off` leaves them out. `on` makes a backup that can't include them exit with code 3; the database backup still completes either way. Also `--auth` / `--no-auth`, or `"auth": true/false` in the config file | on when possible | | `BACKUPDRILL_S3_ENDPOINT` | S3-compatible endpoint (R2/B2/self-hosted; omit for AWS S3) | — | | `BACKUPDRILL_S3_REGION` | Destination bucket region | `auto` | @@ -199,7 +199,7 @@ The drill's structural checks (tables, rows, checksums) can't know what "working backupdrill drill --check-cmd "npm run smoke" # BACKUPDRILL_SANDBOX_URL points at the restored copy ``` -Your command runs after all structural checks pass, with `BACKUPDRILL_SANDBOX_URL` set to the sandbox's connection string. Exit 0 means pass; the result shows up in the report as an `app checks` line, and a non-zero exit fails the drill (the report keeps structural and app-level failures clearly separate). Entirely optional — without the flag, nothing changes and the report has no `app checks` line. There's a 10-minute timeout (the whole process tree is killed), and `--keep` leaves the sandbox container running when a drill fails so you can inspect it — the report JSON then includes a `keptSandbox` object with the container id and connection string (`docker rm -f ` when done). +Your command runs after all structural checks pass, with `BACKUPDRILL_SANDBOX_URL` set to the sandbox's connection string. Exit 0 means pass; the result shows up in the report as an `app checks` line, and a non-zero exit fails the drill (the report keeps structural and app-level failures clearly separate). Entirely optional — without the flag, nothing changes and the report has no `app checks` line. There's a 10-minute timeout (the whole process tree is killed), and `--keep` leaves the sandbox container running when a drill fails so you can inspect it — the report JSON then includes a `keptSandbox` object with the container id and connection string (`docker rm -f ` when done). The Auth sign-up test only runs when the backup has at least one custom Auth trigger to recreate. BackupDrill waits for any `--check-cmd` to finish, then disconnects the sandbox from its Docker networks before running the test. If the drill fails with `--keep`, BackupDrill skips the sign-up test so you can still connect. **What this can and cannot verify, honestly:** `BACKUPDRILL_SANDBOX_URL` connects as the sandbox **superuser**, and superusers bypass row-level security. The sandbox does carry a stub of the Supabase runtime — an `auth` schema whose `uid()`/`jwt()`/`role()`/`email()` return null, and the `anon`/`authenticated`/`service_role` roles — so functions, column defaults and policies that reference them restore instead of being skipped. The sandbox deliberately does not create Supabase-managed *tables* such as `auth.users`: an index, constraint or policy that points at one is reported as a skipped managed object (these are restored in a second, post-data pass where that exemption applies). A skipped foreign key into `auth.users` still matters for a real restore, see [Tables that reference auth.users](#tables-that-reference-authusers). A *view* over one is created in the strict first pass instead, and fails the drill — a real gap in what a public-only backup can rebuild, shown rather than hidden. A function *body* that selects from `auth.users` is different: PostgreSQL does not validate string-literal bodies (`AS $$ … $$`) during a restore (`check_function_bodies` is off in every dump), so such a function is recreated and the drill passes — it would only fail when called. The exception is an SQL-standard `BEGIN ATOMIC … END` body, which is parsed and dependency-checked at creation regardless of that setting, so one of those referencing a managed table fails the drill like a view does. That is exactly what `--check-cmd` is for: if your application depends on such a function, call it there. So use `--check-cmd` for data and business invariants ("orders reference existing users", "the row count I care about is sane"). It is **not** an RLS behavior test — `auth.uid()` is a stub and you are a superuser; verifying RLS takes an authenticated client stack with real JWTs, which no restore sandbox can fake generically. @@ -364,7 +364,7 @@ docker run -d --name backupdrill --restart unless-stopped \ - Arguments go straight to the CLI: `docker run --rm -e … ghcr.io/backupdrill/backupdrill estimate` or `… --help`. To start a backup now in a running scheduled container: `docker exec backupdrill backupdrill backup`. - `BACKUPDRILL_CRON` takes a standard 5-field expression or a shortcut such as `@daily`. Anything else stops the container at start (exit code 64) instead of leaving it idle. - `drill` needs Docker to start its throwaway Postgres, and the image doesn't get access to your Docker daemon, so run drills where Docker is available (your machine, or the GitHub Action with `drill: "true"`). -- Tags: `latest`, the CLI version (e.g. `2.10.1`), and `sha-`. Images are built for amd64 and arm64. +- Tags: `latest`, the CLI version (e.g. `2.11.1`), and `sha-`. Images are built for amd64 and arm64. ## Alerts with Healthchecks.io diff --git a/package.json b/package.json index c6bf002..98c1141 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "backupdrill", - "version": "2.11.0", + "version": "2.11.1", "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-archive.ts b/src/auth-archive.ts new file mode 100644 index 0000000..483f5ee --- /dev/null +++ b/src/auth-archive.ts @@ -0,0 +1,389 @@ +import { PassThrough, Readable, Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { createDeflate, createInflate } from "node:zlib"; + +/** + * 2.11.1 起:auth.dump 上传前,把 auth.users 里待处理的认证状态抹掉(找回密码、邮箱确认、改邮箱改手机、 + * 重新认证的 token,以及它们的发送时间和待改成的新邮箱/手机号)。 + * + * 为什么在备份时就抹:这些 token 在源项目上还没过期时,GoTrue 的 /verify 收 token_hash,拿到桶的人 + * 可以直接用它在**源项目**上重置密码、确认邮箱。恢复时(CLEAR_PENDING_AUTH_SQL)本来就会清空, + * 所以留在备份里没有任何用处,只有风险。2.10 / 2.11.0 写的旧归档仍靠恢复端那一句清空。 + * + * 为什么改归档而不是改 pg_dump:pg_dump 没有"导出时把某几列换掉"的办法;另起一份数据(COPY 查询结果) + * 又会让 auth.dump 不再是一份 pg_restore 能直接读的归档,RECOVERY.md 的手工步骤、演练、恢复都得跟着改。 + * 所以 pg_dump 的参数一个不动(源库上的负载、锁、快照都和以前一样),只在它的输出流进桶之前, + * 改写 auth.users 那一段 COPY 数据;目录、其余数据段逐字节不变。sha256 和字节数按改写后的内容算, + * 和桶里的文件一致。 + * + * 只认 pg_dump 在管道上写出的 custom 格式(目录里不带数据偏移),归档版本 1.12–1.16(PostgreSQL 10–17 的 + * pg_dump;18 仍是 1.16)。认不出的一律报错:Auth 这一节记失败,绝不把没抹干净的归档当成功上传。 + */ + +/** + * 要抹的列 → 抹成的 COPY 文本值。和恢复端 CLEAR_PENDING_AUTH_SQL 逐列一致(测试里对齐检查): + * token 和待改的新邮箱/手机号写空串(GoTrue 读这些列时不接受 NULL),确认状态写 0,发送时间写 NULL。 + * 某个 GoTrue 版本里没有的列就跳过。 + */ +export const PENDING_AUTH_COPY_VALUES: ReadonlyArray = [ + ["confirmation_token", ""], + ["recovery_token", ""], + ["email_change_token_new", ""], + ["email_change_token_current", ""], + ["phone_change_token", ""], + ["reauthentication_token", ""], + ["email_change", ""], + ["phone_change", ""], + ["email_change_confirm_status", "0"], + ["confirmation_sent_at", "\\N"], + ["recovery_sent_at", "\\N"], + ["email_change_sent_at", "\\N"], + ["phone_change_sent_at", "\\N"], + ["reauthentication_sent_at", "\\N"], +]; + +// pg_backup_archiver.h 里的版本号:MAKE_ARCHIVE_VERSION(major, minor, rev) +const archiveVersion = (major: number, minor: number, rev: number) => (major * 256 + minor) * 256 + rev; +const K_VERS_1_12 = archiveVersion(1, 12, 0); +const K_VERS_1_14 = archiveVersion(1, 14, 0); +const K_VERS_1_15 = archiveVersion(1, 15, 0); +const K_VERS_1_16 = archiveVersion(1, 16, 0); +const K_VERS_MAX_KNOWN = archiveVersion(1, 16, 255); +const ARCH_CUSTOM = 1; +const BLK_DATA = 1; +const K_OFFSET_POS_NOT_SET = 1; +const K_OFFSET_POS_SET = 2; +// pg_compress_algorithm(1.15 起头部里存算法;之前存压缩级别,0 = 不压缩,其余都是 zlib) +const COMPRESSION_NONE = 0; +const COMPRESSION_GZIP = 1; + +class ArchiveError extends Error {} + +/** 从异步迭代器按字节数取数据的读取器;只在需要拼接时才拷贝 */ +class ByteReader { + private chunks: Buffer[] = []; + private buffered = 0; + private ended = false; + constructor(private readonly source: AsyncIterator) {} + + private async fill(n: number): Promise { + while (this.buffered < n && !this.ended) { + const next = await this.source.next(); + if (next.done) this.ended = true; + else if (next.value.length) { + this.chunks.push(next.value); + this.buffered += next.value.length; + } + } + return this.buffered >= n; + } + + async atEnd(): Promise { + return !(await this.fill(1)); + } + + /** 正好 n 个字节;不够就是归档被截断了 */ + async read(n: number): Promise { + // 空字符串(长度 0)在目录里很常见;缓冲恰好读空时也不能去碰不存在的第一块 + if (n === 0) return Buffer.alloc(0); + if (!(await this.fill(n))) throw new ArchiveError("the archive ended early"); + const head = this.chunks[0]; + if (head.length >= n) { + this.chunks[0] = head.subarray(n); + if (!this.chunks[0].length) this.chunks.shift(); + this.buffered -= n; + return head.subarray(0, n); + } + const all = Buffer.concat(this.chunks); + this.chunks = all.length > n ? [all.subarray(n)] : []; + this.buffered -= n; + return all.subarray(0, n); + } + + /** 至多 n 个字节、至少 1 个,不拼接:大块数据按到手的大小往下传 */ + async readUpTo(n: number): Promise { + if (!(await this.fill(1))) throw new ArchiveError("the archive ended early"); + const head = this.chunks[0]; + if (head.length <= n) { + this.chunks.shift(); + this.buffered -= head.length; + return head; + } + this.chunks[0] = head.subarray(n); + this.buffered -= n; + return head.subarray(0, n); + } +} + +/** pg_dump 的整数:1 字节符号 + intSize 字节小端 */ +function decodeInt(raw: Buffer): number { + let value = 0; + for (let i = raw.length - 1; i >= 1; i--) value = value * 256 + raw[i]; + return raw[0] ? -value : value; +} + +function encodeInt(value: number, intSize: number): Buffer { + const out = Buffer.alloc(1 + intSize); + let rest = value; + for (let i = 1; i <= intSize; i++) { + out[i] = rest % 256; + rest = Math.floor(rest / 256); + } + if (rest) throw new ArchiveError("a data chunk is too large for this archive"); + return out; +} + +/** COPY auth.users (a, b, "c") FROM stdin; → 列名(去掉引号) */ +export function copyColumns(copyStmt: string): string[] { + const m = /^COPY\s+\S+\s+\(([\s\S]*)\)\s+FROM\s+stdin;\s*$/i.exec(copyStmt.trim()); + if (!m) throw new ArchiveError("the COPY statement of auth.users isn't in the expected form"); + const columns: string[] = []; + const re = /\s*(?:"((?:[^"]|"")*)"|([^\s,"]+))\s*(,|$)/y; + let match: RegExpExecArray | null; + let at = 0; + const list = m[1]; + while (at < list.length && (match = re.exec(list))) { + columns.push(match[1] !== undefined ? match[1].replace(/""/g, '"') : match[2]); + at = re.lastIndex; + if (match[3] === "") break; + } + if (at !== list.length || !columns.length) throw new ArchiveError("the column list of auth.users couldn't be read"); + return columns; +} + +/** + * 逐字段改写 COPY 文本:按制表符和换行切字段,要抹的那几列换掉,其余字节原样往下传。COPY 文本格式里数据中的 + * 制表符和换行都转义成 \t、\n,所以按原始字节 0x09 / 0x0A 切是安全的(服务端编码都兼容 ASCII)。 + * + * 不按整行缓冲:一行可以非常大(metadata 很长、又压缩得很好时,解压出来的一行能远超内存)。逐块扫一遍, + * 要抹的字段直接丢、其余直接写出,占用的内存只和一块输入一样大,和行多长无关。 + * 字段数和列数对不上就报错,不猜(已经写出去的半行随这次上传一起作废)。 + */ +function copyLineScrubber(columns: string[], replace: Map): Transform { + // 第一列要抹的话就认不出 "\." 结束标记(它的字节被丢了);auth.users 的第一列从来不是 token + if (replace.has(0)) throw new ArchiveError("the first column of auth.users is unexpectedly one to clear"); + let field = 0; // 当前行里的第几个字段 + let skipping = false; // 当前字段要抹:它的字节不写出 + let lineLength = 0; // 当前行到目前为止的字节数(只用来认结束标记,到 3 就不再数) + let lineHead = 0; // 当前行的头两个字节 + // pg_dump 在每段 COPY 数据末尾写 "\.",后面只跟几个空行。结束标记必须有,之后只许是空行: + // 别的字节都说明这不是 pg_dump 写的样子,宁可失败也不上传 + let afterEndMarker = false; + const afterEndError = () => new ArchiveError("the data of auth.users has something after its end marker"); + const onlyNewlines = (chunk: Buffer, from: number) => { + for (let i = from; i < chunk.length; i++) if (chunk[i] !== 0x0a) throw afterEndError(); + }; + const fieldCountError = (fields: number) => + new ArchiveError(`a row of auth.users has ${fields} fields, but the COPY statement lists ${columns.length} columns`); + const scan = (chunk: Buffer, out: Buffer[]): void => { + let start = 0; // 下一个还没写出的字节 + for (let i = 0; i < chunk.length; i++) { + const b = chunk[i]; + if (b !== 0x09 && b !== 0x0a) { + if (lineLength < 3) { + if (lineLength < 2) lineHead = lineHead * 256 + b; + lineLength++; + } + continue; + } + if (skipping) { + out.push(replace.get(field)!); + start = i; // 分隔符本身照常写出 + skipping = false; + } + if (b === 0x09) { + field++; + lineLength = 3; // 有制表符就不可能是结束标记 + if (field >= columns.length) throw fieldCountError(field + 1); + } else { + const endMarker = field === 0 && lineLength === 2 && lineHead === 0x5c2e; + if (!endMarker && field !== columns.length - 1) throw fieldCountError(field + 1); + field = 0; + lineLength = 0; + lineHead = 0; + if (endMarker) { + afterEndMarker = true; + onlyNewlines(chunk, i + 1); + out.push(chunk.subarray(start)); + return; + } + } + if (replace.has(field)) { + out.push(chunk.subarray(start, i + 1)); + start = i + 1; + skipping = true; + } + } + if (!skipping) out.push(chunk.subarray(start)); + }; + return new Transform({ + transform(chunk: Buffer, _encoding, callback) { + try { + if (afterEndMarker) { + onlyNewlines(chunk, 0); + return callback(null, chunk); + } + const out: Buffer[] = []; + scan(chunk, out); + callback(null, out.length === 1 ? out[0] : Buffer.concat(out)); + } catch (error) { + callback(error as Error); + } + }, + flush(callback) { + // 没有结束标记 = 数据不完整(或者不是 pg_dump 写的):不能当成抹干净了 + if (!afterEndMarker) return callback(new ArchiveError("the data of auth.users has no end marker")); + callback(); + }, + }); +} + +/** + * 把 pg_dump 输出的 auth.dump 流改写成抹掉待处理 token 的版本。返回的流出错 = 没能抹干净,调用方必须当失败处理。 + * 只读输入、只写输出,不碰数据库。 + */ +export function scrubPendingAuthTokens(input: Readable): Readable { + const out = new PassThrough(); + const write = async (buf: Buffer): Promise => { + if (!buf.length) return; + if (out.destroyed) throw new ArchiveError("stopped"); + if (out.write(buf)) return; + await new Promise((resolve, reject) => { + const done = () => { + out.off("drain", onDrain); + out.off("close", onClose); + }; + const onDrain = () => (done(), resolve()); + const onClose = () => (done(), reject(new ArchiveError("stopped"))); + out.once("drain", onDrain); + out.once("close", onClose); + }); + }; + void (async () => { + const reader = new ByteReader(input[Symbol.asyncIterator]()); + // 头部和目录原样照抄:读到多少写多少 + const take = async (n: number): Promise => { + const buf = await reader.read(n); + await write(buf); + return buf; + }; + const magic = await take(5); + if (magic.toString("latin1") !== "PGDMP") throw new ArchiveError("the Auth archive isn't a pg_dump custom-format archive"); + const [vmaj, vmin] = await take(2); + const vrev = vmaj > 1 || (vmaj === 1 && vmin > 0) ? (await take(1))[0] : 0; + const version = archiveVersion(vmaj, vmin, vrev); + if (version < K_VERS_1_12 || version > K_VERS_MAX_KNOWN) { + throw new ArchiveError(`pg_dump wrote archive version ${vmaj}.${vmin}.${vrev}, which this CLI can't clear pending Auth tokens from`); + } + const intSize = (await take(1))[0]; + const offSize = (await take(1))[0]; + if (intSize < 1 || intSize > 8 || offSize < 1 || offSize > 16) throw new ArchiveError("the archive header is malformed"); + const readInt = async () => decodeInt(await take(1 + intSize)); + const readStr = async (): Promise => { + const length = await readInt(); + if (length < 0) return null; + return (await take(length)).toString("utf8"); + }; + if ((await take(1))[0] !== ARCH_CUSTOM) throw new ArchiveError("the Auth archive isn't in custom format"); + let compression: number; + if (version >= K_VERS_1_15) compression = (await take(1))[0]; + else compression = (await readInt()) === 0 ? COMPRESSION_NONE : COMPRESSION_GZIP; + if (compression !== COMPRESSION_NONE && compression !== COMPRESSION_GZIP) { + throw new ArchiveError("the Auth archive uses a compression method this CLI can't rewrite"); + } + for (let i = 0; i < 7; i++) await readInt(); // 创建时间(秒、分、时、日、月、年、夏令时) + await readStr(); // 库名 + await readStr(); // 服务端版本 + await readStr(); // pg_dump 版本 + + const tocCount = await readInt(); + // 目录里声明了有数据的条目:每一条都要在后面见到它的数据段,少一段就是归档不完整 + const withData = new Set(); + let target: { dumpId: number; columns: string[] } | null = null; + for (let i = 0; i < tocCount; i++) { + const dumpId = await readInt(); + await readInt(); // hadDumper + await readStr(); // tableoid + await readStr(); // oid + const tag = await readStr(); + const desc = await readStr(); + await readInt(); // section + await readStr(); // defn + await readStr(); // dropStmt + const copyStmt = await readStr(); + const namespace = await readStr(); + await readStr(); // tablespace + if (version >= K_VERS_1_14) await readStr(); // tableam + if (version >= K_VERS_1_16) await readInt(); // relkind + await readStr(); // owner + await readStr(); // 旧的 WITH OIDS 标记 + while ((await readStr()) !== null); // 依赖,以 NULL 结尾 + const offsetFlag = (await take(1))[0]; + await take(offSize); + if (offsetFlag === K_OFFSET_POS_NOT_SET) withData.add(dumpId); + // 改写会改变数据段的长度:目录里记着数据偏移的归档(写进可寻址文件的)不能这样改。管道上写出的不会记 + if (offsetFlag === K_OFFSET_POS_SET) throw new ArchiveError("the Auth archive records data offsets, which this CLI can't rewrite"); + if (desc === "TABLE DATA" && namespace === "auth" && tag === "users") { + if (target) throw new ArchiveError("the Auth archive has the data of auth.users twice"); + target = { dumpId, columns: copyColumns(copyStmt ?? "") }; + } + } + if (!target) throw new ArchiveError("the Auth archive has no data entry for auth.users"); + const replace = new Map(); + for (const [column, value] of PENDING_AUTH_COPY_VALUES) { + const index = target.columns.indexOf(column); + if (index !== -1) replace.set(index, Buffer.from(value)); + } + + // 数据段:每段 = 类型字节 + dumpId + 若干 [长度, 数据] 块,长度 0 结束 + let scrubbed = false; + while (!(await reader.atEnd())) { + if ((await take(1))[0] !== BLK_DATA) throw new ArchiveError("the Auth archive has a data block of an unexpected type"); + const dumpId = await readInt(); + if (!withData.delete(dumpId)) throw new ArchiveError("the Auth archive contains a duplicate data block or one missing from its table of contents"); + if (dumpId !== target.dumpId) { + for (let length = await readInt(); length !== 0; length = await readInt()) { + if (length < 0) throw new ArchiveError("the archive has a malformed data chunk"); + for (let left = length; left > 0; ) { + const piece = await reader.readUpTo(left); + await write(piece); + left -= piece.length; + } + } + continue; + } + if (scrubbed) throw new ArchiveError("the Auth archive has the data of auth.users twice"); + scrubbed = true; + // 原来的数据块不照抄,逐块读出来解压(按头部的压缩方式)、改写、再压缩,写成新的数据块 + async function* payload(): AsyncGenerator { + for (let length = decodeInt(await reader.read(1 + intSize)); length !== 0; length = decodeInt(await reader.read(1 + intSize))) { + if (length < 0) throw new ArchiveError("the archive has a malformed data chunk"); + for (let left = length; left > 0; ) { + const piece = await reader.readUpTo(left); + yield piece; + left -= piece.length; + } + } + } + const emitChunks = async (source: AsyncIterable) => { + for await (const piece of source) { + if (!piece.length) continue; + await write(encodeInt(piece.length, intSize)); + await write(piece); + } + }; + if (compression === COMPRESSION_GZIP) { + await pipeline(Readable.from(payload()), createInflate(), copyLineScrubber(target.columns, replace), createDeflate(), emitChunks); + } else { + await pipeline(Readable.from(payload()), copyLineScrubber(target.columns, replace), emitChunks); + } + await write(encodeInt(0, intSize)); + } + if (!scrubbed) throw new ArchiveError("the Auth archive has no data block for auth.users"); + if (withData.size) throw new ArchiveError("the Auth archive ended before all of its data blocks"); + out.end(); + })().catch((error: unknown) => { + out.destroy(error instanceof Error ? error : new Error(String(error))); + }); + return out; +} diff --git a/src/auth-backup.ts b/src/auth-backup.ts index c1163e1..2b96dcd 100644 --- a/src/auth-backup.ts +++ b/src/auth-backup.ts @@ -1,13 +1,15 @@ import pg from "pg"; import { attachPgErrorGuard, pgConnectOptions } from "./supabase-ca.js"; import type { AuthSection, AuthTriggerInfo, AuthPolicyInfo } from "./manifest.js"; +import { PENDING_AUTH_COPY_VALUES } from "./auth-archive.js"; /** * Supabase Auth 用户(auth.users + auth.identities)的备份。 * * 只备这两张表:用户 ID、邮箱、密码哈希、metadata、登录方式。sessions、refresh token、MFA 因子、 * SSO 配置一律不备——恢复到新项目后用户重新登录一次即可,MFA 因子可能用旧项目的密钥加密过, - * 带过去反而可能把用户锁在外面。 + * 带过去反而可能把用户锁在外面。2.11.1 起 auth.users 里待处理的找回密码、邮箱确认等 token 在上传前就抹掉 + * (见 auth-archive.ts),pg_dump 的参数不变。 * * 不打扰现有备份是硬约束: * - "off"(库调用的默认值)时,备份命令、上传的文件、manifest 与没有这个功能时逐字节一致。 @@ -201,6 +203,8 @@ export type AuthInspection = triggers: AuthTriggerInfo[]; policies: AuthPolicyInfo[]; grants: Array<{ table: string; grantee: string; privilege: string }>; + /** auth.users 上第一个不是 Supabase 自带的、可能拒收抹过的值的对象(见 firstNonStockObject);null = 可以抹 */ + nonStockObject: string | null; }; // Supabase 平台自己的 schema。触发器函数或策略引用的函数在这些 schema 里时算平台对象 @@ -330,9 +334,16 @@ export async function inspectAuth( order by 1, 2, 3` ); + // 比对的是 pg_get_*def 打印出来的原文:让它和白名单记下时的打印方式一样,不受角色/库级设置影响 + // (quote_all_identifiers 会给每个名字加引号;search_path 决定名字前带不带 schema) + await client.query("set local quote_all_identifiers = off"); + await client.query("set local search_path = ''"); + const nonStockObject = await firstNonStockObject(client); + await client.query("commit"); return { readable: true, + nonStockObject, grants: grants.rows, users: Number(c.users), identities: Number(c.identities), @@ -364,6 +375,141 @@ export async function inspectAuth( } } +/** + * 把系统目录里的名字(约束名、索引名、列名)写进日志、manifest 和 RECOVERY.md 之前用:加双引号, + * 反斜杠、引号和所有控制字符(C0、DEL、C1、U+2028/2029)都转义成可见的文字。名字可以含换行, + * 原样写进终端就能伪造一行日志 + */ +export function quotedName(name: string): string { + return `"${name.replace(/[\\"\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (ch) => { + if (ch === "\\" || ch === '"') return `\\${ch}`; + if (ch === "\n") return "\\n"; + if (ch === "\r") return "\\r"; + if (ch === "\t") return "\\t"; + return `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`; + })}"`; +} + +/** + * Supabase(GoTrue)自带的 auth.users:2026-11-21 在 supabase/postgres 17.6 上跑完 GoTrue v2.186.0 的全部迁移后 + * 从系统目录读出来的原文(pg_get_constraintdef / pg_get_indexdef / pg_get_expr;PG16、PG17 输出一致)。 + * 索引去掉名字只比定义,名字改过不算不同 + */ +const STOCK_AUTH_USERS = { + /** CHECK / FOREIGN KEY / EXCLUDE 约束;自带的只有这一条 CHECK,没有外键和排他约束 */ + constraints: ["CHECK (((email_change_confirm_status >= 0) AND (email_change_confirm_status <= 2)))"], + /** 索引:唯一索引(含主键、UNIQUE 约束背后的索引),以及带表达式的普通索引 */ + indexes: [ + "CREATE UNIQUE INDEX ON auth.users USING btree (id)", + "CREATE UNIQUE INDEX ON auth.users USING btree (phone)", + "CREATE UNIQUE INDEX ON auth.users USING btree (email) WHERE (is_sso_user = false)", + ...["confirmation_token", "recovery_token", "email_change_token_current", "email_change_token_new", "reauthentication_token"].map( + (column) => `CREATE UNIQUE INDEX ON auth.users USING btree (${column}) WHERE ((${column})::text !~ '^[0-9 ]*$'::text)` + ), + "CREATE INDEX ON auth.users USING btree (instance_id, lower((email)::text))", + ], + /** 生成列 → 表达式 */ + generated: new Map([["confirmed_at", "LEAST(email_confirmed_at, phone_confirmed_at)"]]), +}; + +/** pg_get_indexdef 的结果去掉索引名:"CREATE [UNIQUE] INDEX <名字> ON ..." → "CREATE [UNIQUE] INDEX ON ..." */ +function indexDefWithoutName(def: string): string { + return def.replace(/^(CREATE (?:UNIQUE )?INDEX )(?:"(?:[^"]|"")*"|\S+) ON /, "$1ON "); +} + +/** + * 2.11.1 起 auth.dump 里待处理的 token 被抹成空串、发送时间成 NULL、确认状态成 0(见 auth-archive.ts)。 + * 用户自己在 auth.users 上加的约束可能不接受这些值(例如 CHECK (recovery_token <> '')、token 列上不带条件的 + * 唯一索引、从 token 算出来的生成列再加 CHECK):原样的归档恢复得了、抹过的却恢复不了,这比不抹更糟。 + * + * 规则:**可能碰到被抹的列**的东西,必须和 Supabase 自带的一模一样,否则不写 auth.dump、Auth 这一节记失败并点名 + * 第一个对不上的对象。碰不到的(UNIQUE (email)、新加的非 token 列上的唯一索引、instance_id 上的外键)一律放过—— + * 不然和 token 无关的改动、或者 GoTrue 以后新加的索引,都会让 Auth 备份悄悄停掉。"可能碰到"按系统目录判断: + * - 约束的 conkey、索引的键列里有被抹的列(CHECK 的 conkey 就是它引用的全部列,0 = 整行); + * - 索引的表达式和 WHERE 条件、生成列的表达式:读系统目录里存的表达式树(indexprs / indpred / adbin 的文本), + * 里面每个列引用都是 ":varattno N",0 = 整行。不用 pg_depend:全是表达式的索引在那里总记着对整张表(列号 0) + * 的依赖,分不出 lower(email) 和真的整行引用; + * - 排他约束按它背后的索引判断; + * - 生成列的表达式引用了被抹的列:它本身要和自带的一样,用到它的约束、索引也算可能碰到; + * - 外键:只看 conkey; + * - 被抹成 NULL 的列不能是 NOT NULL,被抹的列不能是域类型。 + * 要比对的对象类型:CHECK、外键、排他约束(pg_get_constraintdef 原文),唯一索引和排他约束背后的索引 + * (去掉名字的 pg_get_indexdef 原文),带表达式或 WHERE 条件的普通索引(恢复时重建要算它们;只按列建的普通索引 + * 重建不会失败,不管),生成列(列名和表达式原文)。和 pg_dump 一样只看有效的索引。 + * + * **只读系统目录,不执行任何用户定义的东西**:约束表达式里可以调用用户函数,不能拿备份角色的权限在生产库上跑。 + * 跑在 inspectAuth 已经开着的 REPEATABLE READ READ ONLY 事务里,不另开连接。返回第一个对不上的对象(没有就是 null) + */ +async function firstNonStockObject(client: pg.Client): Promise { + const blanked = new Map(PENDING_AUTH_COPY_VALUES); + const columns = await client.query<{ attnum: number; name: string; notnull: boolean; domain: boolean }>( + `select a.attnum, a.attname as name, a.attnotnull as notnull, t.typtype = 'd' as domain + from pg_attribute a join pg_type t on t.oid = a.atttypid + where a.attrelid = 'auth.users'::regclass and a.attnum > 0 and not a.attisdropped + order by a.attnum` + ); + // 被抹的列,加上从它们算出来的生成列:碰到这些列的东西才要比对 + const touched = new Set(); + for (const c of columns.rows) { + if (!blanked.has(c.name)) continue; + touched.add(c.attnum); + if (c.domain) return `a domain-typed column ${quotedName(c.name)}`; + if (blanked.get(c.name) === "\\N" && c.notnull) return `a NOT NULL column ${quotedName(c.name)}`; + } + // 列号 0 = 整行,什么列都可能碰到 + const mayTouch = (referenced: number[]) => referenced.some((n) => n === 0 || touched.has(n)); + /** 表达式树(pg_node_tree 的文本)里引用的列号;表达式里的常量是按字节存的,不会被误认成列引用 */ + const columnsIn = (...trees: Array) => + trees.flatMap((tree) => [...(tree ?? "").matchAll(/:varattno (-?\d+)/g)].map((m) => Number(m[1]))); + + const generated = await client.query<{ attnum: number; name: string; expr: string; tree: string }>( + `select a.attnum, a.attname as name, pg_get_expr(d.adbin, d.adrelid) as expr, d.adbin::text as tree + from pg_attribute a join pg_attrdef d on d.adrelid = a.attrelid and d.adnum = a.attnum + where a.attrelid = 'auth.users'::regclass and a.attgenerated <> '' and not a.attisdropped + order by a.attnum` + ); + for (const g of generated.rows) { + if (!mayTouch(columnsIn(g.tree))) continue; + if (STOCK_AUTH_USERS.generated.get(g.name) !== g.expr) return `a custom generated column ${quotedName(g.name)}`; + touched.add(g.attnum); + } + + // CHECK 的 conkey 是它引用的全部列;外键只有自己的列。排他约束在下面按它背后的索引判断 + const constraints = await client.query<{ name: string; type: string; def: string; keys: number[] }>( + `select conname as name, contype::text as type, pg_get_constraintdef(oid) as def, coalesce(conkey::int[], '{}') as keys + from pg_constraint + where conrelid = 'auth.users'::regclass and contype in ('c', 'f') + order by conname` + ); + for (const k of constraints.rows) { + const could = k.type === "f" ? k.keys.some((n) => touched.has(n)) : mayTouch(k.keys); + if (!could || STOCK_AUTH_USERS.constraints.includes(k.def)) continue; + return `a custom ${k.type === "c" ? "check constraint" : "foreign key"} ${quotedName(k.name)}`; + } + + // pg_dump 导出的索引(和它一样只要 indisvalid、indisready 的:CONCURRENTLY 建失败留下的无效索引不进归档)。 + // 恢复时每个索引都要在抹过的数据上重建:唯一索引、排他约束会因重复值失败;普通索引只要有表达式或 WHERE + // 条件,也会在重建时算它们(例如 1 / length(recovery_token) 碰到 '' 就除零)。只按列建的普通索引重建不会失败,不管 + const indexes = await client.query<{ + name: string; def: string; keys: number[]; exprs: string | null; pred: string | null; unique: boolean; exclusion: boolean; + }>( + `select c.relname as name, pg_get_indexdef(i.indexrelid) as def, i.indkey::int2[] as keys, + i.indexprs::text as exprs, i.indpred::text as pred, i.indisunique as unique, i.indisexclusion as exclusion + from pg_index i join pg_class c on c.oid = i.indexrelid + where i.indrelid = 'auth.users'::regclass and i.indisvalid and i.indisready + order by c.relname` + ); + for (const ix of indexes.rows) { + if (!ix.unique && !ix.exclusion && ix.exprs === null && ix.pred === null) continue; + // 键列里的 0 是"这一列是表达式"的占位,表达式用到的列从表达式树里读 + const referenced = [...ix.keys.filter((n) => n !== 0), ...columnsIn(ix.exprs, ix.pred)]; + if (!mayTouch(referenced) || STOCK_AUTH_USERS.indexes.includes(indexDefWithoutName(ix.def))) continue; + const kind = ix.exclusion ? "exclusion constraint" : ix.unique ? "unique index" : "index"; + return `a custom ${kind} ${quotedName(ix.name)}`; + } + return null; +} + /** * schema 是否在这次备份里:按 pg_dump 读模式的规则匹配 schemas(含通配)。平台 schema 不算: * 用户自己建在 extensions 之类里的函数不在任何一份归档里,新项目里也没有。 diff --git a/src/auth-drill.ts b/src/auth-drill.ts index 8e8bd6f..39d7224 100644 --- a/src/auth-drill.ts +++ b/src/auth-drill.ts @@ -1,4 +1,4 @@ -import { createHash } from "node:crypto"; +import { createHash, randomBytes } from "node:crypto"; import { createReadStream } from "node:fs"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -16,7 +16,8 @@ import { interrupted } from "./interrupt.js"; * 演练里的 Auth 校验(2.10.0 起,附加模式)。 * * 在演练照旧做完、通过与否已经定下之后,在同一个沙箱里:把 auth.dump 的两张表建出来、灌数据, - * 补上之前因为沙箱没有 auth 表而跳过的外键,建可以自动恢复的触发器,再以 GoTrue 的身份模拟一次注册。 + * 补上之前因为沙箱没有 auth 表而跳过的外键,建可以自动恢复的触发器,再以 GoTrue 的身份模拟一次注册 + * (2.11.1 起断网跑,见 OfflineSandbox)。 * 结果只写进报告的 auth 一节,**不改变演练结论**,自己出错也只记在这一节里——上线初期先观察, * 是否计入结论由以后决定(PRD 增补 §0.1 第 5 条)。 */ @@ -44,6 +45,25 @@ export interface AuthDumpForDrill { error?: string; } +/** + * 2.11.1 起:模拟注册只在断了网的沙箱里跑。注册会触发用户挂在 auth.users 上的触发器,触发器经 dblink、 + * postgres_fdw、http 之类的扩展连出去写的东西,不会跟着事务回滚——演练不能替用户往外部系统里写一个测试用户。 + * 由演练(drill.ts)提供:它管着沙箱容器。 + */ +export interface OfflineSandbox { + /** + * 断开沙箱容器的全部网络,用容器里的 psql(连容器自己的 127.0.0.1)跑 script。marker 是这次注册的随机标记 + * (也是 script 里 DO 块的引号标签),被叫停或超时时靠它找到并停掉容器里那次注册。**之后再也不接回网络**: + * 只确认 SQL 会话都退出了,不能证明触发器没有留下别的东西(还没起来的 docker exec、后台进程), + * 接回去它们就又能连出去。所以模拟注册是这个沙箱上做的最后一件事。断不开就抛错,一句 SQL 都不跑 + */ + runOffline(script: string, marker: string, signal?: AbortSignal): Promise<{ code: number | null; stdout: string }>; + /** 是否已经开始断网(断网后经主机端口的连接都连不上了) */ + offline(): boolean; + /** 断网之后叫停时用:经 docker exec 终止沙箱里所有客户端会话 */ + stopOfflineSessions(): Promise; +} + // 报告会发给用户、进运营者告警,**一律不放报错原文**:触发器能在任何错误码下抛出自定义消息、 // 伪造对象名字段,里面可以是任意数据,靠脱敏堵不干净。只给 SQLSTATE 映射出的固定说法和 SQLSTATE 本身 const SQLSTATE_TEXT: Record = { @@ -63,6 +83,9 @@ const SQLSTATE_TEXT: Record = { "57014": "a statement timed out or was cancelled", "40P01": "a deadlock", P0001: "an exception was raised", + P0004: "an assertion failed", + "08001": "a connection couldn't be made", + "08006": "a connection failed", }; function safeError(error: unknown): string { @@ -155,12 +178,122 @@ async function insertStatement(client: Client, table: "users" | "identities"): P return `insert into auth.${table} (${names.join(", ")}) values (${values.join(", ")})`; } +/** + * 模拟注册的 SQL,交给容器里的 psql 跑。注册放在 DO 块的子事务里:出错时接住,把 SQLSTATE、出错位置 + * (错误上下文)、错误消息和 DETAIL 写进四个会话变量(消息和 DETAIL 只用来判断是不是连不上,不进报告); + * 最后一行输出由我们自己的 select 拼出来——触发器的 NOTICE + * 只进 stderr,改不了这一行。成功路径最后覆盖写一遍,触发器事先写进去的值不算数。整个事务最后回滚。 + * 美元引号的标签每次随机:插入语句里的列名来自归档,不能让它把 DO 块提前截断 + */ +export function signupScript(userInsert: string, identityInsert: string, marker: string): string { + const tag = `$bd_${marker}$`; + return [ + "set statement_timeout = '5min';", + "set lock_timeout = '1min';", + "begin;", + `do ${tag}`, + "declare", + " state text;", + " context text;", + " message text;", + " detail text;", + "begin", + " begin", + " set local role supabase_auth_admin;", + ` ${userInsert};`, + ` ${identityInsert};`, + // 延迟检查的约束和约束触发器平时在提交时才跑:这里立刻跑完,才算这次注册真的能成 + " set constraints all immediate;", + // WHEN OTHERS 接不住 ASSERT 失败(P0004),单独接;两个分支做同一件事 + " exception", + ...["assert_failure", "others"].flatMap((condition) => [ + ` when ${condition} then`, + " get stacked diagnostics state = returned_sqlstate, context = pg_exception_context,", + " message = message_text, detail = pg_exception_detail;", + " perform set_config('backupdrill.signup_state', state, true);", + " perform set_config('backupdrill.signup_context', context, true);", + " perform set_config('backupdrill.signup_message', message, true);", + " perform set_config('backupdrill.signup_detail', detail, true);", + " return;", + ]), + " end;", + " perform set_config('backupdrill.signup_state', 'ok', true);", + " perform set_config('backupdrill.signup_context', '', true);", + " perform set_config('backupdrill.signup_message', '', true);", + " perform set_config('backupdrill.signup_detail', '', true);", + "end", + `${tag};`, + "select 'backupdrill-signup ' || current_setting('backupdrill.signup_state') || ' ' ||", + " encode(convert_to(current_setting('backupdrill.signup_context'), 'UTF8'), 'hex') || ' ' ||", + " encode(convert_to(current_setting('backupdrill.signup_message'), 'UTF8'), 'hex') || ' ' ||", + " encode(convert_to(current_setting('backupdrill.signup_detail'), 'UTF8'), 'hex');", + "rollback;", + "", + ].join("\n"); +} + +/** + * "没测成、可能是因为断网"只认有连不上的证据的情况,其余一律按真的注册失败报(23xxx、P0001、42xxx 等都是真问题)。 + * 证据要在错误消息或 DETAIL 里:解析不了主机名、网络不可达、没有路由、连接被拒、连接超时这类 + * (libc 的措辞不同:glibc 写 "Network is unreachable",musl 写 "Network unreachable",两种都认)。然后: + * - SQLSTATE 08 类(dblink、postgres_fdw 连不上);同样是 08 类的认证、配置失败(密码不对、没有 pg_hba + * 条目)没有这类证据,按真失败报; + * - 或者出错的那条语句(错误上下文的第一行)本身是联网调用(dblink、http 扩展、pg_net)或 COPY ... PROGRAM + * (http 扩展的 libcurl 错误码是通用的 XX000,程序失败是 38000)。COPY ... PROGRAM 的消息通常只说 + * "程序失败",看不出原因,这时也按真失败报。 + * 上下文是用户函数里出错那条语句的原文,写成别的样子(动态 SQL 等)就认不出,同样按真失败报——宁可报一次 + * 需要人看的失败,也不把真问题藏成"没测成"。错误原文只在这里用来判断,不进报告(见 safeError) + */ +const NETWORK_CALL = /\b(dblink\w*|http(_\w+)?|net\.http_\w+)\s*\(|\b(to|from)\s+program\b/i; +const CONNECTION_FAILURE = + /could not translate host name|could not resolve|couldn't resolve|resolve host|bad address|name or service not known|temporary failure in name resolution|network (is )?unreachable|host (is )?unreachable|no route to host|connection refused|connection timed out|timeout expired|timeout was reached|couldn't connect to server/i; + +function failedForLackOfNetwork(state: string, innermost: string, evidence: string): boolean { + if (!CONNECTION_FAILURE.test(evidence)) return false; + if (state.startsWith("08")) return true; + return (state === "XX000" || state === "38000") && NETWORK_CALL.test(innermost); +} + +/** psql 的输出 → 报告里的 signup。只用 SQLSTATE 和"错在不在触发器里",错误原文不进报告(见 safeError) */ +export function signupOutcome(result: { code: number | null; stdout: string }): NonNullable { + const line = /^backupdrill-signup (\S+) ([0-9a-f]*) ([0-9a-f]*) ([0-9a-f]*)$/m.exec(result.stdout); + if (result.code !== 0 || !line) { + // 超时(57014 接不住)或 psql 本身出错:没模拟成 + return { ran: false, detail: "psql did not confirm a sign-up result" }; + } + const [, state, contextHex, messageHex, detailHex] = line; + if (state === "ok") return { ran: true, ok: true }; + // 去掉我们自己那层 DO 块的上下文,剩下的才是表结构或用户的函数;第一行是真正出错的那条语句 + const where = Buffer.from(contextHex, "hex") + .toString("utf8") + .split("\n") + .filter((l) => !/inline_code_block/.test(l)) + .join("\n"); + // 消息和 DETAIL 只用来判断是不是连不上,不进报告 + const evidence = `${Buffer.from(messageHex, "hex").toString("utf8")}\n${Buffer.from(detailHex, "hex").toString("utf8")}`; + const triggerPath = + /PL\/pgSQL function|SQL function|trigger/i.test(where) || + ["23503", "23505", "42501", "42883", "42P01", "42703", "3F000", "P0001", "P0004"].includes(state); + if (triggerPath && failedForLackOfNetwork(state, where.split("\n")[0] ?? "", evidence)) { + return { + ran: false, + detail: `a database operation failed to connect while the sandbox was offline (SQLSTATE ${state})`, + }; + } + return triggerPath + ? { ran: true, ok: false, detail: `a new sign-up would fail: ${describeSqlstate(state)}${SIGNUP_TESTED_AS}` } + : { ran: false, detail: `couldn't simulate a sign-up: ${describeSqlstate(state)}` }; +} + export async function runAuthDrill( sandboxConnString: string, manifest: Manifest, mainDumpPath: string, authDump: AuthDumpForDrill, - signal?: AbortSignal + signal?: AbortSignal, + sandbox?: OfflineSandbox, + /** 不跑模拟注册的原因(例如 --keep 要留下一个连得上的沙箱);报告里记 ran: false */ + skipSignup?: string ): Promise { const auth = manifest.auth!; // 这一节的所有会话都带上 application_name,超时时 authDrillSection 只终止它们 @@ -331,6 +464,7 @@ export async function runAuthDrill( stopIfCancelled(); // ── 4. 以 GoTrue 的身份(supabase_auth_admin,非超级用户)模拟一次邮箱注册,事后回滚 ── + // 断网跑(见 OfflineSandbox):触发器的副作用只能留在沙箱里 let signup: NonNullable = { ran: false, detail: "no triggers of your own on the Auth tables" }; if (triggers.created.length) { await client.query("alter table auth.users owner to supabase_auth_admin; alter table auth.identities owner to supabase_auth_admin"); @@ -338,27 +472,23 @@ export async function runAuthDrill( const identityInsert = await insertStatement(client, "identities"); if (!userInsert || !identityInsert) { signup = { ran: false, detail: "couldn't build a test sign-up for this Auth table layout" }; + } else if (skipSignup) { + signup = { ran: false, detail: skipSignup }; + } else if (!sandbox) { + signup = { ran: false, detail: "offline testing is unavailable for this sandbox" }; } else { - await client.query("begin"); + // 断网之后这条 TCP 连接就断了:先关掉,后面不再用它 + await client.end().catch(() => {}); + client = undefined; + stopIfCancelled(); + let result: { code: number | null; stdout: string } | null = null; try { - await client.query("set local role supabase_auth_admin"); - await client.query(userInsert); - await client.query(identityInsert); - // 延迟检查的约束和约束触发器平时在提交时才跑:这里立刻跑完,才算这次注册真的能成 - await client.query("set constraints all immediate"); - signup = { ran: true, ok: true }; - } catch (error) { - const e = error as Error & { where?: string; code?: string }; - // 只有错在触发器里才算触发器的问题;造的测试行本身不合表结构,算没模拟成 - const triggerPath = - /PL\/pgSQL function|SQL function|trigger/i.test(e.where ?? "") || - ["23503", "23505", "42501", "42883", "42P01", "42703", "3F000", "P0001"].includes(e.code ?? ""); - signup = triggerPath - ? { ran: true, ok: false, detail: `a new sign-up would fail: ${safeError(e)}${SIGNUP_TESTED_AS}` } - : { ran: false, detail: `couldn't simulate a sign-up: ${safeError(e)}` }; - } finally { - await client.query("rollback").catch(() => {}); + const marker = randomBytes(8).toString("hex"); + result = await sandbox.runOffline(signupScript(userInsert, identityInsert, marker), marker, signal); + } catch { + signup = { ran: false, detail: "the offline test stopped before returning a result" }; } + if (result) signup = signupOutcome(result); } if (signup.ran && !signup.ok) problems.push(signup.detail!); // 有要验证的触发器,却没能模拟成注册:不能报"全部对上" @@ -443,7 +573,7 @@ export async function authDrillSection( * 托管 worker:begin 在开始前告诉它进入 Auth 阶段(被拒绝就不做这一节);stop 是它叫停这一节的信号。 * 两者都只影响这一节,演练结论不变 */ - runner: { begin?: () => Promise; stop?: AbortSignal } = {} + runner: { begin?: () => Promise; stop?: AbortSignal; sandbox?: OfflineSandbox; skipSignup?: string } = {} ): Promise { if (manifest.auth?.status !== "included" || !authDump) return undefined; if (interrupted()) return undefined; @@ -472,7 +602,9 @@ export async function authDrillSection( if (started) { void (async () => { await waitAtMost(started, 10_000); - await stopAuthSessions(sandboxConnString); + // 模拟注册已经把沙箱断了网:经主机端口连不上了,改经 docker exec 终止 + if (runner.sandbox?.offline()) await runner.sandbox.stopOfflineSessions(); + else await stopAuthSessions(sandboxConnString); })(); } }; @@ -492,7 +624,7 @@ export async function authDrillSection( } // 等 begin 的时候已经被叫停或到点了:比赛已经有了结果,这里不再开始 if (cancel.signal.aborted) return stoppedByRunner(); - work = runAuthDrill(sandboxConnString, manifest, mainDumpPath, await authDump, cancel.signal); + work = runAuthDrill(sandboxConnString, manifest, mainDumpPath, await authDump, cancel.signal, runner.sandbox, runner.skipSignup); return await work; })(), new Promise((resolve) => { diff --git a/src/backup.ts b/src/backup.ts index 83ec9f8..ed29cac 100644 --- a/src/backup.ts +++ b/src/backup.ts @@ -17,6 +17,7 @@ import { type AuthMode, type SharedSnapshot, } from "./auth-backup.js"; +import { scrubPendingAuthTokens } from "./auth-archive.js"; import { syncStorage } from "./storage.js"; import { inspectBucketAttrs } from "./storage-catalog.js"; import { projectRefOf, refFromStorageEndpoint, assertNoHostOverride } from "./restore-engine.js"; @@ -184,6 +185,11 @@ async function streamPgDump(opts: { endOnlyOnSuccess?: boolean; /** 失败时等上传中止最多 5 秒(Auth 那些新路径用;主 dump 的老路径不传,照旧等到中止完成) */ boundedCleanup?: boolean; + /** + * 上传前改写 pg_dump 的输出(只有 auth.dump 用:抹掉待处理的 token,见 auth-archive.ts)。 + * 字节数、sha256、大小上限都按改写后的内容算,和桶里的文件一致。要求同时传 endOnlyOnSuccess + */ + rewrite?: (stdout: Readable) => Readable; }): Promise<{ bytes: number; sha256: string }> { const hash = createHash("sha256"); let bytes = 0; @@ -235,13 +241,32 @@ async function streamPgDump(opts: { }); // endOnlyOnSuccess(auth.dump 用):pg_dump 成功退出才结束上传流,失败就带错中断,上传因此完不成—— // 不在用户桶里留下一个空的或半截的 auth.dump。主 dump 不传这个选项,行为与之前一致 - dump.stdout.pipe(meter, { end: !opts.endOnlyOnSuccess }); + const output = opts.rewrite ? opts.rewrite(dump.stdout) : dump.stdout; + output.pipe(meter, { end: !opts.endOnlyOnSuccess }); if (opts.endOnlyOnSuccess) { + // 改写的那一步要把最后一段也交给 meter 才算完:pg_dump 0 退出 + 改写端读完,两样都到了才结束上传流 + const rewriteFinished = opts.rewrite + ? new Promise((resolve) => output.once("end", resolve)) + : Promise.resolve(); dump.on("close", (code) => { - if (code === 0) meter.end(); + if (code === 0) void rewriteFinished.then(() => meter.end()); else meter.destroy(new Error(`pg_dump exited with code ${code}`)); }); } + if (opts.rewrite) { + // 改写失败 = 没能抹干净:这份归档绝不能上传成功。pg_dump 自己中途失败时改写端也会先报"归档被截断", + // 那时等它退出(最多 2 秒),原因以 pg_dump 的报错为准(上面的 close 处理);否则停掉 pg_dump、带着改写的错误中止 + output.on("error", (error) => { + void (async () => { + if (dump.exitCode === null && dump.signalCode === null) { + await waitAtMost(new Promise((resolve) => dump.once("close", resolve)), 2000); + } + if (dump.exitCode !== null && dump.exitCode !== 0) return; + dump.kill("SIGKILL"); + meter.destroy(error); + })(); + }); + } const dumpDone = new Promise((resolve, reject) => { dump.on("error", reject); // 启动失败(如 ENOENT) @@ -273,6 +298,7 @@ async function streamPgDump(opts: { dumpDone.catch(() => {}); // 没走到 Promise.all 时,被杀的 pg_dump 的退出也得有人接住 dump.kill("SIGKILL"); meter.destroy(); + if (output !== dump.stdout) output.destroy(); // 被叫停时中止上传但不等它(可能正卡在那)。可叫停的调用(Auth、共享快照那次)自己失败时, // 等中止最多 5 秒——中止本身也可能卡住,不能让调用方跟着卡。主 dump 的老路径照旧等中止完成 if (opts.signal?.aborted) void upload?.abort().catch(() => {}); @@ -341,6 +367,14 @@ type AuthPlan = * 主 dump 永远不因 Auth 受影响。返回 dump 时,共享快照已经导出,调用方负责释放。 */ async function planAuth(config: BackupConfig, writer: SnapshotWriter, mode: AuthMode): Promise { + // 2.11.1 起只有 auth.dump 抹掉待处理 token;schemas 里明写了 auth 时,主 dump 里的 Auth 表还是原样(含 token), + // 每次备份提醒一句。不管 Auth 备份开没开都提醒:主 dump 的内容和它无关 + if (authInSchemas(config.schemas) === "yes") { + log.warn( + "Your schema list includes auth, so dump.pgcustom holds the Auth tables as they are, " + + "including pending password-reset and confirmation tokens. Only auth.dump has them cleared." + ); + } if (mode === "off") return { kind: "none" }; // schemas 已经(可能)把 auth 带进主 dump:今天怎样以后还怎样,不另备一份。 // 确定包含 → skipped(数据就在主 dump 里);说不准 → 默认模式也 skipped,显式要求时记 failed, @@ -397,6 +431,17 @@ async function prepareAuthDump( await shared.release(); return { kind: "settled", section: authNotDone(mode, inspection.reason) }; } + // auth.users 上有不是 Supabase 自带的约束、唯一索引或生成列:抹过的 auth.dump 可能恢复不了,不写(见 firstNonStockObject) + if (inspection.nonStockObject) { + await shared.release(); + return { + kind: "settled", + section: { + status: "failed", + reason: `BackupDrill stopped before writing auth.dump. Clearing pending Auth tokens could cause a restore to fail because of ${inspection.nonStockObject} on auth.users.`, + }, + }; + } const uploadAuthDump = writer.uploadAuthDump!.bind(writer); return { kind: "dump", shared, inspection, key: writer.authDumpKey!, upload: (body) => uploadAuthDump(body) }; } @@ -432,6 +477,8 @@ async function dumpWithAuth( maxBytes: AUTH_DUMP_MAX_BYTES, signal: authAbort.signal, endOnlyOnSuccess: true, + // 2.11.1 起:待处理的找回密码、邮箱确认等 token 不进桶(见 auth-archive.ts) + rewrite: scrubPendingAuthTokens, }).then( (result) => ({ ok: true as const, ...result }), (error: unknown) => ({ ok: false as const, error }) @@ -579,7 +626,8 @@ function logAuthOutcome(auth: AuthSection, schemas: string[]): void { } return; } - const why = AUTH_SKIP_TEXT[auth.reason ?? ""] ?? auth.reason ?? "unknown reason"; + // 有的原因本身就是完整的句子(以句号结尾),后面还要接一句,去掉它的句号免得出现 ".." + const why = (AUTH_SKIP_TEXT[auth.reason ?? ""] ?? auth.reason ?? "unknown reason").replace(/\.$/, ""); if (auth.status === "skipped") { // 不是 Supabase 库时这是正常情况,不该显得像个问题 if (auth.reason === "no_auth_schema") log.step(`Auth users: skipped (${why}).`); diff --git a/src/drill.ts b/src/drill.ts index 1b118c9..b5ed917 100644 --- a/src/drill.ts +++ b/src/drill.ts @@ -25,7 +25,7 @@ import { orphanedForeignKeysCheck, tableKey, type OrphanedForeignKey } from "./o import { grantsCheck, type GrantRestore, type GrantedObject } from "./grants.js"; import { localPgRestoreMajor, restoreToolBreaksOnTarget, sandboxMajorFor } from "./pgbin.js"; import { log } from "./log.js"; -import { authDrillSection, type AuthDrillReport, type AuthDumpForDrill } from "./auth-drill.js"; +import { authDrillSection, type AuthDrillReport, type AuthDumpForDrill, type OfflineSandbox } from "./auth-drill.js"; import { onInterrupt, stopOnInterrupt, throwIfInterrupted } from "./interrupt.js"; const execFileAsync = promisify(execFile); @@ -81,7 +81,8 @@ export interface DrillReport { restoredTableCount: number; restoredRowTotal: number; /** --keep 且演练失败时:被保留的沙箱(供排查/脚本消费);其余情况不存在 */ - keptSandbox?: { containerId: string; connString: string }; + /** inspect(2.11.1 起):进沙箱的 docker exec 命令 */ + keptSandbox?: { containerId: string; connString: string; inspect?: string }; /** 源库自带孤儿行的外键:演练和真实恢复都把它们建成 NOT VALID,不算失败。没有时不出现 */ orphanedForeignKeys?: OrphanedForeignKey[]; /** @@ -97,6 +98,8 @@ interface Ephemeral { containerId: string; port: string; connString: string; + /** 2.11.1:模拟注册之前把沙箱断了网(确认摘掉之后才记,之后不再接回),connString 从此连不上 */ + offline: boolean; /** pg_restore 并行路数,随调参一起按 Docker 的内存和 CPU 定(见 sandboxTuning) */ restoreJobs: number; /** 删容器和数据卷;幂等,正常收尾和中断收尾共用 */ @@ -371,7 +374,7 @@ async function startEphemeralPostgres(image: string, major: number, resourceName "postgres", "-q", ]); - return { containerId, port, connString, restoreJobs: tuning.restoreJobs, teardown, forgetInterruptCleanup }; + return { containerId, port, connString, offline: false, restoreJobs: tuning.restoreJobs, teardown, forgetInterruptCleanup }; } catch { await new Promise((r) => setTimeout(r, 500)); } @@ -384,6 +387,204 @@ async function startEphemeralPostgres(image: string, major: number, resourceName } } +// ── 断网跑 SQL(模拟注册用,2.11.1)──────────────────────────────── + +/** 沙箱容器当前接着的 Docker 网络 */ +async function containerNetworks(containerId: string): Promise { + const { stdout } = await execFileAsync("docker", ["inspect", "-f", "{{json .NetworkSettings.Networks}}", containerId], { + timeout: 15_000, + }); + return Object.keys((JSON.parse(stdout.trim() || "null") as Record | null) ?? {}); +} + +/** 在容器里跑一条命令(docker exec);timeoutMs 或 signal 到了就杀掉本地的 docker exec 客户端 */ +function containerExec( + containerId: string, + command: string[], + opts: { input?: string; timeoutMs: number; signal?: AbortSignal; env?: string[] } +): Promise<{ code: number | null; stdout: string; killed: boolean }> { + return new Promise((resolve) => { + const proc = spawn( + "docker", + [ + "exec", + ...(opts.input !== undefined ? ["-i"] : []), + ...(opts.env ?? []).flatMap((kv) => ["-e", kv]), + containerId, + ...command, + ], + { stdio: [opts.input !== undefined ? "pipe" : "ignore", "pipe", "ignore"] } + ); + let stdout = ""; + proc.stdout!.on("data", (d: Buffer) => { + // 只要我们自己 select 出来的那一行;封顶,不让输出无限长 + if (stdout.length < 64 * 1024) stdout += d.toString(); + }); + let killed = false; + const kill = () => { + killed = true; + proc.kill("SIGKILL"); + }; + const timer = setTimeout(kill, opts.timeoutMs); + if (opts.signal?.aborted) kill(); + opts.signal?.addEventListener("abort", kill, { once: true }); + proc.on("error", () => {}); + proc.on("close", (code) => { + clearTimeout(timer); + opts.signal?.removeEventListener("abort", kill); + resolve({ code, stdout, killed }); + }); + if (opts.input !== undefined) { + proc.stdin!.on("error", () => {}); + proc.stdin!.end(opts.input); + } + }); +} + +/** 容器里用 psql 跑 SQL(默认走 unix socket,不经网络)。官方镜像对本地 socket 和 127.0.0.1 都是 trust */ +const PSQL = ["psql", "-X", "-q", "-tA", "-v", "ON_ERROR_STOP=1", "-U", "postgres", "-d", "postgres"]; + +/** 模拟注册在容器里的几样痕迹,都带同一个随机标记:取消标记文件、psql 的 pid 文件、会话的 application_name */ +function signupTraces(marker: string) { + if (!/^[0-9a-f]{16}$/.test(marker)) throw new Error("bad sign-up marker"); + return { + cancelFile: `/tmp/backupdrill-signup-${marker}.cancel`, + pidFile: `/tmp/backupdrill-signup-${marker}.pid`, + appName: `backupdrill-signup-${marker}`, + }; +} + +/** + * 模拟注册本地那一侧(docker exec 客户端)最多等多久;导出供测试调短,产品里不改。 + * launchPauseSeconds 只给测试用:在启动脚本"看过取消标记"和"exec psql"之间停一会儿,复现最坏的时序 + */ +export const OFFLINE_SIGNUP_LIMITS = { psqlMs: 6 * 60 * 1000, launchPauseSeconds: 0 }; + +/** + * 容器里启动模拟注册的脚本。和 stopSignup 的约定:**先占位、再看取消**。 + * - 启动脚本先独占创建 pid 文件(set -C),写进自己的 pid,然后才看取消标记,有就退出; + * - stopSignup 先建取消标记,然后才看 pid 文件。 + * 所以 stopSignup 没看到 pid 文件,启动脚本之后一定会看到取消标记而退出;看到了,就按 pid 杀掉它—— + * 不管它还是 sh(停在 exec 之前)还是已经 exec 成了 psql,pid 都是同一个。 + * + * psql 经 127.0.0.1 连(断网后 loopback 还在):走 unix socket 时 inet_client_addr() 是 NULL, + * 真实注册经 TCP 进来,要客户端地址的触发器会被误判成坏的。官方镜像 loopback 是 trust; + * 万一不是,用容器自己的 POSTGRES_PASSWORD + */ +function signupLauncher(marker: string): string { + const { cancelFile, pidFile } = signupTraces(marker); + const pause = Math.max(0, Math.floor(OFFLINE_SIGNUP_LIMITS.launchPauseSeconds)); + return ( + `set -C; echo $$ > ${pidFile} || exit 99; [ -e ${cancelFile} ] && exit 99; ` + + (pause ? `sleep ${pause}; ` : "") + + `PGPASSWORD="$POSTGRES_PASSWORD" exec ${PSQL.join(" ")} -h 127.0.0.1` + ); +} + +/** + * 停掉一次没有正常结束的模拟注册,并等到它在容器里确实没了,到 deadline(时间戳)为止。本地的 docker exec 客户端被杀掉 + * (超时、叫停)时,容器里的那次启动照样在跑,甚至可能还没起来。按 signupLauncher 的约定: + * 1. 先建取消标记,再看 pid 文件:没有 pid 文件 = 它以后也不会启动;有 = 那个进程(sh 或 psql)还活着就杀掉; + * 2. 终止它的会话(按 application_name,或者语句里带着这次的随机标记——触发器能改 application_name)。 + * 进程没了、会话也没了才算停下来。每条 docker 命令的时限也截在 deadline 之内,整体不会超过它 + */ +async function stopSignup(containerId: string, marker: string, deadline: number): Promise { + const { cancelFile, pidFile, appName } = signupTraces(marker); + // 输出 "alive":还有进程(刚杀掉,或者 pid 文件刚建、还没写进 pid),下一轮再看 + const killLauncher = + `touch ${cancelFile}; if [ -e ${pidFile} ]; then p=$(cat ${pidFile}); ` + + `if [ -z "$p" ]; then echo alive; ` + + `else c=$(cat /proc/$p/comm 2>/dev/null); if [ "$c" = sh ] || [ "$c" = psql ]; then kill -9 "$p"; echo alive; fi; fi; fi; true`; + const sessions = + `select count(pg_terminate_backend(pid)) from pg_stat_activity where pid <> pg_backend_pid() ` + + `and (application_name = '${appName}' or query like '%${marker}%')`; + const left = () => deadline - Date.now(); + while (left() > 0) { + const killed = await containerExec(containerId, ["sh", "-c", killLauncher], { timeoutMs: Math.max(1, left()) }); + if (killed.code !== 0 || left() <= 0) return false; + const sessionsLeft = await containerExec(containerId, [...PSQL, "-c", sessions], { timeoutMs: Math.max(1, left()) }); + if (sessionsLeft.code !== 0) return false; + if (killed.stdout.trim() === "" && sessionsLeft.stdout.trim() === "0") return true; + await new Promise((resolve) => setTimeout(resolve, Math.min(500, Math.max(0, left())))); + } + return false; +} + +/** 停掉模拟注册最多等多久(整体,从开始停算起) */ +const STOP_SIGNUP_MS = 15_000; + +/** + * 模拟注册用的"断网跑 SQL"(见 auth-drill.ts OfflineSandbox)。 + * + * 为什么是临时断网,而不是一开始就不给沙箱联网:CLI 和 pg_restore 都从主机经发布的端口连沙箱, + * --network none 和 --internal 网络都发布不了端口。所以恢复、校验照旧,只在最后的模拟注册之前把容器从所有 + * 网络上摘下来(只剩 loopback),经 docker exec 里的 psql 连 127.0.0.1 跑(见 signupLauncher)。 + * + * **断了就不再接回**:能确认的只有会话和那个 psql 都没了,确认不了触发器有没有留下别的东西(后台进程等), + * 一接回它们就又能连出去。所以模拟注册是这个沙箱上的最后一件事,跑完沙箱就销毁。--keep 要留下沙箱时 + * 根本不跑模拟注册(见 drillDump),留下的沙箱和 2.11.0 一样连得上。 + * 每一步之前都看一眼是否已被叫停:叫停后(报告可能已经出了)不再断开任何网络。摘不干净就不跑。 + */ +/** @internal 演练内部用;导出只为测试能直接对一个容器验证断网、叫停和超时收尾 */ +export function offlineSandbox(pg: { containerId: string; offline: boolean }): OfflineSandbox { + let running: string | null = null; + // 同一次注册的收尾只做一次:本地超时、叫停、演练那边的 stopOfflineSessions 谁先来谁启动,其余的等同一个结果 + const stopping = new Map>(); + const stopOnce = (marker: string) => { + let p = stopping.get(marker); + if (!p) stopping.set(marker, (p = stopSignup(pg.containerId, marker, Date.now() + STOP_SIGNUP_MS))); + return p; + }; + return { + offline: () => pg.offline, + async stopOfflineSessions() { + if (running) await stopOnce(running); + }, + async runOffline(script, marker, signal) { + const { appName } = signupTraces(marker); + const stopped = () => { + if (signal?.aborted) throw new Error("stopped"); + }; + stopped(); + const networks = await containerNetworks(pg.containerId); + for (const network of networks) { + stopped(); + await execFileAsync("docker", ["network", "disconnect", network, pg.containerId], { timeout: 30_000 }); + // 只记确认过的状态:这一个网络已经摘掉了,之后不会再接回 + pg.offline = true; + } + const left = await containerNetworks(pg.containerId); + if (left.length) throw new Error(`the sandbox is still on ${left.join(", ")}`); + pg.offline = true; + stopped(); + running = marker; + const result = await containerExec( + pg.containerId, + ["sh", "-c", signupLauncher(marker)], + { input: script, timeoutMs: OFFLINE_SIGNUP_LIMITS.psqlMs, signal, env: [`PGAPPNAME=${appName}`] } + ); + // 本地超时或被叫停:容器里的那次模拟注册可能还在跑,先确实停掉它,再交出结果(之后沙箱才会被销毁) + if (result.killed || signal?.aborted) { + // 超时收尾时演练可能正同时销毁沙箱:容器已经停了(或没了),里面的注册也就跟着没了,不必提示 + const stillThere = () => + execFileAsync("docker", ["inspect", "-f", "{{.State.Running}}", pg.containerId], { timeout: 10_000 }).then( + (r) => r.stdout.trim() === "true", + () => false + ); + if (!(await stopOnce(marker)) && (await stillThere())) { + log.warn("Couldn't confirm the stopped test sign-up ended inside the drill sandbox; it stays off the network until it is removed."); + } + } + return { code: result.killed ? null : result.code, stdout: result.stdout }; + }, + }; +} + +/** --keep 留下的沙箱:和 2.11.0 一样给连接串(留沙箱时不跑模拟注册,它一直连得上),另给一条进容器的命令 */ +function keptSandboxInfo(pg: Ephemeral): NonNullable { + return { containerId: pg.containerId, connString: pg.connString, inspect: `docker exec -it ${pg.containerId.slice(0, 12)} psql -U postgres` }; +} + // installExtensions 已上移到统一引擎(restore-engine.ts):沙箱与真实恢复共用, // 唯一差异是调用方对"装不上"的裁决——沙箱记录后继续,真实目标阻断。 @@ -920,6 +1121,10 @@ export async function drillDump( // 托管 worker 在这一步前后换磁盘守卫的规则:Auth 阶段吃紧只叫停这一节,不判演练失败 begin: opts.supervision ? () => opts.supervision!.observe({ phase: "auth" }) : undefined, stop: opts.supervision?.authStop, + sandbox: offlineSandbox(pg), + // --keep 要留下这个沙箱时不跑模拟注册:断了网就不能再接回,留下的沙箱就连不上了(脚本靠 keptSandbox.connString)。 + // 结论(pass)这时已经定了,只有真的会留沙箱(演练没通过)才跳过 + skipSignup: opts.keepSandboxOnFailure && !pass ? "--keep leaves the sandbox connected so you can inspect it" : undefined, }); if (authSection) { report.auth = authSection; @@ -929,7 +1134,7 @@ export async function drillDump( } if (opts.keepSandboxOnFailure && !pass) { // 写进报告让 --keep 可被脚本消费(拿连接串排查),不只靠人眼看日志 - report.keptSandbox = { containerId: pg.containerId, connString: pg.connString }; + report.keptSandbox = keptSandboxInfo(pg); } return report; } catch (error) { diff --git a/src/recovery-doc.ts b/src/recovery-doc.ts index 6c1d604..af3944b 100644 --- a/src/recovery-doc.ts +++ b/src/recovery-doc.ts @@ -11,6 +11,19 @@ import { recoveryGrantsSql } from "./grants.js"; import { plainSchemaName, restorableAuthObjects } from "./auth-backup.js"; import { authRestoreNotes, CLEAR_PENDING_AUTH_SQL } from "./auth-restore.js"; +/** + * 原样写进 RECOVERY.md 的一段文字(例如 Auth 失败的原因,里面有从系统目录读来的约束名、索引名):放进代码段里, + * Markdown 不再解释里面的任何东西(链接、强调、HTML,GFM 也不会把裸网址自动变成链接)。按 CommonMark 的规则, + * 包住它的反引号要比里面最长的一串反引号多一个;两边各加一个空格,文字本身以反引号或空格开头结尾也不受影响。 + * 控制字符换成可见的转义,名字里的换行不会让这一段断开 + */ +export function markdownCode(text: string): string { + const visible = text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`); + const longestRun = Math.max(0, ...[...visible.matchAll(/`+/g)].map((m) => m[0].length)); + const fence = "`".repeat(longestRun + 1); + return `${fence} ${visible} ${fence}`; +} + /** 生成手册所需的非秘密快照坐标。刻意不收连接串/密钥类型——签名即防线。 */ export interface RecoveryDocContext { snapshot: string; // 快照时间戳目录名 @@ -75,7 +88,7 @@ export function authRecoveryText(manifest: Manifest, place: RecoveryDocPlace): A (pg_dump custom format, ${mb(auth.dump!.bytes)} MB, sha256 \`${auth.dump!.sha256}\`) — ${auth.rows!.users.toLocaleString("en-US")} users, ${auth.rows!.identities.toLocaleString("en-US")} sign-in identities ` : manifest.auth - ? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? manifest.auth.reason ?? "not captured"}) + ? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? markdownCode(manifest.auth.reason ?? "not captured")}) ` : ""; // 空目标检查用的 schema 列表(SQL 字符串字面量,单引号按 SQL 规则加倍) diff --git a/test/auth-archive.test.js b/test/auth-archive.test.js new file mode 100644 index 0000000..310bd41 --- /dev/null +++ b/test/auth-archive.test.js @@ -0,0 +1,253 @@ +// auth.dump 上传前抹掉待处理 token(2.11.1)。这里拼出和 pg_dump 管道输出同形的 custom 格式归档 +// (不同的归档版本、压缩与不压缩),过一遍改写,再用真的 pg_restore 读回来:不需要数据库,也不需要 Docker。 +// 真实 pg_dump 输出的端到端检查在 auth-backup / auth-restore / auth-drill 的测试里。 +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Readable } from "node:stream"; +import { promisify } from "node:util"; +import { createDeflate, deflateSync } from "node:zlib"; +import { PENDING_AUTH_COPY_VALUES, copyColumns, scrubPendingAuthTokens } from "../dist/auth-archive.js"; +import { CLEAR_PENDING_AUTH_SQL } from "../dist/auth-restore.js"; + +const x = promisify(execFile); +const pgRestore = process.env.BACKUPDRILL_PG_RESTORE || "pg_restore"; +const pgRestoreVersion = await x(pgRestore, ["--version"]).then((r) => r.stdout, () => null); +const pgRestoreMajor = pgRestoreVersion ? Number(/(\d+)(?:\.\d+)?/.exec(pgRestoreVersion)?.[1]) : null; +// 每个归档版本最早能读它的 pg_restore(pg_backup_archiver.h:1.14 = 12,1.15 = 16,1.16 = 17;1.12 早于 10) +const READABLE_FROM = { 12: 10, 14: 12, 15: 16, 16: 17 }; +/** 本机 pg_restore 读不了这个版本的归档时跳过,并说清楚原因 */ +const needsPgRestoreFor = (minor) => + pgRestoreMajor === null + ? "requires pg_restore" + : pgRestoreMajor < READABLE_FROM[minor] + ? `pg_restore ${pgRestoreMajor} can't read archive version 1.${minor} (needs ${READABLE_FROM[minor]} or newer)` + : false; + +const USER_COLUMNS = [ + "id", "email", "encrypted_password", "raw_user_meta_data", "confirmation_token", "recovery_token", + "email_change_token_new", "email_change_token_current", "phone_change_token", "reauthentication_token", + "email_change", "phone_change", "email_change_confirm_status", "confirmation_sent_at", "recovery_sent_at", + "email_change_sent_at", "phone_change_sent_at", "reauthentication_sent_at", "Odd \"name\", here", +]; + +function userRow(i) { + return [ + `00000000-0000-4000-8000-${String(i).padStart(12, "0")}`, `u${i}@example.test`, "$2a$10$hash", + // 数据里的制表符、换行、反斜杠在 COPY 文本里都是转义过的 + `{"name": "tab\\\\there\\\\nnew ü 中"}`, `conf-${i}`, `reset-${i}`, `new-${i}`, `cur-${i}`, `phone-${i}`, `reauth-${i}`, + `next${i}@example.test`, "+15550000", "1", "2020-01-01 00:00:00+00", "2020-01-02 00:00:00+00", + "2020-01-03 00:00:00+00", "\\N", "2020-01-05 00:00:00+00", "x\\ty", + ].join("\t"); +} + +const SCRUBBED_EXPECT = new Map(PENDING_AUTH_COPY_VALUES); + +/** 拼一份 custom 格式归档:auth.users、auth.identities 两张表的结构和数据,offset 一律"未记录"(管道输出就是这样) */ +function buildArchive({ + minor = 16, compression = "gzip", users = 3, chunkSize = 1000, offsetFlag = 1, identitiesBlock = true, usersPayload = null, +} = {}) { + const intSize = 4; + const parts = []; + const byte = (b) => parts.push(Buffer.from([b])); + const int = (v) => { + const b = Buffer.alloc(1 + intSize); + b[0] = v < 0 ? 1 : 0; + b.writeUInt32LE(Math.abs(v), 1); + parts.push(b); + }; + const str = (s) => { + if (s === null) return int(-1); + const b = Buffer.from(s, "utf8"); + int(b.length); + parts.push(b); + }; + parts.push(Buffer.from("PGDMP")); + byte(1), byte(minor), byte(0), byte(intSize), byte(8), byte(1); + if (minor >= 15) byte(compression === "gzip" ? 1 : 0); + else int(compression === "gzip" ? -1 : 0); + for (const v of [0, 0, 0, 1, 0, 125, 0]) int(v); + str("postgres"), str("17.0"), str("17.0"); + const quote = (c) => (/^[a-z_][a-z0-9_]*$/.test(c) ? c : `"${c.replace(/"/g, '""')}"`); + const entries = [ + { id: 1, tag: "auth", desc: "SCHEMA", section: 2, defn: "CREATE SCHEMA auth;\n", ns: null }, + { + id: 2, tag: "users", desc: "TABLE", section: 2, ns: "auth", + defn: `CREATE TABLE auth.users (\n${USER_COLUMNS.map((c) => ` ${quote(c)} text`).join(",\n")}\n);\n`, + }, + { id: 3, tag: "identities", desc: "TABLE", section: 2, ns: "auth", defn: "CREATE TABLE auth.identities (\n user_id text,\n provider text\n);\n" }, + { id: 4, tag: "users", desc: "TABLE DATA", section: 3, ns: "auth", dumper: 1, deps: ["2"], + copy: `COPY auth.users (${USER_COLUMNS.map(quote).join(", ")}) FROM stdin;\n` }, + { id: 5, tag: "identities", desc: "TABLE DATA", section: 3, ns: "auth", dumper: 1, deps: ["3"], + copy: "COPY auth.identities (user_id, provider) FROM stdin;\n" }, + ]; + int(entries.length); + for (const e of entries) { + int(e.id), int(e.dumper ?? 0), str("0"), str("0"), str(e.tag), str(e.desc), int(e.section); + str(e.defn ?? ""), str(""), str(e.copy ?? ""), str(e.ns), str(""); + if (minor >= 14) str("heap"); + if (minor >= 16) int(114); + str("postgres"), str("false"); + for (const d of e.deps ?? []) str(d); + str(null); + byte(e.dumper ? offsetFlag : 3); + parts.push(Buffer.alloc(8)); + } + const dataBlock = (id, text, ready = null) => { + byte(1), int(id); + const payload = ready ?? (compression === "gzip" ? deflateSync(Buffer.from(text)) : Buffer.from(text)); + // 和 pg_dump 一样分成若干块;块边界会落在行中间 + for (let at = 0; at < payload.length; at += chunkSize) { + const piece = payload.subarray(at, at + chunkSize); + int(piece.length); + parts.push(piece); + } + int(0); + }; + const rows = Array.from({ length: users }, (_, i) => userRow(i + 1)); + dataBlock(4, rows.map((r) => `${r}\n`).join("") + "\\.\n\n\n", usersPayload); + if (identitiesBlock) dataBlock(5, Array.from({ length: users }, (_, i) => `u${i}\temail\n`).join("") + "\\.\n\n\n"); + return Buffer.concat(parts); +} + +async function scrub(buffer, pieceSize = 7) { + // 输入切成很小的碎片:整数、字符串、数据块的边界都会被切开 + const pieces = []; + for (let at = 0; at < buffer.length; at += pieceSize) pieces.push(buffer.subarray(at, at + pieceSize)); + const chunks = []; + for await (const chunk of scrubPendingAuthTokens(Readable.from(pieces))) chunks.push(chunk); + return Buffer.concat(chunks); +} + +/** pg_restore 读回 COPY 数据:列名 → 每行的值 */ +async function restoredUsers(archive) { + const dir = mkdtempSync(join(tmpdir(), "bd-scrub-")); + try { + const path = join(dir, "auth.dump"); + writeFileSync(path, archive); + const { stdout } = await x(pgRestore, ["--data-only", "-t", "users", "-f", "-", path], { maxBuffer: 64 * 1024 * 1024 }); + const lines = stdout.split("\n"); + const start = lines.findIndex((l) => l.startsWith("COPY auth.users ")); + const rows = []; + for (let i = start + 1; lines[i] !== "\\."; i++) rows.push(lines[i].split("\t")); + return rows; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +test("copyColumns reads quoted and plain column names", () => { + assert.deepEqual(copyColumns('COPY auth.users (id, "Odd ""name"", here", email) FROM stdin;\n'), ["id", 'Odd "name", here', "email"]); + assert.throws(() => copyColumns("COPY auth.users FROM stdin;"), /expected form/); +}); + +test("the columns blanked in the archive are exactly the ones the restore clears, with the same values", () => { + const assignments = new Map( + CLEAR_PENDING_AUTH_SQL.replace(/^update auth\.users set /, "").replace(/;$/, "").split(", ").map((a) => a.split(" = ")) + ); + const asCopy = (sqlValue) => (sqlValue === "null" ? "\\N" : sqlValue === "''" ? "" : sqlValue); + assert.deepEqual( + [...assignments].map(([column, value]) => [column, asCopy(value)]), + PENDING_AUTH_COPY_VALUES.map(([column, value]) => [column, value]) + ); +}); + +for (const [minor, compression] of [[16, "gzip"], [16, "none"], [15, "gzip"], [14, "gzip"], [14, "none"], [12, "gzip"]]) { + test(`archive 1.${minor} (${compression}): pending tokens are blanked, everything else reads back the same`, { skip: needsPgRestoreFor(minor) }, async () => { + const original = buildArchive({ minor, compression, users: 500 }); + const scrubbed = await scrub(original); + const before = await restoredUsers(original); + const after = await restoredUsers(scrubbed); + assert.equal(after.length, 500); + for (let r = 0; r < before.length; r++) { + USER_COLUMNS.forEach((column, c) => { + const expected = SCRUBBED_EXPECT.has(column) ? SCRUBBED_EXPECT.get(column) : before[r][c]; + assert.equal(after[r][c], expected, `row ${r} column ${column}`); + }); + } + // 目录和另一张表逐字节不变:auth.identities 的数据照抄 + const dir = mkdtempSync(join(tmpdir(), "bd-scrub-")); + try { + writeFileSync(join(dir, "a"), original); + writeFileSync(join(dir, "b"), scrubbed); + const list = async (f) => (await x(pgRestore, ["-l", join(dir, f)])).stdout.split("\n").filter((l) => !l.startsWith(";")).join("\n"); + assert.equal(await list("b"), await list("a")); + // pg_restore 17.6 起每次输出一个随机的 \restrict 口令,比较前去掉 + const identities = async (f) => + (await x(pgRestore, ["--data-only", "-t", "identities", "-f", "-", join(dir, f)])).stdout.replace(/^\\(un)?restrict .*$/gm, ""); + assert.equal(await identities("b"), await identities("a")); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + assert.ok(!scrubbed.includes("reset-1") && !(compression === "none" && scrubbed.includes("next1@"))); + }); +} + +test("a truncated archive, recorded data offsets or a row that doesn't match the columns are errors, never a silent pass", async () => { + const good = buildArchive({ compression: "none" }); + await assert.rejects(scrub(good.subarray(0, good.length - 20)), /ended early/); + await assert.rejects(scrub(buildArchive({ offsetFlag: 2 })), /data offsets/); + await assert.rejects(scrub(Buffer.from("PGDMX-not-an-archive")), /isn't a pg_dump custom-format archive/); + // 一行少了一个字段(把最后一个制表符换成空格,长度不变,块长度仍然对) + const sameLength = Buffer.from(good.toString("latin1").replace("\tx\\ty\n", " x\\ty\n"), "latin1"); + assert.equal(sameLength.length, good.length); + await assert.rejects(scrub(sameLength), /fields, but the COPY statement lists/); + // 归档版本比认得的新:不猜 + const newer = Buffer.from(good); + newer[6] = 17; + await assert.rejects(scrub(newer), /archive version 1\.17/); +}); + +test("an empty auth.users and a gzip archive split into one-byte pieces still come out readable", { skip: needsPgRestoreFor(16) }, async () => { + const empty = await scrub(buildArchive({ users: 0 }), 1); + assert.deepEqual(await restoredUsers(empty), []); + const tiny = await scrub(buildArchive({ users: 20, chunkSize: 3 }), 1); + assert.equal((await restoredUsers(tiny)).length, 20); +}); + +test("an archive whose TOC declares data that never comes (auth.identities cut off) is an error, not an upload", async () => { + await assert.rejects(scrub(buildArchive({ identitiesBlock: false })), /ended before all of its data blocks/); +}); + +test("one huge, highly compressible row streams through in bounded memory and linear time", async () => { + // 一行 256 MiB 的 metadata,压缩后只有几百 KB:整行缓冲的写法会在这里吃掉几百 MB 内存、反复拷贝 + const fieldMiB = 256; + const deflate = createDeflate(); + const compressed = []; + deflate.on("data", (c) => compressed.push(c)); + const done = new Promise((resolve) => deflate.on("end", resolve)); + const fields = userRow(1).split("\t"); + const metadataAt = USER_COLUMNS.indexOf("raw_user_meta_data"); + deflate.write(Buffer.from(fields.slice(0, metadataAt).join("\t") + "\t")); + const block = Buffer.alloc(1024 * 1024, "a"); + for (let i = 0; i < fieldMiB; i++) deflate.write(block); + deflate.end(Buffer.from("\t" + fields.slice(metadataAt + 1).join("\t") + "\n\\.\n")); + await done; + const archive = buildArchive({ users: 1, usersPayload: Buffer.concat(compressed), chunkSize: 16 * 1024 }); + const before = process.memoryUsage(); + let peakArrayBuffers = 0; + let bytes = 0; + const started = Date.now(); + for await (const chunk of scrubPendingAuthTokens(Readable.from([archive]))) { + bytes += chunk.length; + peakArrayBuffers = Math.max(peakArrayBuffers, process.memoryUsage().arrayBuffers - before.arrayBuffers); + } + assert.ok(bytes > 0); + assert.ok(peakArrayBuffers < 64 * 1024 * 1024, `buffered ${Math.round(peakArrayBuffers / 1024 / 1024)} MiB for a ${fieldMiB} MiB row`); + assert.ok(Date.now() - started < 30_000, `took ${Date.now() - started} ms`); +}); + +test("the auth.users data must end with pg_dump's end marker, followed by nothing but blank lines", async () => { + const rows = [userRow(1), userRow(2)].map((r) => `${r}\n`).join(""); + const archiveWith = (text) => buildArchive({ compression: "none", users: 2, usersPayload: Buffer.from(text) }); + // 和 pg_dump 一样:结束标记后跟空行 + await scrub(archiveWith(`${rows}\\.\n\n\n`)); + // 没有结束标记 + await assert.rejects(scrub(archiveWith(rows)), /no end marker/); + // 结束标记之后还有别的字节(多一行数据,或者垃圾) + await assert.rejects(scrub(archiveWith(`${rows}\\.\n${userRow(3)}\n`)), /something after its end marker/); + await assert.rejects(scrub(archiveWith(`${rows}\\.\n\nx`)), /something after its end marker/); +}); diff --git a/test/auth-backup.test.js b/test/auth-backup.test.js index 1a25f22..29718fc 100644 --- a/test/auth-backup.test.js +++ b/test/auth-backup.test.js @@ -12,9 +12,9 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import pg from "pg"; import { runBackup, mainDumpArgs, AUTH_TIMEOUTS } from "../dist/backup.js"; -import { schemasMayIncludeAuth, restorableAuthObjects, manualAuthObjects, redactValues } from "../dist/auth-backup.js"; +import { schemasMayIncludeAuth, restorableAuthObjects, manualAuthObjects, redactValues, quotedName } from "../dist/auth-backup.js"; import { parseManifest } from "../dist/manifest.js"; -import { authRecoveryText, renderRecoveryDoc } from "../dist/recovery-doc.js"; +import { authRecoveryText, markdownCode, renderRecoveryDoc } from "../dist/recovery-doc.js"; import { AUTH_DDL, SETUP, sql, startPostgres } from "./auth-fixtures.js"; const x = promisify(execFile); @@ -97,6 +97,19 @@ test("RECOVERY.md never puts an object name into a shell command unless it is a assert.match(doc, /backupdrill restore --finish --confirm-target /); }); +test("names from the catalog are shown safely: control characters escaped, Markdown never interpreted", () => { + assert.equal(quotedName("plain"), '"plain"'); + assert.equal(quotedName('a"b\\c'), '"a\\"b\\\\c"'); + assert.equal(quotedName("x\ny\rz\tw\u0007\u009b\u2028"), '"x\\ny\\rz\\tw\\u0007\\u009b\\u2028"'); + // RECOVERY.md 里放进代码段:包住它的反引号比里面最长的一串多一个,两边各留一个空格 + const reason = `has ${quotedName("evil\n[click](https://example.com) *x* `code` ``x``")}`; + const shown = markdownCode(reason); + assert.equal(shown, `\`\`\` ${reason} \`\`\``); + assert.equal(shown.includes("\n"), false); + assert.equal(markdownCode("plain https://example.com"), "` plain https://example.com `"); + assert.equal(markdownCode("bell\u0007"), "` bell\\u0007 `"); +}); + test("redactValues: values that may be user data go, identifiers stay", () => { assert.equal( redactValues('ERROR: invalid input syntax for type uuid: "bob@example.com"'), @@ -186,7 +199,10 @@ for a in "$@"; do done echo "$args" >> "${log}" case "$args" in - *--table=auth.users*) if [ -n "$BD_TEST_FAIL_AUTH" ]; then echo "pg_dump: error: injected auth failure" >&2; exit 1; fi ;; + *--table=auth.users*) + if [ -n "$BD_TEST_FAIL_AUTH" ]; then echo "pg_dump: error: injected auth failure" >&2; exit 1; fi + # 0 退出却只写出半份归档 + if [ -n "$BD_TEST_MALFORMED_AUTH" ]; then "${realPgDump}" "$@" | head -c 300; exit 0; fi ;; *--snapshot=*--schema=*) if [ -n "$BD_TEST_FAIL_MAIN_SNAPSHOT" ]; then echo "pg_dump: error: query failed: ERROR: invalid snapshot identifier" >&2; exit 1; fi ;; esac case "$args" in @@ -330,6 +346,17 @@ test( assert.match(listing, /TABLE DATA auth identities/); assert.match(listing, /TRIGGER auth users on_auth_user_created/); assert.match(listing, /POLICY auth users self_read/); + // 2.11.1 起:待处理的找回密码 token 和发送时间不进桶(源库里 pw@ 那个用户有一个没用掉的) + const usersData = ( + await x(process.env.BACKUPDRILL_PG_RESTORE || "pg_restore", ["--data-only", "-t", "users", "-f", "-", archive]) + ).stdout.split("\n"); + const header = usersData.find((l) => l.startsWith("COPY auth.users ")); + const columns = header.slice(header.indexOf("(") + 1, header.indexOf(")")).split(", "); + const row = usersData.map((l) => l.split("\t")).find((f) => f[columns.indexOf("id")] === "11111111-1111-1111-1111-111111111111"); + assert.equal(row[columns.indexOf("recovery_token")], ""); + assert.equal(row[columns.indexOf("recovery_sent_at")], "\\N"); + assert.equal(row[columns.indexOf("email")], "pw@example.test", "everything else is still there"); + assert.ok(!r.files.get("auth.dump").includes("pending-reset")); // 主 dump 不受影响:就是一份正常的 public 备份 assert.ok(r.files.get("dump.pgcustom").length > 0); assert.equal(r.manifest.dump.bytes, r.files.get("dump.pgcustom").length); @@ -470,6 +497,128 @@ test( assert.equal(r.files.has("auth.dump"), false); }); + await t.test("pg_dump exits 0 but writes a broken Auth archive: no auth.dump, Auth failed, database backed up", async () => { + const r = await run("auth-malformed", { databaseUrl: okUrl, auth: "default" }, { env: { BD_TEST_MALFORMED_AUTH: "1" } }); + assert.equal(r.manifest.auth.status, "failed"); + assert.match(r.manifest.auth.reason, /^Auth archive not written: the archive ended early/); + assert.equal(r.files.has("auth.dump"), false); + assert.ok(r.files.get("dump.pgcustom").length > 0); + assert.equal(r.manifest.dump.bytes, r.files.get("dump.pgcustom").length); + }); + + await t.test("anything on auth.users beyond Supabase's own: no auth.dump, Auth failed naming it, database backed up", async () => { + const reasonFor = (what) => `BackupDrill stopped before writing auth.dump. Clearing pending Auth tokens could cause a restore to fail because of ${what} on auth.users.`; + const expectRefused = async (name, what) => { + const r = await run(name, { databaseUrl: okUrl, auth: "default" }); + assert.equal(r.manifest.auth.status, "failed", JSON.stringify(r.manifest.auth)); + assert.equal(r.manifest.auth.reason, reasonFor(what)); + assert.equal(r.files.has("auth.dump"), false); + assert.ok(r.files.get("dump.pgcustom").length > 0); + assert.equal(r.manifest.dump.bytes, r.files.get("dump.pgcustom").length); + return r; + }; + // 每个用户都有 recovery_token,下面这些约束和索引才建得出来;抹成 '' 之后它们可能不接受 + await sql(admin, "update auth.users set recovery_token = 'r-' || id where recovery_token = ''"); + const cases = [ + ["custom-check", "alter table auth.users add constraint recovery_token_set check (recovery_token <> '')", + 'a custom check constraint "recovery_token_set"', "alter table auth.users drop constraint recovery_token_set"], + // 约束里调用了用户函数:备份只读系统目录里的定义,绝不在源库上执行它。函数一旦被调用就抛错, + // 那样这里就会变成"检查 Auth 表失败",而不是点名这条约束 + ["function-check", `create function public.never_call_me(t text) returns boolean language plpgsql as $$ + begin raise exception 'called on the source database'; end $$; + alter table auth.users add constraint token_checked_by_function check (public.never_call_me(recovery_token)) not valid`, + 'a custom check constraint "token_checked_by_function"', + "alter table auth.users drop constraint token_checked_by_function; drop function public.never_call_me(text)"], + // 被抹成 NULL 的发送时间列是 NOT NULL + ["not-null", `update auth.users set reauthentication_sent_at = now() where reauthentication_sent_at is null; + alter table auth.users alter column reauthentication_sent_at set not null`, + 'a NOT NULL column "reauthentication_sent_at"', + "alter table auth.users alter column reauthentication_sent_at drop not null; update auth.users set reauthentication_sent_at = null"], + // token 列上不带条件的唯一索引:抹过之后所有行都是 '',撞在一起 + ["unique", "create unique index recovery_token_unique on auth.users (recovery_token)", + 'a custom unique index "recovery_token_unique"', "drop index auth.recovery_token_unique"], + // 从 token 算出来的生成列,再在生成列上加 CHECK(约束本身不提 token 列) + ["generated", `alter table auth.users add column token_length int generated always as (length(recovery_token)) stored; + alter table auth.users add constraint token_length_positive check (token_length > 0)`, + 'a custom generated column "token_length"', "alter table auth.users drop column token_length"], + // 表达式上的排他约束(conkey 是 {0},按它背后索引的表达式树认出用到了 recovery_token) + ["exclusion", "alter table auth.users add constraint token_exclusive exclude using btree (lower(recovery_token) with =)", + 'a custom exclusion constraint "token_exclusive"', "alter table auth.users drop constraint token_exclusive"], + // token 上的表达式唯一索引 + ["expression-unique", "create unique index token_lower_unique on auth.users (lower(recovery_token))", + 'a custom unique index "token_lower_unique"', "drop index auth.token_lower_unique"], + // 普通索引,但表达式会在恢复重建时算:抹成 '' 之后 1 / length(recovery_token) 除零 + ["expression-index", "create index token_ratio on auth.users ((1 / length(recovery_token)))", + 'a custom index "token_ratio"', "drop index auth.token_ratio"], + ]; + try { + for (const [name, add, what, drop] of cases) { + await sql(admin, add); + try { + await expectRefused(`scrub-${name}`, what); + } finally { + await sql(admin, drop); + } + } + // 名字里带换行和 Markdown 链接:日志、manifest 里转义成可见的文字,RECOVERY.md 里不会变成链接或多出一行 + const evil = 'evil\n[click](https://example.com)'; + await sql(admin, `alter table auth.users add constraint "${evil.replace(/"/g, '""')}" check (recovery_token is not null)`); + try { + const r = await expectRefused("scrub-evil-name", 'a custom check constraint "evil\\n[click](https://example.com)"'); + assert.equal(r.manifest.auth.reason.includes("\n"), false, "no raw newline in the reason"); + const doc = renderRecoveryDoc(r.manifest, { snapshot: "s", bucket: "b", prefix: "p", projectName: "p" }); + const line = doc.split("\n").find((l) => l.startsWith("- **Supabase Auth users**: not in this snapshot")); + assert.ok(line, doc); + // 整段原因在代码段里:名字里的链接和裸网址都只是文字 + assert.ok(line.includes(`(\` ${r.manifest.auth.reason} \`)`), line); + assert.ok(r.manifest.auth.reason.includes("https://example.com")); + } finally { + await sql(admin, `alter table auth.users drop constraint "${evil.replace(/"/g, '""')}"`); + } + } finally { + await sql(admin, "update auth.users set recovery_token = '' where recovery_token like 'r-%'"); + } + // 都去掉之后照常:Supabase 自带的那些(fixture 里有)不挡 + const ok = await run("scrub-stock", { databaseUrl: okUrl, auth: "default" }); + assert.equal(ok.manifest.auth.status, "included", JSON.stringify(ok.manifest.auth)); + + // 比对不受角色级设置影响:quote_all_identifiers 会给名字加引号,search_path 决定名字前带不带 schema + await sql(admin, "alter role reader_ok set quote_all_identifiers = on; alter role reader_ok set search_path = auth, public"); + try { + const quoted = await run("scrub-quoted", { databaseUrl: okUrl, auth: "default" }); + assert.equal(quoted.manifest.auth.status, "included", JSON.stringify(quoted.manifest.auth)); + } finally { + await sql(admin, "alter role reader_ok reset quote_all_identifiers; alter role reader_ok reset search_path"); + } + + // CONCURRENTLY 建失败留下的无效索引 pg_dump 不导出,也就不挡(这里有重复的 '',唯一索引一定建不成) + await assert.rejects(sql(admin, "create unique index concurrently token_left_invalid on auth.users (recovery_token)")); + try { + const invalid = await sql(admin, "select indisvalid from pg_index where indexrelid = 'auth.token_left_invalid'::regclass"); + assert.equal(invalid.rows[0].indisvalid, false); + const r = await run("scrub-invalid-index", { databaseUrl: okUrl, auth: "default" }); + assert.equal(r.manifest.auth.status, "included", JSON.stringify(r.manifest.auth)); + } finally { + await sql(admin, "drop index if exists auth.token_left_invalid"); + } + + // 碰不到被抹的列的,不在白名单上也放过:和 token 无关的改动、GoTrue 以后新加的索引不能让 Auth 备份停掉 + await sql(admin, ` + alter table auth.users add constraint users_email_key unique (email); + alter table auth.users add column extra text unique; + create unique index users_lower_email on auth.users (lower(email)); + create table public.instances (id uuid primary key); + alter table auth.users add constraint users_instance_fk foreign key (instance_id) references public.instances (id);`); + try { + const unrelated = await run("scrub-unrelated", { databaseUrl: okUrl, auth: "default" }); + assert.equal(unrelated.manifest.auth.status, "included", JSON.stringify(unrelated.manifest.auth)); + assert.ok(unrelated.files.get("auth.dump").length > 0); + } finally { + await sql(admin, `alter table auth.users drop constraint users_instance_fk, drop constraint users_email_key, drop column extra; + drop index auth.users_lower_email; drop table public.instances`); + } + }); + await t.test("the main dump can't import the snapshot: it is redone the old way, Auth marked unavailable", async () => { const r = await run("snap-fails", { databaseUrl: okUrl, auth: "default" }, { env: { BD_TEST_FAIL_MAIN_SNAPSHOT: "1" } }); assert.deepEqual(r.manifest.auth, { status: "skipped", reason: "snapshot_unavailable" }); diff --git a/test/auth-drill.test.js b/test/auth-drill.test.js index b28163a..d60bcb8 100644 --- a/test/auth-drill.test.js +++ b/test/auth-drill.test.js @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { runBackup } from "../dist/backup.js"; -import { runDrill } from "../dist/drill.js"; +import { OFFLINE_SIGNUP_LIMITS, offlineSandbox, runDrill } from "../dist/drill.js"; import { AUTH_DRILL_LIMITS, authDrillSection } from "../dist/auth-drill.js"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; @@ -377,6 +377,198 @@ id" uuid references auth.users (id) on delete set null)`); } }); + await t.test("the test sign-up runs with the sandbox off the network: a dblink trigger can't write anywhere else", async () => { + // "别的系统"就用源库本身:沙箱平时在默认网桥上,按容器 IP 连得到它 + const sourceIp = ( + await x("docker", ["inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", ids[0]]) + ).stdout.trim(); + assert.match(sourceIp, /^\d+\.\d+\.\d+\.\d+$/); + const dblinkCall = `public.dblink_exec('host=${sourceIp} port=5432 user=postgres password=pw dbname=postgres connect_timeout=5', 'insert into public.leaks default values')`; + await sql(admin, ` + create extension dblink; + create table public.leaks (at timestamptz not null default now()); + create function public.tell_crm() returns trigger language plpgsql security definer set search_path = '' as $$ + begin + perform ${dblinkCall}; + return new; + end $$; + create trigger tell_crm after insert on auth.users for each row execute function public.tell_crm();`); + try { + const mem = await backup("default"); + // 对照:同一个沙箱在线时(--check-cmd 在模拟注册之前跑),同一句 dblink 调用确实写得进源库。 + // 证明这个测试里"别的系统"是连得到的,下面的 0 才有意义 + const control = `psql "$BACKUPDRILL_SANDBOX_URL" -X -q -v ON_ERROR_STOP=1 -c "select ${dblinkCall.replace(/"/g, '\\"')}"`; + const report = await runDrill(config, { store: mem.store, appCheckCommand: control }); + assert.equal(report.pass, true, JSON.stringify(report.checks)); + assert.equal(report.checks.find((c) => c.name === "app checks")?.pass, true, "the online control call ran"); + assert.ok(report.auth.triggers.created.includes("tell_crm"), JSON.stringify(report.auth)); + assert.equal(report.auth.signup.ran, false, JSON.stringify(report.auth.signup)); + assert.match(report.auth.signup.detail, /^a database operation failed to connect while the sandbox was offline \(SQLSTATE /); + const leaks = await sql(admin, "select count(*)::int as n from public.leaks"); + assert.equal(leaks.rows[0].n, 1, "only the online control wrote a row; the offline test sign-up wrote nothing"); + + // dblink 照样装着,触发器却是因为权限失败:报成注册会失败,不藏成"没测成" + await sql(admin, ` + create or replace function public.tell_crm() returns trigger language plpgsql security definer set search_path = '' as $$ + begin raise exception 'no access' using errcode = '42501'; end $$;`); + const denied = await runDrill(config, { store: (await backup("default")).store }); + assert.equal(denied.auth.signup.ok, false, JSON.stringify(denied.auth.signup)); + assert.equal( + denied.auth.signup.detail, + "a new sign-up would fail: permission denied (SQLSTATE 42501) (tested as an email sign-up with no user metadata)" + ); + } finally { + await sql(admin, "drop trigger tell_crm on auth.users; drop function public.tell_crm(); drop table public.leaks; drop extension dblink"); + } + }); + + const networksOf = async (id) => + Object.keys(JSON.parse((await x("docker", ["inspect", "-f", "{{json .NetworkSettings.Networks}}", id])).stdout.trim()) ?? {}); + const inContainer = async (id, query) => + (await x("docker", ["exec", id, "psql", "-U", "postgres", "-X", "-tA", "-c", query])).stdout.trim(); + + await t.test("a trigger whose ASSERT fails is reported as a failing sign-up (WHEN OTHERS doesn't catch it)", async () => { + await sql(admin, ` + create function public.assert_signup() returns trigger language plpgsql security definer set search_path = '' as $$ + begin assert new.email like '%@example.com', 'only example.com'; return new; end $$; + create trigger assert_signup after insert on auth.users for each row execute function public.assert_signup();`); + try { + const report = await runDrill(config, { store: (await backup("default")).store }); + assert.deepEqual(report.auth.signup, { + ran: true, + ok: false, + detail: "a new sign-up would fail: an assertion failed (SQLSTATE P0004) (tested as an email sign-up with no user metadata)", + }); + } finally { + await sql(admin, "drop trigger assert_signup on auth.users; drop function public.assert_signup()"); + } + }); + + await t.test("the offline test sign-up arrives over TCP like a real one: a trigger that needs the client address works", async () => { + await sql(admin, ` + create function public.needs_client_addr() returns trigger language plpgsql security definer set search_path = '' as $$ + begin + if pg_catalog.inet_client_addr() is null then raise exception 'no client address'; end if; + return new; + end $$; + create trigger needs_client_addr after insert on auth.users for each row execute function public.needs_client_addr();`); + try { + const report = await runDrill(config, { store: (await backup("default")).store }); + assert.ok(report.auth.triggers.created.includes("needs_client_addr"), JSON.stringify(report.auth)); + assert.deepEqual(report.auth.signup, { ran: true, ok: true }); + } finally { + await sql(admin, "drop trigger needs_client_addr on auth.users; drop function public.needs_client_addr()"); + } + }); + + await t.test("--keep keeps a reachable sandbox: the test sign-up is skipped, connString works as in 2.11.0", async () => { + const mem = await backup("default"); + const report = await runDrill(config, { store: mem.store, appCheckCommand: "exit 1", keepSandboxOnFailure: true }); + assert.ok(report.keptSandbox, "a failed drill with --keep leaves the sandbox"); + const id = report.keptSandbox.containerId; + try { + assert.deepEqual(report.auth.signup, { ran: false, detail: "--keep leaves the sandbox connected so you can inspect it" }); + assert.equal(report.pass, false, "the verdict comes from the app check, as before"); + assert.ok((await networksOf(id)).length > 0, "never taken off the network"); + const kept = await sql(report.keptSandbox.connString, "select count(*)::int as n from auth.users"); + assert.equal(kept.rows[0].n, 4, "connString answers; no test user was ever inserted"); + assert.equal(report.keptSandbox.inspect, `docker exec -it ${id.slice(0, 12)} psql -U postgres`); + } finally { + await x("docker", ["rm", "-f", "-v", id]).catch(() => {}); + } + // --keep 但演练通过了:沙箱不会留下,模拟注册照常(断网)跑 + const passed = await runDrill(config, { store: mem.store, keepSandboxOnFailure: true }); + assert.equal(passed.pass, true); + assert.equal(passed.keptSandbox, undefined); + assert.deepEqual(passed.auth.signup, { ran: true, ok: true }); + }); + + await t.test("an Auth check that times out during the offline sign-up: not checked, and the drill finishes", async () => { + await sql(admin, ` + create function public.slow_signup() returns trigger language plpgsql security definer set search_path = '' as $$ + begin perform pg_sleep(120); return new; end $$; + create trigger slow_signup after insert on auth.users for each row execute function public.slow_signup();`); + const previous = AUTH_DRILL_LIMITS.totalMs; + try { + const mem = await backup("default"); + AUTH_DRILL_LIMITS.totalMs = 20_000; + const started = Date.now(); + const report = await runDrill(config, { store: mem.store }); + assert.equal(report.auth.status, "not_checked", report.auth.summary); + assert.deepEqual(verdict(report).pass, baseline.pass); + assert.ok(Date.now() - started < 90_000, `took ${Date.now() - started} ms`); + } finally { + AUTH_DRILL_LIMITS.totalMs = previous; + await sql(admin, "drop trigger slow_signup on auth.users; drop function public.slow_signup()"); + } + }); + + await t.test("offline sandbox: cancelled first means no network is touched; a local timeout or a stop ends the sign-up inside", async () => { + await startPostgres(ids); + const id = ids.at(-1); + const sandbox = { containerId: id, offline: false }; + const offline = offlineSandbox(sandbox); + const marker = () => randomUUID().replace(/-/g, "").slice(0, 16); + const sleepy = (m) => `select 'm${m}', pg_sleep(120);\n`; + const leftovers = async (m) => ({ + sessions: await inContainer(id, `select count(*) from pg_stat_activity where query like '%m${m}%' and pid <> pg_backend_pid()`), + psql: (await x("docker", ["exec", id, "sh", "-c", "cat /proc/[0-9]*/comm 2>/dev/null | grep -c '^psql$' || true"])).stdout.trim(), + }); + + // 叫停在先:一个网络都不摘,沙箱照样在线 + const early = new AbortController(); + early.abort(); + await assert.rejects(offline.runOffline(sleepy(marker()), marker(), early.signal), /stopped/); + assert.equal(sandbox.offline, false); + assert.ok((await networksOf(id)).length > 0); + + // 本地的 docker exec 等到点被杀:容器里的那次注册也被停掉,才交出结果 + const previous = OFFLINE_SIGNUP_LIMITS.psqlMs; + OFFLINE_SIGNUP_LIMITS.psqlMs = 3000; + try { + const m = marker(); + const result = await offline.runOffline(sleepy(m), m); + assert.equal(result.code, null, "killed at the local timeout"); + assert.equal(sandbox.offline, true); + assert.deepEqual(await networksOf(id), []); + assert.deepEqual(await leftovers(m), { sessions: "0", psql: "0" }); + } finally { + OFFLINE_SIGNUP_LIMITS.psqlMs = previous; + } + + // 最坏的时序:启动脚本看过取消标记、还没 exec psql 时就被叫停(测试钩子在这两步之间停 3 秒)。 + // 收尾之后等它本来该醒来的时间过去,psql 也不能再起来 + OFFLINE_SIGNUP_LIMITS.launchPauseSeconds = 3; + try { + const late = marker(); + const stopEarly = new AbortController(); + setTimeout(() => stopEarly.abort(), 1000); + const result = await offline.runOffline(sleepy(late), late, stopEarly.signal); + assert.equal(result.code, null); + await new Promise((r) => setTimeout(r, 4000)); + assert.deepEqual(await leftovers(late), { sessions: "0", psql: "0" }); + } finally { + OFFLINE_SIGNUP_LIMITS.launchPauseSeconds = 0; + } + + // 运行中被叫停:同样停掉容器里的注册。演练那边的收尾(stopOfflineSessions)同时也来, + // 两边等的是同一次收尾,整体在时限(15 秒)之内结束 + const m = marker(); + const stop = new AbortController(); + let stopsBoth; + setTimeout(() => { + stop.abort(); + stopsBoth = offline.stopOfflineSessions(); + }, 1500); + const stoppedAt = Date.now(); + const result = await offline.runOffline(sleepy(m), m, stop.signal); + await stopsBoth; + assert.ok(Date.now() - stoppedAt < 1500 + 16_000, `took ${Date.now() - stoppedAt} ms`); + assert.equal(result.code, null); + assert.deepEqual(await leftovers(m), { sessions: "0", psql: "0" }); + assert.deepEqual(await networksOf(id), [], "and still never put back on the network"); + }); + await t.test("a backed-up row count that doesn't match is a problem, the verdict doesn't move", async () => { const mem = await backup("default"); const m = mem.manifest(); diff --git a/test/auth-fixtures.js b/test/auth-fixtures.js index 54fb4ae..d582e3c 100644 --- a/test/auth-fixtures.js +++ b/test/auth-fixtures.js @@ -60,6 +60,15 @@ export const AUTH_DDL = ` ); alter table auth.users enable row level security; alter table auth.identities enable row level security; + -- Supabase 自带的约束和索引:token 上的唯一索引带 WHERE 条件,空串不在索引里;确认状态只能是 0 到 2。 + -- 备份时抹掉待处理 token 必须过得了它们(见 pendingTokenConflicts) + alter table auth.users add constraint users_email_change_confirm_status_check + check (email_change_confirm_status >= 0 and email_change_confirm_status <= 2); + create unique index confirmation_token_idx on auth.users (confirmation_token) where confirmation_token::text !~ '^[0-9 ]*$'; + create unique index recovery_token_idx on auth.users (recovery_token) where recovery_token::text !~ '^[0-9 ]*$'; + create unique index email_change_token_current_idx on auth.users (email_change_token_current) where email_change_token_current::text !~ '^[0-9 ]*$'; + create unique index email_change_token_new_idx on auth.users (email_change_token_new) where email_change_token_new::text !~ '^[0-9 ]*$'; + create unique index reauthentication_token_idx on auth.users (reauthentication_token) where reauthentication_token::text !~ '^[0-9 ]*$'; `; // 和 Supabase 同形的最小 auth:两张表开 RLS、identities 外键指向 users;public.profiles 外键指向 auth.users, diff --git a/test/auth-restore.test.js b/test/auth-restore.test.js index 21f30ab..af85f27 100644 --- a/test/auth-restore.test.js +++ b/test/auth-restore.test.js @@ -6,6 +6,7 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; import pg from "pg"; @@ -167,6 +168,37 @@ test( assert.equal(profile.rows[0]?.name, "new@example.test"); }); + await t.test("an Auth archive written before 2.11.1, with the pending tokens still in it, restores with them cleared", async () => { + // 2.10 / 2.11.0 的 auth.dump:同样的 pg_dump 参数、不改写 + const { stdout: legacy } = await x( + pgDump, + ["--format=custom", "--no-owner", "--no-privileges", "--table=auth.users", "--table=auth.identities", "--dbname", okUrl], + { encoding: "buffer", maxBuffer: 64 * 1024 * 1024 } + ); + const legacyPath = join(work, "legacy-auth.dump"); + writeFileSync(legacyPath, legacy); + const legacyData = (await x(realPgRestore, ["--data-only", "-t", "users", "-f", "-", legacyPath])).stdout; + assert.ok(legacyData.includes("pending-reset"), "the old-style archive really has the pending token"); + const old = readableMemoryStore(); + for (const [k, v] of mem.files) old.files.set(k, v); + old.files.set("auth.dump", legacy); + const m = mem.manifest(); + old.setManifest({ + ...m, + auth: { ...m.auth, dump: { ...m.auth.dump, bytes: legacy.length, sha256: createHash("sha256").update(legacy).digest("hex") } }, + }); + const target = await freshTarget(); + const result = await runRestore(config, { store: old.store, targetDatabaseUrl: target, confirmTarget: "127.0.0.1" }); + assert.equal(result.auth.restored, true); + const after = await sql( + target, + `select count(*)::int as users, + count(*) filter (where recovery_token <> '' or recovery_sent_at is not null)::int as pending + from auth.users` + ); + assert.deepEqual(after.rows[0], { users: 4, pending: 0 }); + }); + await t.test("dry run: passes on a new project, and stops on a target that already has Auth users", async () => { const target = await freshTarget(); await restore(target, { dryRun: true }); @@ -487,6 +519,8 @@ test( const srcConfig = { ...config, databaseUrl: `postgresql://reader_ok:r@127.0.0.1:${port}/emailsource`, projectName: "emailfk" }; const srcMem = readableMemoryStore(); await runBackup({ ...srcConfig, auth: "default" }, { store: srcMem.store }); + // email 不是被抹的列,UNIQUE (email) 不挡 Auth 备份:这条检查走的是带 Auth 的恢复 + assert.equal(srcMem.manifest().auth.status, "included", JSON.stringify(srcMem.manifest().auth)); const target = await freshTarget(); const run = (extra) => runRestore(srcConfig, { store: srcMem.store, targetDatabaseUrl: target, confirmTarget: "127.0.0.1", ...extra }); await assert.rejects(run({ dryRun: true }), /auth\.users on the target has no unique index on \(email\)/); diff --git a/test/auth-signup-offline.test.js b/test/auth-signup-offline.test.js new file mode 100644 index 0000000..8742085 --- /dev/null +++ b/test/auth-signup-offline.test.js @@ -0,0 +1,106 @@ +// 演练里的模拟注册(2.11.1 起断网跑,经容器里的 psql):SQL 怎么拼、psql 的输出怎么读成报告。不需要 Docker; +// 真的断网跑一遍(含 dblink 触发器写不出去)在 auth-drill.test.js 里。 +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { signupOutcome, signupScript } from "../dist/auth-drill.js"; + +const hex = (s) => Buffer.from(s, "utf8").toString("hex"); +const out = (state, context = "", message = "", detail = "") => ({ + code: 0, + stdout: `backupdrill-signup ${state} ${hex(context)} ${hex(message)} ${hex(detail)}\n`, +}); +const OWN_BLOCK = 'SQL statement "insert into auth.users (id) values (1)"\nPL/pgSQL function inline_code_block line 9 at SQL statement'; + +test("signupScript: rolls back, runs as supabase_auth_admin, and quotes the block with this sign-up's random marker", () => { + const marker = "0123456789abcdef"; + const a = signupScript("insert into auth.users (\"$bd_x$\") values (1)", "insert into auth.identities (id) values (1)", marker); + assert.match(a, /^do \$bd_0123456789abcdef\$$/m); + assert.equal(a.split("$bd_0123456789abcdef$").length, 3, "the marker only opens and closes the block"); + assert.match(a, /set local role supabase_auth_admin;/); + assert.match(a, /set constraints all immediate;/); + // WHEN OTHERS 接不住 ASSERT 失败,单独接 + assert.match(a, /when assert_failure then[\s\S]*when others then/); + assert.match(a.trimEnd(), /rollback;$/); + assert.doesNotMatch(a, /\bcommit\b/i); +}); + +test("signupOutcome: ok, a trigger that fails, and a test row that doesn't fit the table", () => { + assert.deepEqual(signupOutcome(out("ok")), { ran: true, ok: true }); + assert.deepEqual( + signupOutcome(out("P0001", `PL/pgSQL function public.handle_new_user() line 3 at RAISE\n${OWN_BLOCK}`)), + { ran: true, ok: false, detail: "a new sign-up would fail: an exception was raised (SQLSTATE P0001) (tested as an email sign-up with no user metadata)" } + ); + // 错在我们造的那一行本身(只有我们自己那层 DO 块的上下文):不算触发器的问题 + assert.deepEqual(signupOutcome(out("23502", OWN_BLOCK)), { + ran: false, + detail: "couldn't simulate a sign-up: a not-null constraint was violated (SQLSTATE 23502)", + }); +}); + +test("signupOutcome: 'may need network access' only with evidence of a connection failure; anything else is a real sign-up failure", () => { + const inTrigger = (statement) => `${statement}\nPL/pgSQL function public.tell_crm() line 2 at PERFORM\n${OWN_BLOCK}`; + const dblinkCall = inTrigger(`SQL statement "SELECT public.dblink_exec('host=10.0.0.1', 'insert into t default values')"`); + const httpCall = inTrigger(`SQL statement "SELECT http_post('https://crm.example/hook', '{}', 'application/json')"`); + const notTested = (r) => { + assert.equal(r.ran, false, JSON.stringify(r)); + assert.match(r.detail, /^a database operation failed to connect while the sandbox was offline \(SQLSTATE \w{5}\)$/); + }; + // 连接类 SQLSTATE,DETAIL 里是网络不可达 / 解析不了主机名(dblink、postgres_fdw 断网时就是这样) + notTested(signupOutcome(out("08001", dblinkCall, "could not establish connection", + 'connection to server at "10.0.0.1", port 5432 failed: Network is unreachable'))); + notTested(signupOutcome(out("08001", dblinkCall, "could not establish connection", + 'could not translate host name "crm.example" to address: Temporary failure in name resolution'))); + // musl(alpine 沙箱)的原话,2026-11-21 在断网的 postgres:17-alpine 里实测 + notTested(signupOutcome(out("08001", dblinkCall, "could not establish connection", + 'connection to server at "172.17.0.9", port 5432 failed: Network unreachable\n\tIs the server running on that host and accepting TCP/IP connections?'))); + notTested(signupOutcome(out("08001", dblinkCall, "could not establish connection", + 'could not translate host name "crm.example.invalid" to address: Try again'))); + // 联网调用自己报的连接/解析失败(http 扩展的 libcurl 错误是 XX000) + notTested(signupOutcome(out("XX000", httpCall, "Couldn't resolve host name"))); + // COPY ... PROGRAM:消息里有连不上的证据才算 + const copyProgram = inTrigger(`SQL statement "copy (select 1) to program 'wget -q https://crm.example/hook'"`); + notTested(signupOutcome(out("38000", copyProgram, "wget: bad address 'crm.example'"))); + + const failed = (r, sqlstate) => + assert.deepEqual(r, { + ran: true, + ok: false, + detail: `a new sign-up would fail: ${sqlstate} (tested as an email sign-up with no user metadata)`, + }); + // 出错的语句里也调了 net.http_post,但失败的是检查约束(审查复现的情况):真问题 + failed( + signupOutcome(out("23514", inTrigger(`SQL statement "insert into public.hooks (r) values (net.http_post(url := 'https://crm.example'))"`), "new row violates check constraint")), + "a check constraint was violated (SQLSTATE 23514)" + ); + // 同是 08001,但原因是认证或配置(密码不对、没有 pg_hba 条目),或者根本没给出原因:真问题 + for (const detail of [ + 'connection to server at "10.0.0.1", port 5432 failed: FATAL: password authentication failed for user "app"', + 'connection to server at "10.0.0.1", port 5432 failed: FATAL: no pg_hba.conf entry for host "172.17.0.3"', + 'connection to server at "127.0.0.1", port 5432 failed: FATAL: role "nobody" does not exist', + "", + ]) { + failed(signupOutcome(out("08001", dblinkCall, "could not establish connection", detail)), "a connection couldn't be made (SQLSTATE 08001)"); + } + // 触发器里的 ASSERT 失败(P0004) + failed( + signupOutcome(out("P0004", `PL/pgSQL function public.check_user() line 2 at ASSERT\n${OWN_BLOCK}`, "assertion failed")), + "an assertion failed (SQLSTATE P0004)" + ); + // dblink 调用本身报权限不够(42501)、dblink 没装(42883):真问题 + failed(signupOutcome(out("42501", dblinkCall, "permission denied for function dblink_exec")), "permission denied (SQLSTATE 42501)"); + failed(signupOutcome(out("42883", dblinkCall, "function public.dblink_exec(unknown, unknown) does not exist")), "a function doesn't exist (SQLSTATE 42883)"); + // COPY ... PROGRAM 只说程序失败、看不出原因:真问题 + failed(signupOutcome(out("38000", copyProgram, 'program "wget -q https://crm.example/hook" failed')), "an error (SQLSTATE 38000)"); + // http 调用报的不是连接问题,或者触发器自己 RAISE:真问题 + failed(signupOutcome(out("XX000", httpCall, "invalid content type")), "an error (SQLSTATE XX000)"); + failed(signupOutcome(out("P0001", httpCall, "could not connect")), "an exception was raised (SQLSTATE P0001)"); +}); + +test("signupOutcome: psql that didn't finish (timeout, killed) or printed no result line means no sign-up was simulated", () => { + assert.deepEqual(signupOutcome({ code: 3, stdout: "" }), { ran: false, detail: "psql did not confirm a sign-up result" }); + assert.deepEqual(signupOutcome({ code: null, stdout: "backupdrill-signup ok \n" }), { + ran: false, + detail: "psql did not confirm a sign-up result", + }); + assert.equal(signupOutcome({ code: 0, stdout: "something else\n" }).ran, false); +});