backupdrill 2.8.0 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -9
- package/dist/backup.js +15 -0
- package/dist/drill.d.ts +5 -7
- package/dist/drill.js +19 -11
- package/dist/grants.d.ts +66 -0
- package/dist/grants.js +296 -0
- package/dist/lib.d.ts +2 -0
- package/dist/lib.js +2 -0
- package/dist/manifest.d.ts +4 -0
- package/dist/manifest.js +32 -0
- package/dist/orphaned-foreign-keys.d.ts +10 -1
- package/dist/orphaned-foreign-keys.js +14 -1
- package/dist/recovery-doc.js +17 -4
- package/dist/restore-engine.d.ts +14 -5
- package/dist/restore-engine.js +67 -18
- package/dist/restore.js +18 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -160,7 +160,7 @@ backupdrill estimate --plan pro # measures your DB + Storage, prints the proje
|
|
|
160
160
|
├── dump.pgcustom # pg_dump --format=custom (public schema by default)
|
|
161
161
|
├── storage/<bucket>/<key> # your Storage files (if configured)
|
|
162
162
|
├── RECOVERY.md # how to restore this snapshot
|
|
163
|
-
└── manifest.json # schemas, tables, row counts, file list, sizes + sha256
|
|
163
|
+
└── manifest.json # schemas, tables, row counts, grants, file list, sizes + sha256
|
|
164
164
|
<prefix>/<project>.drills/<finished-at>-<passed|failed>-<tag>.json # only with drill --record: one file per drill
|
|
165
165
|
```
|
|
166
166
|
|
|
@@ -207,7 +207,7 @@ backupdrill restore --database --target-supabase-url https://<ref>.supabase.co -
|
|
|
207
207
|
|
|
208
208
|
Prefer files on disk instead? Skip the Storage target and pass `--storage-dir ./recovered`.
|
|
209
209
|
|
|
210
|
-
`--dry-run` writes nothing to the target. Besides checking the target (not the source project, schemas empty, Postgres and `pg_restore` versions, extensions available), it downloads the dump to a temporary directory, checks its sha256 and looks for foreign keys that point outside the backup (see [Tables that reference auth.users](#tables-that-reference-authusers)). The real run repeats those checks before it writes anything; a foreign key into a table that one of the recorded extensions creates is checked again once the extensions are installed. The database restore then runs in a single transaction: if any statement fails, nothing from the snapshot stays on the target, and you can run it again on the same project once you've fixed the cause. (If the connection drops while it commits, the error says so and asks you to check the target first.) Foreign keys between two tables in the backup are the exception: they're added
|
|
210
|
+
`--dry-run` writes nothing to the target. Besides checking the target (not the source project, schemas empty, Postgres and `pg_restore` versions, extensions available), it downloads the dump to a temporary directory, checks its sha256 and looks for foreign keys that point outside the backup (see [Tables that reference auth.users](#tables-that-reference-authusers)). The real run repeats those checks before it writes anything; a foreign key into a table that one of the recorded extensions creates is checked again once the extensions are installed. The database restore then runs in a single transaction: if any statement fails, nothing from the snapshot stays on the target, and you can run it again on the same project once you've fixed the cause. (If the connection drops while it commits, the error says so and asks you to check the target first.) Right after that transaction commits, the grants for `anon`, `authenticated` and `service_role` are set in a transaction of their own (see [Grants for anon, authenticated and service_role](#grants-for-anon-authenticated-and-service_role)). Foreign keys between two tables in the backup are the exception to the single transaction: they're added after that, in one more. If rows in your data already break one of them (deleting with triggers switched off, for example under `session_replication_role = replica`, can leave rows like that), the key is added as `NOT VALID` instead of failing the restore. Those rows come back as they are, new writes are still checked, and the report names the key and, when it can count them, how many rows break it. Keys on or into partitioned tables, keys into an extension's tables, and every key in an archive whose foreign key statements BackupDrill can't fully read stay in the main transaction, so a broken one rolls the whole restore back. A key over a generated column is added in the second step but is never relaxed, because the restore recomputes those values; if it breaks, that step fails. Keys added as `NOT VALID` don't fail a drill: the drill passes and lists them in its report. If a step after the main transaction fails for any other reason, the tables and data are already on the target and the error says so. Extensions the run installed stay installed, since the next run needs them too, and the empty-target check doesn't count objects that belong to an extension (except an extension's configuration tables, whose rows a dump can carry). One transaction holds a lock on every table, index and sequence until it commits, so a very large schema can run out of lock slots: on Supabase's smallest compute size, about a thousand tables (partitions count as tables). The restore then stops with nothing written and tells you how to raise `max_locks_per_transaction`.
|
|
211
211
|
|
|
212
212
|
Or restore the dump by hand — into an **empty** database, without `--clean`:
|
|
213
213
|
|
|
@@ -215,13 +215,25 @@ Or restore the dump by hand — into an **empty** database, without `--clean`:
|
|
|
215
215
|
pg_restore --no-owner --no-privileges --dbname "<target-connection-string>" dump.pgcustom
|
|
216
216
|
```
|
|
217
217
|
|
|
218
|
-
Don't use `--clean` against a Supabase project:
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
218
|
+
One error is expected and harmless: `schema "public" already exists` — the target always has it. An error on a foreign key into `auth.users` means the users have to be copied in first (see [Tables that reference auth.users](#tables-that-reference-authusers)). After that, set the grants yourself (next section). Don't use `--clean` against a Supabase project: it drops and recreates the `public` schema, and with it the grants Supabase put on it. The `backupdrill restore` command above handles all of this (plus verification) for you.
|
|
219
|
+
|
|
220
|
+
### Grants for anon, authenticated and service_role
|
|
221
|
+
|
|
222
|
+
supabase-js and the other client libraries reach your tables through the Data API, as `anon`, `authenticated` or `service_role`. Postgres refuses any table those roles have no grant on, with `42501 permission denied`, before row-level security even runs.
|
|
223
|
+
|
|
224
|
+
The dump doesn't carry grants, so a restored table only gets what the target project hands out by default. Supabase used to grant every new table in `public` to all three roles. It stopped doing that for new projects on May 30, 2026, and for existing projects on October 30, 2026 ([Supabase's announcement](https://github.com/orgs/supabase/discussions/45329)). On a project that has switched, a plain `pg_restore` brings back every table and row, and the app still gets `42501` on all of them. On a project that hasn't switched yet, it does the opposite: every restored table is open to `anon`, including the ones you had closed.
|
|
225
|
+
|
|
226
|
+
So each backup also records, in `manifest.json` under `database.grants`, what `anon`, `authenticated`, `service_role` and `PUBLIC` were granted on every table, view, sequence and function in the backed-up schemas (column-level grants and schema `USAGE` included). After the data is in, `restore` and `drill` take those four roles off every restored object and grant back exactly what the source had, whatever the target's defaults are, then read the grants back to check they took. Objects that belong to an extension are left alone. The report has an `API grants` line. `pg_restore` runs in its own process, so the grants can't go into its transaction: for the moment between its commit and the grants, the restored objects have the target's defaults. If setting the grants fails, `restore` tries to revoke those roles' access to the restored objects instead. If that works, your app gets `42501` until you grant what it needs; if it fails too, the error tells you to check the target's default grants before the app goes live.
|
|
227
|
+
|
|
228
|
+
Snapshots taken before 2.9.0 have no record. Restoring one of those, the CLI gives the three roles Supabase's old default access to every table, sequence and function in `public`, which is what those projects had unless you revoked it, and the `API grants` line says so. Revoke it on anything you had kept private. For tables in your own schemas, the CLI leaves the target's default grants as they are.
|
|
229
|
+
|
|
230
|
+
By hand, to get back Supabase's old defaults in `public` (then revoke on the tables you keep private):
|
|
231
|
+
|
|
232
|
+
```sql
|
|
233
|
+
grant all on all tables in schema public to anon, authenticated, service_role;
|
|
234
|
+
grant all on all sequences in schema public to anon, authenticated, service_role;
|
|
235
|
+
grant execute on all functions in schema public to anon, authenticated, service_role;
|
|
236
|
+
```
|
|
225
237
|
|
|
226
238
|
### Tables that reference auth.users
|
|
227
239
|
|
package/dist/backup.js
CHANGED
|
@@ -11,6 +11,7 @@ import { log } from "./log.js";
|
|
|
11
11
|
import { TOOL_VERSION } from "./version.js";
|
|
12
12
|
import { parsePgDumpMajor } from "./pgbin.js";
|
|
13
13
|
import { relationBytes } from "./estimate.js";
|
|
14
|
+
import { captureGrants } from "./grants.js";
|
|
14
15
|
// 解析函数搬到了 pgbin(演练与恢复都要读 pg_restore 版本,放这里会成环);保留旧出口
|
|
15
16
|
export { parsePgDumpMajor };
|
|
16
17
|
import { dumpUrlFor, connectPg, isSupabaseHost } from "./supabase-ca.js";
|
|
@@ -90,6 +91,15 @@ async function inspectDatabase(databaseUrl, schemas) {
|
|
|
90
91
|
await client.end();
|
|
91
92
|
}
|
|
92
93
|
}
|
|
94
|
+
async function readGrants(databaseUrl, schemas) {
|
|
95
|
+
const client = await connectPg(databaseUrl);
|
|
96
|
+
try {
|
|
97
|
+
return await captureGrants(client, schemas);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
await client.end();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
93
103
|
/** 流式跑 pg_dump,边写快照边算 sha256 与字节数。返回校验和与大小。 */
|
|
94
104
|
async function dumpToSnapshot(config, writer, pgDumpBin, dumpRelationBytes) {
|
|
95
105
|
const hash = createHash("sha256");
|
|
@@ -192,6 +202,10 @@ export async function runBackup(config, opts = {}) {
|
|
|
192
202
|
log.step(`Dumping → ${writer.describe("dump.pgcustom")}`);
|
|
193
203
|
const { bytes, sha256 } = await dumpToSnapshot(config, writer, pgDumpBin, db.relationBytes);
|
|
194
204
|
log.ok(`Database dumped (${(bytes / 1024 / 1024).toFixed(1)} MB, sha256 ${sha256.slice(0, 12)}…)`);
|
|
205
|
+
// 授权在转储之后读:转储期间有人收回权限,记下的是收回之后的,不会拿旧的开放授权去配新数据。
|
|
206
|
+
// 读不到就让备份失败,不留一份缺授权记录的快照:恢复端把"没有记录"当成 2.9.0 之前的旧快照,
|
|
207
|
+
// 按 Supabase 以前的默认授权开放 public,会把源库关着的表打开
|
|
208
|
+
const grants = await readGrants(config.databaseUrl, config.schemas);
|
|
195
209
|
// Storage 文件同步(源配置存在才做;否则只备数据库)
|
|
196
210
|
let storageResult = null;
|
|
197
211
|
if (config.supabaseStorage && storageFiles) {
|
|
@@ -237,6 +251,7 @@ export async function runBackup(config, opts = {}) {
|
|
|
237
251
|
estimatedRowTotal: db.tables.reduce((n, t) => n + t.estimatedRows, 0),
|
|
238
252
|
tables: db.tables,
|
|
239
253
|
extensions: db.extensions,
|
|
254
|
+
grants,
|
|
240
255
|
},
|
|
241
256
|
dump: { key: dumpKey, format: "custom", bytes, sha256 },
|
|
242
257
|
storage: storageResult,
|
package/dist/drill.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { BackupConfig } from "./config.js";
|
|
2
2
|
import type { Manifest } from "./manifest.js";
|
|
3
3
|
import { type SnapshotStore } from "./snapshot-store.js";
|
|
4
|
-
import type
|
|
4
|
+
import { type OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
5
|
+
import { type GrantRestore } from "./grants.js";
|
|
5
6
|
/**
|
|
6
7
|
* 无放回随机抽样:部分 Fisher-Yates,只洗出前 n 位(O(n) 次交换,不必全 shuffle)。
|
|
7
8
|
* 此前恒取 manifest 顺序的前 CAP 个 → 超过 CAP 的项目里排序靠后的文件永远不被校验;
|
|
@@ -41,13 +42,8 @@ export interface DrillReport {
|
|
|
41
42
|
containerId: string;
|
|
42
43
|
connString: string;
|
|
43
44
|
};
|
|
44
|
-
/**
|
|
45
|
+
/** 源库自带孤儿行的外键:演练和真实恢复都把它们建成 NOT VALID,不算失败。没有时不出现 */
|
|
45
46
|
orphanedForeignKeys?: OrphanedForeignKey[];
|
|
46
|
-
/**
|
|
47
|
-
* 失败的唯一原因是这些孤儿行:备份完整、恢复能成功,是用户库里的数据违反了自己的外键。
|
|
48
|
-
* worker 据此把失败报告直接发给用户,不当成我们要排查的故障。
|
|
49
|
-
*/
|
|
50
|
-
failureCause?: "source-data";
|
|
51
47
|
}
|
|
52
48
|
export interface SandboxTuning {
|
|
53
49
|
settings: string[];
|
|
@@ -64,6 +60,8 @@ interface PostDataResult {
|
|
|
64
60
|
failures: string[];
|
|
65
61
|
/** 已同时计入 failures */
|
|
66
62
|
orphanedForeignKeys?: OrphanedForeignKey[];
|
|
63
|
+
/** 授权重建结果;失败时不存在,原因在 failures 里 */
|
|
64
|
+
grants?: GrantRestore;
|
|
67
65
|
}
|
|
68
66
|
/** 兼容层:历史签名保留,分类逻辑的单一权威在统一引擎(restore-engine.ts)。 */
|
|
69
67
|
export declare function classifyPostDataErrors(stderr: string): PostDataResult;
|
package/dist/drill.js
CHANGED
|
@@ -9,6 +9,8 @@ import { hashObject } from "./snapshots.js";
|
|
|
9
9
|
import { s3SnapshotStore } from "./snapshot-store.js";
|
|
10
10
|
import { SANDBOX_MANAGED_ERROR, classifyBlocks, finalizePass, installExtensions, quoteIdent, restoreDatabaseArtifact, installSandboxShim, tableDataInDump, } from "./restore-engine.js";
|
|
11
11
|
import { connectPg } from "./supabase-ca.js";
|
|
12
|
+
import { orphanedForeignKeysCheck } from "./orphaned-foreign-keys.js";
|
|
13
|
+
import { grantsCheck } from "./grants.js";
|
|
12
14
|
import { localPgRestoreMajor, restoreToolBreaksOnTarget, sandboxMajorFor } from "./pgbin.js";
|
|
13
15
|
import { log } from "./log.js";
|
|
14
16
|
import { onInterrupt, stopOnInterrupt, throwIfInterrupted } from "./interrupt.js";
|
|
@@ -308,8 +310,15 @@ export function postDataResult(code, stderr) {
|
|
|
308
310
|
* 的托管对象跳过如实返回。pre-data 的 schema 冲突跳过(dump 自带 CREATE SCHEMA,
|
|
309
311
|
* 容器恒有 public)是非事件,不计入报告。
|
|
310
312
|
*/
|
|
311
|
-
async function pgRestore(dumpPath, connString, dumpedSchemas, jobs) {
|
|
312
|
-
const result = await restoreDatabaseArtifact({
|
|
313
|
+
async function pgRestore(dumpPath, connString, dumpedSchemas, jobs, grants) {
|
|
314
|
+
const result = await restoreDatabaseArtifact({
|
|
315
|
+
dumpPath,
|
|
316
|
+
connString,
|
|
317
|
+
target: "sandbox",
|
|
318
|
+
dumpedSchemas,
|
|
319
|
+
jobs,
|
|
320
|
+
grants: { schemas: dumpedSchemas, recorded: grants },
|
|
321
|
+
});
|
|
313
322
|
if (result.preData.failures.length) {
|
|
314
323
|
throw new Error(`pg_restore failed: ${result.preData.failures.join(" | ")}`);
|
|
315
324
|
}
|
|
@@ -317,6 +326,7 @@ async function pgRestore(dumpPath, connString, dumpedSchemas, jobs) {
|
|
|
317
326
|
supabaseSkipped: result.postData.expectedSkips,
|
|
318
327
|
failures: result.postData.failures,
|
|
319
328
|
orphanedForeignKeys: result.orphanedForeignKeys,
|
|
329
|
+
grants: result.grants,
|
|
320
330
|
};
|
|
321
331
|
}
|
|
322
332
|
// ── 校验 ────────────────────────────────────────────────────────────
|
|
@@ -580,7 +590,7 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
580
590
|
log.step("Restoring into ephemeral Postgres…");
|
|
581
591
|
let postData;
|
|
582
592
|
try {
|
|
583
|
-
postData = await pgRestore(dumpPath, pg.connString, manifest.database.schemas, pg.restoreJobs);
|
|
593
|
+
postData = await pgRestore(dumpPath, pg.connString, manifest.database.schemas, pg.restoreJobs, manifest.database.grants);
|
|
584
594
|
}
|
|
585
595
|
catch (error) {
|
|
586
596
|
// 沙箱装不上扩展 + 错误特征命中"缺类型/schema/扩展" → 假设式归因到沙箱环境
|
|
@@ -616,6 +626,11 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
616
626
|
await opts.supervision?.observe({ phase: "verify" });
|
|
617
627
|
const verify = await verifyRestored(pg.connString, manifest, dumpPath);
|
|
618
628
|
checks.push(...verify.checks);
|
|
629
|
+
if (postData.grants)
|
|
630
|
+
checks.push(grantsCheck(postData.grants, "drill"));
|
|
631
|
+
const orphaned = postData.orphanedForeignKeys ?? [];
|
|
632
|
+
if (orphaned.length)
|
|
633
|
+
checks.push(orphanedForeignKeysCheck(orphaned));
|
|
619
634
|
// 语义层钩子:只在结构层全绿时才跑——结构已失败时再跑应用检查,只会把
|
|
620
635
|
// 一次失败报成两层失败,误导排查方向。没配置则不跑、报告里不出现该行。
|
|
621
636
|
if (appCheckCommand && checks.every((c) => c.pass)) {
|
|
@@ -632,15 +647,8 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
632
647
|
restoredTableCount: verify.tableCount,
|
|
633
648
|
restoredRowTotal: verify.rowTotal,
|
|
634
649
|
};
|
|
635
|
-
|
|
636
|
-
if (orphaned.length) {
|
|
650
|
+
if (orphaned.length)
|
|
637
651
|
report.orphanedForeignKeys = orphaned;
|
|
638
|
-
// 孤儿外键是 post-data 里仅有的失败、其余检查全过 → 失败只因用户数据
|
|
639
|
-
const onlyOrphans = postData.failures.length === orphaned.length;
|
|
640
|
-
if (!pass && onlyOrphans && checks.every((c) => c.pass || c.name === "post-data objects")) {
|
|
641
|
-
report.failureCause = "source-data";
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
652
|
if (opts.keepSandboxOnFailure && !pass) {
|
|
645
653
|
// 写进报告让 --keep 可被脚本消费(拿连接串排查),不只靠人眼看日志
|
|
646
654
|
report.keptSandbox = { containerId: pg.containerId, connString: pg.connString };
|
package/dist/grants.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Client } from "pg";
|
|
2
|
+
export declare const API_ROLES: readonly ["anon", "authenticated", "service_role"];
|
|
3
|
+
export type GrantRole = "PUBLIC" | (typeof API_ROLES)[number];
|
|
4
|
+
export declare const GRANT_ROLES: readonly GrantRole[];
|
|
5
|
+
export type GrantedObjectKind = "schema" | "table" | "sequence" | "routine" | "column";
|
|
6
|
+
export declare const GRANTED_OBJECT_KINDS: readonly GrantedObjectKind[];
|
|
7
|
+
export declare const GRANT_PRIVILEGES: readonly ["SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER", "MAINTAIN", "USAGE", "EXECUTE", "CREATE"];
|
|
8
|
+
/**
|
|
9
|
+
* 一个对象上 PUBLIC 和三个 API 角色的授权。表、视图、序列、函数一律记下(没有授权也记,
|
|
10
|
+
* privileges 为空 = 源库没给这几个角色任何权限);列只记有列级授权的;schema 一律记。
|
|
11
|
+
*/
|
|
12
|
+
export interface GrantedObject {
|
|
13
|
+
kind: GrantedObjectKind;
|
|
14
|
+
schema: string;
|
|
15
|
+
/** table / sequence / routine 的名字;column 是它所在的表;schema 没有 */
|
|
16
|
+
name?: string;
|
|
17
|
+
column?: string;
|
|
18
|
+
/** routine:pg_get_function_identity_arguments,聚合是输入参数类型(search_path 为空时取,类型都带 schema) */
|
|
19
|
+
args?: string;
|
|
20
|
+
privileges: Partial<Record<GrantRole, string[]>>;
|
|
21
|
+
}
|
|
22
|
+
export interface GrantRestore {
|
|
23
|
+
/** recorded = 照快照记录;legacy-defaults = 旧快照,按 Supabase 以前的默认授权补 public */
|
|
24
|
+
mode: "recorded" | "legacy-defaults";
|
|
25
|
+
/** 处理过的对象数 */
|
|
26
|
+
objects: number;
|
|
27
|
+
}
|
|
28
|
+
/** 备份端:读源库里这几个 schema 下每个对象给 PUBLIC 和 API 角色的授权。 */
|
|
29
|
+
export declare function captureGrants(client: Client, schemas: string[]): Promise<GrantedObject[]>;
|
|
30
|
+
/**
|
|
31
|
+
* 把一组对象的授权写成 SQL:schema、表、序列、函数先清掉这几个角色的全部权限再照记录授,
|
|
32
|
+
* 列级授权放在最后(清表权限会连带清掉列权限)。schema 也要清:源库可能靠不给 USAGE 把整个
|
|
33
|
+
* schema 关起来,目标上的 public 却是 Supabase 默认开放的。
|
|
34
|
+
* roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN。
|
|
35
|
+
*/
|
|
36
|
+
export declare function grantStatements(objects: GrantedObject[], opts: {
|
|
37
|
+
roles: readonly GrantRole[];
|
|
38
|
+
maintain: boolean;
|
|
39
|
+
}): string[];
|
|
40
|
+
/**
|
|
41
|
+
* 恢复端:在恢复出来的对象上照记录重建授权,一个事务内完成,提交前回读目录核对。
|
|
42
|
+
* 目标上的对象以目标目录为准:记录里有、目标上没有的(沙箱跳过的托管对象)略过;
|
|
43
|
+
* 目标上有、记录里没有的(备份转储完之后才建的)按"没有授权"处理,只清不授。
|
|
44
|
+
* recorded 为 undefined = 旧快照:public 里的表、序列、函数在目标已有授权之上补齐 Supabase 以前的默认授权。
|
|
45
|
+
*/
|
|
46
|
+
export declare function restoreGrants(client: Client, opts: {
|
|
47
|
+
schemas: string[];
|
|
48
|
+
recorded: GrantedObject[] | undefined;
|
|
49
|
+
}): Promise<GrantRestore>;
|
|
50
|
+
/**
|
|
51
|
+
* 补授权失败时的退路(只用于真实目标):把恢复出来的表、序列、函数上这几个角色的权限全部收走。
|
|
52
|
+
* 应用会 42501,但源库关着的东西不会因为目标的默认授权而开着。schema 不动,免得连带目标上别的东西。
|
|
53
|
+
*/
|
|
54
|
+
export declare function revokeApiAccess(client: Client, schemas: string[]): Promise<void>;
|
|
55
|
+
/** 演练和恢复报告里的一行。旧快照那句按场合说:恢复是已经开放了要收回,演练是提醒真恢复时会这样。 */
|
|
56
|
+
export declare function grantsCheck(outcome: GrantRestore, context: "drill" | "restore"): {
|
|
57
|
+
name: string;
|
|
58
|
+
pass: boolean;
|
|
59
|
+
detail: string;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用)。有记录就逐个对象照记录重建,
|
|
63
|
+
* 和 restoreGrants 同一套语句;旧快照没有记录,给 Supabase 以前的默认授权。
|
|
64
|
+
* MAINTAIN 只会出现在 PG17+ 源库的记录里,而恢复目标的版本不低于源库,所以照写。
|
|
65
|
+
*/
|
|
66
|
+
export declare function recoveryGrantsSql(grants: GrantedObject[] | undefined): string;
|
package/dist/grants.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
export const API_ROLES = ["anon", "authenticated", "service_role"];
|
|
2
|
+
export const GRANT_ROLES = ["PUBLIC", ...API_ROLES];
|
|
3
|
+
export const GRANTED_OBJECT_KINDS = ["schema", "table", "sequence", "routine", "column"];
|
|
4
|
+
// aclexplode 吐出的权限名。MAINTAIN 只有 PG17+ 有,恢复进旧版本时跳过
|
|
5
|
+
export const GRANT_PRIVILEGES = [
|
|
6
|
+
"SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER", "MAINTAIN",
|
|
7
|
+
"USAGE", "EXECUTE", "CREATE",
|
|
8
|
+
];
|
|
9
|
+
// 表、视图、物化视图、外部表、分区表、序列;函数和过程;schema;有列级授权的列。
|
|
10
|
+
// 扩展自带的对象不在转储里,恢复时由扩展自己建,不碰。
|
|
11
|
+
// search_path 由调用方设成空:identity arguments 里的类型才会都带 schema,两端比得上。
|
|
12
|
+
const CATALOG_OBJECTS_SQL = `
|
|
13
|
+
with api_roles(oid, role) as (
|
|
14
|
+
select 0::oid, 'PUBLIC'
|
|
15
|
+
union all
|
|
16
|
+
select oid, rolname::text from pg_catalog.pg_roles where rolname = any($2::text[])
|
|
17
|
+
),
|
|
18
|
+
relations as (
|
|
19
|
+
select c.oid, n.nspname::text as schema, c.relname::text as name, c.relkind,
|
|
20
|
+
coalesce(c.relacl, pg_catalog.acldefault(case when c.relkind = 'S' then 's' else 'r' end::"char", c.relowner)) as acl
|
|
21
|
+
from pg_catalog.pg_class c
|
|
22
|
+
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
|
23
|
+
where n.nspname = any($1::text[])
|
|
24
|
+
and c.relkind in ('r', 'p', 'v', 'm', 'f', 'S')
|
|
25
|
+
and not exists (select 1 from pg_catalog.pg_depend d
|
|
26
|
+
where d.classid = 'pg_catalog.pg_class'::pg_catalog.regclass and d.objid = c.oid and d.deptype = 'e')
|
|
27
|
+
),
|
|
28
|
+
objects as (
|
|
29
|
+
select case when relkind = 'S' then 'sequence' else 'table' end as kind,
|
|
30
|
+
schema, name, null::text as column_name, null::text as args, acl
|
|
31
|
+
from relations
|
|
32
|
+
union all
|
|
33
|
+
select 'column', r.schema, r.name, a.attname::text, null, a.attacl
|
|
34
|
+
from relations r
|
|
35
|
+
join pg_catalog.pg_attribute a on a.attrelid = r.oid
|
|
36
|
+
where a.attnum > 0 and not a.attisdropped and a.attacl is not null
|
|
37
|
+
union all
|
|
38
|
+
-- 聚合用输入参数类型:有序集聚合的 identity arguments 带 ORDER BY,GRANT 不认
|
|
39
|
+
select 'routine', n.nspname::text, p.proname::text, null,
|
|
40
|
+
case when p.prokind = 'a' then pg_catalog.oidvectortypes(p.proargtypes)
|
|
41
|
+
else pg_catalog.pg_get_function_identity_arguments(p.oid) end,
|
|
42
|
+
coalesce(p.proacl, pg_catalog.acldefault('f', p.proowner))
|
|
43
|
+
from pg_catalog.pg_proc p
|
|
44
|
+
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
|
|
45
|
+
where n.nspname = any($1::text[])
|
|
46
|
+
and not exists (select 1 from pg_catalog.pg_depend d
|
|
47
|
+
where d.classid = 'pg_catalog.pg_proc'::pg_catalog.regclass and d.objid = p.oid and d.deptype = 'e')
|
|
48
|
+
union all
|
|
49
|
+
select 'schema', n.nspname::text, null, null, null, coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner))
|
|
50
|
+
from pg_catalog.pg_namespace n
|
|
51
|
+
where n.nspname = any($1::text[])
|
|
52
|
+
)
|
|
53
|
+
select o.kind, o.schema, o.name, o.column_name, o.args, r.role,
|
|
54
|
+
-- distinct:同一权限可以由几个授权人各给一次,ACL 里就有几条
|
|
55
|
+
pg_catalog.array_agg(distinct x.privilege_type::text order by x.privilege_type::text) filter (where r.role is not null) as privileges
|
|
56
|
+
from objects o
|
|
57
|
+
left join lateral pg_catalog.aclexplode(o.acl) x on true
|
|
58
|
+
left join api_roles r on r.oid = x.grantee
|
|
59
|
+
group by 1, 2, 3, 4, 5, 6
|
|
60
|
+
order by 1, 2, 3, 4, 5, 6`;
|
|
61
|
+
function objectKey(o) {
|
|
62
|
+
return JSON.stringify([o.kind, o.schema, o.name ?? null, o.column ?? null, o.args ?? null]);
|
|
63
|
+
}
|
|
64
|
+
/** 在已开的事务里调用:search_path 必须为空(见 CATALOG_OBJECTS_SQL)。 */
|
|
65
|
+
async function catalogObjects(client, schemas) {
|
|
66
|
+
const res = await client.query(CATALOG_OBJECTS_SQL, [schemas, [...API_ROLES]]);
|
|
67
|
+
const objects = new Map();
|
|
68
|
+
for (const row of res.rows) {
|
|
69
|
+
const object = {
|
|
70
|
+
kind: row.kind,
|
|
71
|
+
schema: row.schema,
|
|
72
|
+
...(row.name !== null ? { name: row.name } : {}),
|
|
73
|
+
...(row.column_name !== null ? { column: row.column_name } : {}),
|
|
74
|
+
...(row.args !== null ? { args: row.args } : {}),
|
|
75
|
+
privileges: {},
|
|
76
|
+
};
|
|
77
|
+
const key = objectKey(object);
|
|
78
|
+
const existing = objects.get(key) ?? object;
|
|
79
|
+
objects.set(key, existing);
|
|
80
|
+
if (row.role && row.privileges?.length)
|
|
81
|
+
existing.privileges[row.role] = row.privileges;
|
|
82
|
+
}
|
|
83
|
+
// 列级授权只给别的角色时,这一列对我们没有意义
|
|
84
|
+
return [...objects.values()].filter((o) => o.kind !== "column" || Object.keys(o.privileges).length > 0);
|
|
85
|
+
}
|
|
86
|
+
async function withEmptySearchPath(client, work) {
|
|
87
|
+
await client.query("begin");
|
|
88
|
+
try {
|
|
89
|
+
await client.query("set local search_path = ''");
|
|
90
|
+
const result = await work();
|
|
91
|
+
await client.query("commit");
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
await client.query("rollback").catch(() => { });
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** 备份端:读源库里这几个 schema 下每个对象给 PUBLIC 和 API 角色的授权。 */
|
|
100
|
+
export async function captureGrants(client, schemas) {
|
|
101
|
+
return withEmptySearchPath(client, () => catalogObjects(client, schemas));
|
|
102
|
+
}
|
|
103
|
+
function quoteIdent(name) {
|
|
104
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
105
|
+
}
|
|
106
|
+
function qualifiedName(o) {
|
|
107
|
+
return `${quoteIdent(o.schema)}.${quoteIdent(o.name ?? "")}`;
|
|
108
|
+
}
|
|
109
|
+
function objectClause(o) {
|
|
110
|
+
switch (o.kind) {
|
|
111
|
+
case "schema":
|
|
112
|
+
return `schema ${quoteIdent(o.schema)}`;
|
|
113
|
+
case "sequence":
|
|
114
|
+
return `sequence ${qualifiedName(o)}`;
|
|
115
|
+
case "routine":
|
|
116
|
+
// ROUTINE 同时认函数、聚合、过程(PG11+)
|
|
117
|
+
return `routine ${qualifiedName(o)}(${o.args ?? ""})`;
|
|
118
|
+
default:
|
|
119
|
+
return `table ${qualifiedName(o)}`;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function roleName(role) {
|
|
123
|
+
return role === "PUBLIC" ? "public" : quoteIdent(role);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* 把一组对象的授权写成 SQL:schema、表、序列、函数先清掉这几个角色的全部权限再照记录授,
|
|
127
|
+
* 列级授权放在最后(清表权限会连带清掉列权限)。schema 也要清:源库可能靠不给 USAGE 把整个
|
|
128
|
+
* schema 关起来,目标上的 public 却是 Supabase 默认开放的。
|
|
129
|
+
* roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN。
|
|
130
|
+
*/
|
|
131
|
+
export function grantStatements(objects, opts) {
|
|
132
|
+
const roles = GRANT_ROLES.filter((role) => opts.roles.includes(role));
|
|
133
|
+
const revokeFrom = roles.map(roleName).join(", ");
|
|
134
|
+
const statements = [];
|
|
135
|
+
const columns = [];
|
|
136
|
+
for (const o of objects) {
|
|
137
|
+
if (o.kind !== "column") {
|
|
138
|
+
statements.push(`revoke all on ${objectClause(o)} from ${revokeFrom}`);
|
|
139
|
+
}
|
|
140
|
+
for (const role of roles) {
|
|
141
|
+
const privileges = (o.privileges[role] ?? []).filter((p) => GRANT_PRIVILEGES.includes(p) && (opts.maintain || p !== "MAINTAIN"));
|
|
142
|
+
if (!privileges.length)
|
|
143
|
+
continue;
|
|
144
|
+
if (o.kind === "column") {
|
|
145
|
+
const column = quoteIdent(o.column ?? "");
|
|
146
|
+
columns.push(`grant ${privileges.map((p) => `${p.toLowerCase()} (${column})`).join(", ")} on table ${qualifiedName(o)} to ${roleName(role)}`);
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
statements.push(`grant ${privileges.map((p) => p.toLowerCase()).join(", ")} on ${objectClause(o)} to ${roleName(role)}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return [...statements, ...columns];
|
|
154
|
+
}
|
|
155
|
+
/** Supabase 以前给 public 里新对象的默认授权(pg_default_acl 实测:表 arwdDxtm、序列 rwU、函数 X)。 */
|
|
156
|
+
function legacyDefaultGrants(objects) {
|
|
157
|
+
const all = (privileges) => Object.fromEntries(API_ROLES.map((role) => [role, privileges]));
|
|
158
|
+
return objects
|
|
159
|
+
.filter((o) => o.schema === "public" && (o.kind === "table" || o.kind === "sequence" || o.kind === "routine"))
|
|
160
|
+
.map((o) => ({
|
|
161
|
+
...o,
|
|
162
|
+
privileges: {
|
|
163
|
+
...o.privileges,
|
|
164
|
+
...all(o.kind === "table"
|
|
165
|
+
? ["SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER", "MAINTAIN"]
|
|
166
|
+
: o.kind === "sequence"
|
|
167
|
+
? ["SELECT", "UPDATE", "USAGE"]
|
|
168
|
+
: ["EXECUTE"]),
|
|
169
|
+
},
|
|
170
|
+
}));
|
|
171
|
+
}
|
|
172
|
+
// 一次发太多条会让单条查询文本过大;几百条一批足够快
|
|
173
|
+
const STATEMENTS_PER_QUERY = 200;
|
|
174
|
+
/**
|
|
175
|
+
* 恢复端:在恢复出来的对象上照记录重建授权,一个事务内完成,提交前回读目录核对。
|
|
176
|
+
* 目标上的对象以目标目录为准:记录里有、目标上没有的(沙箱跳过的托管对象)略过;
|
|
177
|
+
* 目标上有、记录里没有的(备份转储完之后才建的)按"没有授权"处理,只清不授。
|
|
178
|
+
* recorded 为 undefined = 旧快照:public 里的表、序列、函数在目标已有授权之上补齐 Supabase 以前的默认授权。
|
|
179
|
+
*/
|
|
180
|
+
export async function restoreGrants(client, opts) {
|
|
181
|
+
return withEmptySearchPath(client, async () => {
|
|
182
|
+
const target = await targetFacts(client);
|
|
183
|
+
const onTarget = await catalogObjects(client, opts.schemas);
|
|
184
|
+
let planned;
|
|
185
|
+
if (opts.recorded === undefined) {
|
|
186
|
+
planned = legacyDefaultGrants(onTarget);
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
const recorded = new Map(opts.recorded.map((o) => [objectKey(o), o]));
|
|
190
|
+
// 授权在转储之后才读,转储期间新加的列不在归档里:只处理目标上真有的列
|
|
191
|
+
const columns = await targetColumns(client, opts.schemas);
|
|
192
|
+
planned = [
|
|
193
|
+
// 目标上的 schema、表、序列、函数都要过一遍:记录里没有的按"源库没给授权"处理
|
|
194
|
+
...onTarget
|
|
195
|
+
.filter((o) => o.kind !== "column")
|
|
196
|
+
.map((o) => ({ ...o, privileges: recorded.get(objectKey(o))?.privileges ?? {} })),
|
|
197
|
+
...opts.recorded.filter((o) => o.kind === "column" && columns.has(objectKey(o))),
|
|
198
|
+
];
|
|
199
|
+
}
|
|
200
|
+
await execute(client, grantStatements(planned, target));
|
|
201
|
+
await assertGrantsTookEffect(client, opts.schemas, planned, target);
|
|
202
|
+
return { mode: opts.recorded === undefined ? "legacy-defaults" : "recorded", objects: planned.length };
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* 补授权失败时的退路(只用于真实目标):把恢复出来的表、序列、函数上这几个角色的权限全部收走。
|
|
207
|
+
* 应用会 42501,但源库关着的东西不会因为目标的默认授权而开着。schema 不动,免得连带目标上别的东西。
|
|
208
|
+
*/
|
|
209
|
+
export async function revokeApiAccess(client, schemas) {
|
|
210
|
+
await withEmptySearchPath(client, async () => {
|
|
211
|
+
const target = await targetFacts(client);
|
|
212
|
+
const planned = (await catalogObjects(client, schemas))
|
|
213
|
+
.filter((o) => o.kind === "table" || o.kind === "sequence" || o.kind === "routine")
|
|
214
|
+
.map((o) => ({ ...o, privileges: {} }));
|
|
215
|
+
await execute(client, grantStatements(planned, target));
|
|
216
|
+
await assertGrantsTookEffect(client, schemas, planned, target);
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
async function targetColumns(client, schemas) {
|
|
220
|
+
const res = await client.query(`select n.nspname::text as schema, c.relname::text as name, a.attname::text as column_name
|
|
221
|
+
from pg_catalog.pg_attribute a
|
|
222
|
+
join pg_catalog.pg_class c on c.oid = a.attrelid
|
|
223
|
+
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
|
224
|
+
where n.nspname = any($1::text[]) and c.relkind in ('r', 'p', 'v', 'm', 'f')
|
|
225
|
+
and a.attnum > 0 and not a.attisdropped`, [schemas]);
|
|
226
|
+
return new Set(res.rows.map((r) => objectKey({ kind: "column", schema: r.schema, name: r.name, column: r.column_name })));
|
|
227
|
+
}
|
|
228
|
+
async function targetFacts(client) {
|
|
229
|
+
const version = await client.query("show server_version_num");
|
|
230
|
+
const roleRows = await client.query("select rolname from pg_catalog.pg_roles where rolname = any($1::text[])", [[...API_ROLES]]);
|
|
231
|
+
return {
|
|
232
|
+
roles: ["PUBLIC", ...roleRows.rows.map((r) => r.rolname)],
|
|
233
|
+
maintain: Number(version.rows[0].server_version_num) >= 170000,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
async function execute(client, statements) {
|
|
237
|
+
for (let i = 0; i < statements.length; i += STATEMENTS_PER_QUERY) {
|
|
238
|
+
await client.query(statements.slice(i, i + STATEMENTS_PER_QUERY).join(";\n"));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function effectivePrivileges(o, role, target) {
|
|
242
|
+
return (o.privileges[role] ?? [])
|
|
243
|
+
.filter((p) => GRANT_PRIVILEGES.includes(p) && (target.maintain || p !== "MAINTAIN"))
|
|
244
|
+
.sort()
|
|
245
|
+
.join(",");
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* GRANT/REVOKE 遇到不归自己管的对象只给 WARNING、什么也不做(比如恢复用的角色不是属主)。
|
|
249
|
+
* 回读目录逐个对象比,对不上就报错,让事务回滚、调用方走退路,不把"以为设好了"当成功。
|
|
250
|
+
*/
|
|
251
|
+
async function assertGrantsTookEffect(client, schemas, planned, target) {
|
|
252
|
+
const actual = new Map((await catalogObjects(client, schemas)).map((o) => [objectKey(o), o]));
|
|
253
|
+
const off = planned.filter((o) => {
|
|
254
|
+
const now = actual.get(objectKey(o)) ?? { ...o, privileges: {} };
|
|
255
|
+
return target.roles.some((role) => effectivePrivileges(o, role, target) !== effectivePrivileges(now, role, target));
|
|
256
|
+
});
|
|
257
|
+
if (!off.length)
|
|
258
|
+
return;
|
|
259
|
+
const named = off
|
|
260
|
+
.slice(0, 3)
|
|
261
|
+
.map((o) => `${o.kind} ${o.schema}${o.name ? `.${o.name}` : ""}${o.column ? `.${o.column}` : ""}`)
|
|
262
|
+
.join(", ");
|
|
263
|
+
throw new Error(`grants didn't take effect on ${off.length} object(s) (${named}${off.length > 3 ? ", …" : ""}); ` +
|
|
264
|
+
`the role running the restore probably doesn't own them`);
|
|
265
|
+
}
|
|
266
|
+
/** 演练和恢复报告里的一行。旧快照那句按场合说:恢复是已经开放了要收回,演练是提醒真恢复时会这样。 */
|
|
267
|
+
export function grantsCheck(outcome, context) {
|
|
268
|
+
const legacyScope = `Supabase's old default access to the ${outcome.objects} table(s), sequence(s) and function(s) in public`;
|
|
269
|
+
return {
|
|
270
|
+
name: "API grants",
|
|
271
|
+
pass: true,
|
|
272
|
+
detail: outcome.mode === "recorded"
|
|
273
|
+
? `access for anon, authenticated and service_role set as it was at backup time on ${outcome.objects} object(s)`
|
|
274
|
+
: context === "restore"
|
|
275
|
+
? `this snapshot was taken before BackupDrill recorded grants, so anon, authenticated and service_role got ` +
|
|
276
|
+
`${legacyScope}. Revoke it on anything you kept private`
|
|
277
|
+
: `this snapshot was taken before BackupDrill recorded grants, so restoring it gives anon, authenticated and ` +
|
|
278
|
+
`service_role ${legacyScope}. Newer backups record the grants`,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用)。有记录就逐个对象照记录重建,
|
|
283
|
+
* 和 restoreGrants 同一套语句;旧快照没有记录,给 Supabase 以前的默认授权。
|
|
284
|
+
* MAINTAIN 只会出现在 PG17+ 源库的记录里,而恢复目标的版本不低于源库,所以照写。
|
|
285
|
+
*/
|
|
286
|
+
export function recoveryGrantsSql(grants) {
|
|
287
|
+
if (grants === undefined) {
|
|
288
|
+
return [
|
|
289
|
+
"grant all on all tables in schema public to anon, authenticated, service_role;",
|
|
290
|
+
"grant all on all sequences in schema public to anon, authenticated, service_role;",
|
|
291
|
+
"grant execute on all functions in schema public to anon, authenticated, service_role;",
|
|
292
|
+
].join("\n");
|
|
293
|
+
}
|
|
294
|
+
const statements = grantStatements(grants, { roles: GRANT_ROLES, maintain: true });
|
|
295
|
+
return statements.length ? statements.map((s) => `${s};`).join("\n") : "-- (nothing to grant in this snapshot)";
|
|
296
|
+
}
|
package/dist/lib.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export { runBackup } from "./backup.js";
|
|
|
2
2
|
export { SUPABASE_ROOT_CA, pgConnectOptions, PG_CLIENT_OPTIONS, normalizeConnectionTarget } from "./supabase-ca.js";
|
|
3
3
|
export { runDrill, drillDump } from "./drill.js";
|
|
4
4
|
export { runRestore } from "./restore.js";
|
|
5
|
+
export { recoveryGrantsSql } from "./grants.js";
|
|
5
6
|
export { projectRefOf, assertNoHostOverride, libpqChildEnv } from "./restore-engine.js";
|
|
6
7
|
export { sameDatabaseTarget } from "./restore.js";
|
|
7
8
|
export { runEstimate, project } from "./estimate.js";
|
|
@@ -11,6 +12,7 @@ export { s3SnapshotStore } from "./snapshot-store.js";
|
|
|
11
12
|
export type { SnapshotStore, SnapshotWriter, SnapshotReader, DumpUpload, StorageFilesLocation, } from "./snapshot-store.js";
|
|
12
13
|
export type { BackupConfig, LoadedBackupConfig, StorageConfig, SupabaseStorageConfig, } from "./config.js";
|
|
13
14
|
export type { BucketAttrs, ExtensionInfo, Manifest, StorageFile, TableStat } from "./manifest.js";
|
|
15
|
+
export type { GrantedObject, GrantRestore } from "./grants.js";
|
|
14
16
|
export type { DrillReport, DrillCheck, DrillSupervision, DrillPhase } from "./drill.js";
|
|
15
17
|
export type { OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
16
18
|
export type { RestoreResult } from "./restore.js";
|
package/dist/lib.js
CHANGED
|
@@ -6,6 +6,8 @@ export { runBackup } from "./backup.js";
|
|
|
6
6
|
export { SUPABASE_ROOT_CA, pgConnectOptions, PG_CLIENT_OPTIONS, normalizeConnectionTarget } from "./supabase-ca.js";
|
|
7
7
|
export { runDrill, drillDump } from "./drill.js";
|
|
8
8
|
export { runRestore } from "./restore.js";
|
|
9
|
+
// RECOVERY.md 的授权那一步:worker 的 Drive 版手册和这里的 S3 版用同一份 SQL
|
|
10
|
+
export { recoveryGrantsSql } from "./grants.js";
|
|
9
11
|
// 身份判定三件套对外导出:托管 worker 用它们与 app 侧 shared 的副本做同规则回归(交叉审查)
|
|
10
12
|
export { projectRefOf, assertNoHostOverride, libpqChildEnv } from "./restore-engine.js";
|
|
11
13
|
export { sameDatabaseTarget } from "./restore.js";
|
package/dist/manifest.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type GrantedObject } from "./grants.js";
|
|
1
2
|
/**
|
|
2
3
|
* manifest.json —— 每次快照的自描述清单。
|
|
3
4
|
* 云版演练靠它做校验(表数量、行数对比、体积异常告警);开源侧至少让用户能核对
|
|
@@ -50,6 +51,8 @@ export interface ExtensionInfo {
|
|
|
50
51
|
* - 2(恢复闭环 PRD §5.1):storage 增加 buckets 属性清单(public/大小/MIME 限制),
|
|
51
52
|
* files 增加 contentType/cacheControl/metadata 等恢复所需元数据;tables 预留
|
|
52
53
|
* 验证升级字段(本期不生成)。全部为**可加字段**——v2 读取端兼容 v1 快照。
|
|
54
|
+
* - (仍是 2)2.9.0 加 database.grants:可加字段,旧读取端忽略它、照旧恢复,不升版本,
|
|
55
|
+
* 免得还没升级的 CLI 和 worker 拒读新快照。
|
|
53
56
|
*/
|
|
54
57
|
export declare const MANIFEST_SCHEMA_VERSION = 2;
|
|
55
58
|
export interface Manifest {
|
|
@@ -67,6 +70,7 @@ export interface Manifest {
|
|
|
67
70
|
estimatedRowTotal: number;
|
|
68
71
|
tables: TableStat[];
|
|
69
72
|
extensions?: ExtensionInfo[];
|
|
73
|
+
grants?: GrantedObject[];
|
|
70
74
|
};
|
|
71
75
|
dump: {
|
|
72
76
|
key: string;
|
package/dist/manifest.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { GRANT_PRIVILEGES, GRANT_ROLES, GRANTED_OBJECT_KINDS } from "./grants.js";
|
|
1
2
|
/**
|
|
2
3
|
* manifest.json 的格式版本。**这是留在客户桶里、可能躺很多年的持久产物**——将来改结构时,
|
|
3
4
|
* 读取端要靠它分支判断,而不是去猜 toolVersion。
|
|
@@ -12,6 +13,8 @@
|
|
|
12
13
|
* - 2(恢复闭环 PRD §5.1):storage 增加 buckets 属性清单(public/大小/MIME 限制),
|
|
13
14
|
* files 增加 contentType/cacheControl/metadata 等恢复所需元数据;tables 预留
|
|
14
15
|
* 验证升级字段(本期不生成)。全部为**可加字段**——v2 读取端兼容 v1 快照。
|
|
16
|
+
* - (仍是 2)2.9.0 加 database.grants:可加字段,旧读取端忽略它、照旧恢复,不升版本,
|
|
17
|
+
* 免得还没升级的 CLI 和 worker 拒读新快照。
|
|
15
18
|
*/
|
|
16
19
|
export const MANIFEST_SCHEMA_VERSION = 2;
|
|
17
20
|
/** 结构断言失败时的统一出错口径:说清哪个字段坏了,让"桶里的 manifest 被篡改/截断"可定位。 */
|
|
@@ -28,6 +31,29 @@ function optionalString(value, what) {
|
|
|
28
31
|
if (value !== undefined && typeof value !== "string")
|
|
29
32
|
malformed(what);
|
|
30
33
|
}
|
|
34
|
+
// 名字会拼进 GRANT(标识符一律加引号);函数的参数表只用来和目标目录比对,SQL 里用的是目标目录自己的
|
|
35
|
+
function assertGrantedObject(g) {
|
|
36
|
+
const what = "database.grants[]";
|
|
37
|
+
if (typeof g !== "object" || g === null)
|
|
38
|
+
malformed(what);
|
|
39
|
+
if (!GRANTED_OBJECT_KINDS.includes(g.kind) || typeof g.schema !== "string" || !g.schema)
|
|
40
|
+
malformed(what);
|
|
41
|
+
if (g.kind !== "schema" && (typeof g.name !== "string" || !g.name))
|
|
42
|
+
malformed(`${what}.name`);
|
|
43
|
+
if (g.kind === "column" && (typeof g.column !== "string" || !g.column))
|
|
44
|
+
malformed(`${what}.column`);
|
|
45
|
+
if (g.kind === "routine" && typeof g.args !== "string")
|
|
46
|
+
malformed(`${what}.args`);
|
|
47
|
+
if (typeof g.privileges !== "object" || g.privileges === null || Array.isArray(g.privileges))
|
|
48
|
+
malformed(`${what}.privileges`);
|
|
49
|
+
for (const [role, privileges] of Object.entries(g.privileges)) {
|
|
50
|
+
if (!GRANT_ROLES.includes(role))
|
|
51
|
+
malformed(`${what}.privileges (unknown role)`);
|
|
52
|
+
if (!Array.isArray(privileges) || privileges.some((p) => !GRANT_PRIVILEGES.includes(p))) {
|
|
53
|
+
malformed(`${what}.privileges (unknown privilege)`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
31
57
|
function assertManifestShape(m) {
|
|
32
58
|
// ref 驱动同源安全门:malformed 值会被当"身份已知"却永远匹配不上 = 保护静默失效
|
|
33
59
|
if (m.sourceProjectRef !== undefined && !/^[a-z0-9]{16,}$/.test(m.sourceProjectRef)) {
|
|
@@ -66,6 +92,12 @@ function assertManifestShape(m) {
|
|
|
66
92
|
}
|
|
67
93
|
}
|
|
68
94
|
}
|
|
95
|
+
if (m.database.grants !== undefined) {
|
|
96
|
+
if (!Array.isArray(m.database.grants))
|
|
97
|
+
malformed("database.grants");
|
|
98
|
+
for (const g of m.database.grants)
|
|
99
|
+
assertGrantedObject(g);
|
|
100
|
+
}
|
|
69
101
|
if (typeof m.database.tableCount !== "number")
|
|
70
102
|
malformed("database.tableCount");
|
|
71
103
|
if (!Array.isArray(m.database.tables))
|
|
@@ -49,8 +49,17 @@ export declare const COMPARISON_PLAN_SQL = "\n select n.nspname as schema, o.op
|
|
|
49
49
|
* MATCH SIMPLE 只查引用列全非空的行;MATCH FULL 另算"部分为空"的行。
|
|
50
50
|
*/
|
|
51
51
|
export declare function orphanCountSql(fk: ForeignKeyDef, plan: ComparisonPlan): string;
|
|
52
|
-
/**
|
|
52
|
+
/** 一条孤儿外键给人看的说法。 */
|
|
53
53
|
export declare function describeOrphanedForeignKey(orphaned: OrphanedForeignKey): string;
|
|
54
|
+
/**
|
|
55
|
+
* 演练和真实恢复报告里共用的一项:算通过。我们管的是备份完整、能完整恢复;源库里本来就有的这些行
|
|
56
|
+
* 原样回来,不让用户去改自己的数据(创始人 2026-10-31)。
|
|
57
|
+
*/
|
|
58
|
+
export declare function orphanedForeignKeysCheck(orphaned: OrphanedForeignKey[]): {
|
|
59
|
+
name: string;
|
|
60
|
+
pass: boolean;
|
|
61
|
+
detail: string;
|
|
62
|
+
};
|
|
54
63
|
export interface AddForeignKeysResult {
|
|
55
64
|
orphaned: OrphanedForeignKey[];
|
|
56
65
|
/** 沙箱托管豁免命中数(与 classifyBlocks 同口径) */
|
|
@@ -68,7 +68,7 @@ export function orphanCountSql(fk, plan) {
|
|
|
68
68
|
const where = fk.matchFull ? `(${anySet}) and (not (${allSet}) or ${missing})` : `${allSet} and ${missing}`;
|
|
69
69
|
return `select count(*)::bigint as n from only ${quoteIdent(fk.table.schema)}.${quoteIdent(fk.table.name)} c where ${where}`;
|
|
70
70
|
}
|
|
71
|
-
/**
|
|
71
|
+
/** 一条孤儿外键给人看的说法。 */
|
|
72
72
|
export function describeOrphanedForeignKey(orphaned) {
|
|
73
73
|
const rows = orphaned.orphanRows === null ? "Some rows" : `${orphaned.orphanRows} row(s)`;
|
|
74
74
|
// 不说"指向不存在的行":MATCH FULL 下部分为空的行也算违反,它们未必缺对应的行(文案审查)
|
|
@@ -85,6 +85,19 @@ async function hasGeneratedKeyColumn(client, fk) {
|
|
|
85
85
|
) as generated`, [qualified(fk.table), fk.columns, qualified(fk.references), fk.referencedColumns]);
|
|
86
86
|
return rows[0].generated;
|
|
87
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* 演练和真实恢复报告里共用的一项:算通过。我们管的是备份完整、能完整恢复;源库里本来就有的这些行
|
|
90
|
+
* 原样回来,不让用户去改自己的数据(创始人 2026-10-31)。
|
|
91
|
+
*/
|
|
92
|
+
export function orphanedForeignKeysCheck(orphaned) {
|
|
93
|
+
return {
|
|
94
|
+
name: "foreign keys",
|
|
95
|
+
pass: true,
|
|
96
|
+
detail: `${orphaned.length} added as NOT VALID: ${orphaned.map(describeOrphanedForeignKey).join("; ")}. ` +
|
|
97
|
+
`Those rows were already in the database when it was backed up and are restored as they are. ` +
|
|
98
|
+
`New writes are still checked.`,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
88
101
|
/**
|
|
89
102
|
* 在一个事务里逐条加外键,每条一个 savepoint。23503 → 改加 NOT VALID 并数孤儿行。
|
|
90
103
|
* 其余错误:stopOnError(真实目标)= 回滚整个事务并抛出;否则(沙箱)按 allow 分类后继续。
|
package/dist/recovery-doc.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { recoveryGrantsSql } from "./grants.js";
|
|
1
2
|
function quoteSqlIdent(name) {
|
|
2
3
|
return `"${name.replace(/"/g, '""')}"`;
|
|
3
4
|
}
|
|
@@ -104,9 +105,21 @@ unset PGPASSWORD
|
|
|
104
105
|
|
|
105
106
|
One error is expected and harmless: \`schema "public" already exists\` (the
|
|
106
107
|
target always has it). A foreign key error mentioning \`auth.users\` means the
|
|
107
|
-
Auth users were not copied in first (see "Not covered" above). Do **not** use \`--clean\` against a Supabase project
|
|
108
|
-
|
|
109
|
-
|
|
108
|
+
Auth users were not copied in first (see "Not covered" above). Do **not** use \`--clean\` against a Supabase project:
|
|
109
|
+
it drops and recreates \`public\`, and the grants Supabase put on it go with it.
|
|
110
|
+
|
|
111
|
+
5. Set the grants for \`anon\`, \`authenticated\` and \`service_role\`. The dump
|
|
112
|
+
carries none. With Supabase's new defaults, supabase-js requests to restored
|
|
113
|
+
tables in \`public\` fail with \`42501 permission denied\` until you grant access. ${db.grants
|
|
114
|
+
? `These statements put back exactly what the source had at backup time (also in
|
|
115
|
+
manifest.json under \`database.grants\`):`
|
|
116
|
+
: `This snapshot was taken before BackupDrill recorded grants. The statements below
|
|
117
|
+
give the three roles Supabase's old default access to everything in \`public\`;
|
|
118
|
+
afterwards, revoke it on any table you had kept private:`}
|
|
119
|
+
|
|
120
|
+
\`\`\`sql
|
|
121
|
+
${recoveryGrantsSql(db.grants)}
|
|
122
|
+
\`\`\`
|
|
110
123
|
|
|
111
124
|
## Restore Storage files
|
|
112
125
|
|
|
@@ -128,7 +141,7 @@ referenced outside the snapshot (such as \`auth.users\`) are on the target, inst
|
|
|
128
141
|
the extensions, restores the database in a single transaction through the same
|
|
129
142
|
engine the weekly drills use (an SQL error rolls it back and the extensions stay
|
|
130
143
|
installed; if the connection drops while it commits, check the target before
|
|
131
|
-
retrying), verifies table counts and row presence afterwards, then rebuilds buckets, uploads the
|
|
144
|
+
retrying), sets the grants above, verifies table counts and row presence afterwards, then rebuilds buckets, uploads the
|
|
132
145
|
Storage files back and reconciles every one against the target.
|
|
133
146
|
|
|
134
147
|
More: https://backupdrill.com/docs/restore
|
package/dist/restore-engine.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Client } from "pg";
|
|
2
2
|
import type { ExtensionInfo } from "./manifest.js";
|
|
3
3
|
import { type OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
4
|
+
import { type GrantRestore, type GrantedObject } from "./grants.js";
|
|
4
5
|
export type RestoreTargetKind = "sandbox" | "supabase";
|
|
5
6
|
/** 主机名规范化:先按驱动语义百分号解码(pg-connection-string / libpq 都会解码主机名,
|
|
6
7
|
* `supabase%2Ecom` 在驱动眼里就是 supabase.com),再剥掉合法的 DNS 根点(db.x.supabase.co. ≡
|
|
@@ -35,16 +36,22 @@ export interface EngineResult {
|
|
|
35
36
|
preData: ClassifiedPass;
|
|
36
37
|
postData: ClassifiedPass;
|
|
37
38
|
ok: boolean;
|
|
38
|
-
/** 因源库自带孤儿行而以 NOT VALID 建成的外键(见 orphaned-foreign-keys.ts)
|
|
39
|
+
/** 因源库自带孤儿行而以 NOT VALID 建成的外键(见 orphaned-foreign-keys.ts);沙箱和真实目标一样,不算失败 */
|
|
39
40
|
orphanedForeignKeys?: OrphanedForeignKey[];
|
|
41
|
+
/** 授权重建的结果(grants.ts);恢复没走到这一步时不存在 */
|
|
42
|
+
grants?: GrantRestore;
|
|
40
43
|
/**
|
|
41
|
-
* 真实目标:失败发生在主事务提交之后(
|
|
44
|
+
* 真实目标:失败发生在主事务提交之后(授权或外键那一步),表和数据已经在目标上。
|
|
42
45
|
* 调用方据此如实说明,不能再说"已整体回滚"。
|
|
43
46
|
*/
|
|
44
47
|
committed?: boolean;
|
|
45
48
|
}
|
|
46
|
-
/**
|
|
47
|
-
export
|
|
49
|
+
/** 恢复完要重建授权的范围与依据:manifest.database.schemas 和 manifest.database.grants。 */
|
|
50
|
+
export interface GrantsToRestore {
|
|
51
|
+
schemas: string[];
|
|
52
|
+
/** undefined = 旧快照没有记录,按 Supabase 以前的默认授权补 public */
|
|
53
|
+
recorded: GrantedObject[] | undefined;
|
|
54
|
+
}
|
|
48
55
|
/**
|
|
49
56
|
* 新版 pg_restore 的脚本首尾各有一条 psql 元命令(\restrict <key> / \unrestrict <key>),node-pg 执行不了。
|
|
50
57
|
* 只认位置:开头那条是第一行非空、非 -- 注释的行,结尾那条是最后一行非空行。注释正文是字符串,
|
|
@@ -141,7 +148,7 @@ inTransaction?: Client): Promise<string[]>;
|
|
|
141
148
|
* auth.uid() → uuid、auth.jwt() → jsonb、auth.role() → text、auth.email() → text,
|
|
142
149
|
* 全部返回 null(恢复过程中不会真调它们:COPY 不求值列默认,策略/函数体不执行);
|
|
143
150
|
* 角色 anon / authenticated / service_role(nologin):RLS 策略的 `to authenticated`
|
|
144
|
-
*
|
|
151
|
+
* 要它们在场才能建;恢复完重建授权(grants.ts)也要它们,演练因此和真实恢复走同一段。
|
|
145
152
|
* 刻意不建 auth.users 之类的表:空的 auth.users 会让 FK 校验在 post-data 真失败,
|
|
146
153
|
* 比"缺表跳过"更糟。FK → auth.users 仍按 SANDBOX_MANAGED_ERROR 的 relation 形态跳过。
|
|
147
154
|
*
|
|
@@ -237,6 +244,8 @@ export declare function restoreDatabaseArtifact(opts: {
|
|
|
237
244
|
dumpedSchemas?: string[];
|
|
238
245
|
/** pg_restore 并行路数;不传或 ≤1 = 单连接两遍。 */
|
|
239
246
|
jobs?: number;
|
|
247
|
+
/** 恢复完照它重建 PUBLIC 和 API 角色的授权;沙箱和真实目标一样做 */
|
|
248
|
+
grants: GrantsToRestore;
|
|
240
249
|
}): Promise<EngineResult>;
|
|
241
250
|
/**
|
|
242
251
|
* 逐块读 `pg_restore --data-only -f -` 的输出,判断某张表的 COPY 段有没有数据行。
|
package/dist/restore-engine.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
// R0 spike 的三条实证直接塑造了这里的形状:
|
|
5
5
|
// 1. 裸退出码在真实目标上永远不干净 → 成功判定 = 零未分类错误(版本化 allowlist);
|
|
6
6
|
// 2. 不用 --clean:与"只允许空目标"(D5)冲突、制造伪错,且在真实 Supabase 上
|
|
7
|
-
// DROP/CREATE public 会抹掉 anon/authenticated
|
|
8
|
-
//
|
|
7
|
+
// DROP/CREATE public 会抹掉 anon/authenticated 的默认授权,恢复出的 API 直接 401;
|
|
8
|
+
// (转储不带授权,表的授权在恢复完由 grants.ts 照快照记录补回,见那里的头注)
|
|
9
9
|
// 3. dump 自带 CREATE SCHEMA,而目标(新容器或 Supabase)恒有同名 schema →
|
|
10
10
|
// pre-data 阶段的 schema "already exists" 是两类目标共同的预期冲突。
|
|
11
11
|
//
|
|
@@ -19,8 +19,9 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
|
19
19
|
import { tmpdir } from "node:os";
|
|
20
20
|
import { join } from "node:path";
|
|
21
21
|
import { MAX_COPY_HEADER, parseCopyHeader, parseCreatedTables, parseCreateSchemas, parseForeignKeys, } from "./dump-sql.js";
|
|
22
|
-
import { addForeignKeys,
|
|
22
|
+
import { addForeignKeys, fullyDumpedTableEntries, isDeferrableForeignKey, tableKey, } from "./orphaned-foreign-keys.js";
|
|
23
23
|
import { resolvePgRestoreBin } from "./pgbin.js";
|
|
24
|
+
import { restoreGrants, revokeApiAccess } from "./grants.js";
|
|
24
25
|
import { dumpUrlFor, connectPg, isSupabaseHost } from "./supabase-ca.js";
|
|
25
26
|
import { interrupted, onInterrupt, stopOnInterrupt } from "./interrupt.js";
|
|
26
27
|
/** 主机名规范化:先按驱动语义百分号解码(pg-connection-string / libpq 都会解码主机名,
|
|
@@ -100,10 +101,33 @@ export function refFromStorageEndpoint(endpoint) {
|
|
|
100
101
|
return null;
|
|
101
102
|
}
|
|
102
103
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
104
|
+
async function applyGrants(connString, grants) {
|
|
105
|
+
const client = await connectPg(connString);
|
|
106
|
+
try {
|
|
107
|
+
return await restoreGrants(client, grants);
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
await client.end();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* 真实目标补授权失败后的退路:数据已经提交,目标的默认授权可能把源库关着的表开着。先把这几个角色的
|
|
115
|
+
* 权限全部收走,宁可应用 42501,也不让该关的开着;返回给用户看的一句话。
|
|
116
|
+
*/
|
|
117
|
+
async function lockDownAfterGrantFailure(connString, schemas) {
|
|
118
|
+
try {
|
|
119
|
+
const client = await connectPg(connString);
|
|
120
|
+
try {
|
|
121
|
+
await revokeApiAccess(client, schemas);
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
await client.end();
|
|
125
|
+
}
|
|
126
|
+
return "anon, authenticated and service_role were then given no access to the restored objects, so nothing is open that shouldn't be; grant what your app needs by hand";
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
return `taking access away from anon, authenticated and service_role failed as well (${error.message}): the target's default grants still apply to the restored objects, check them before the app goes live`;
|
|
130
|
+
}
|
|
107
131
|
}
|
|
108
132
|
/**
|
|
109
133
|
* 从目录条目里挑出交给 addForeignKeys 的外键(isDeferrableForeignKey)。让 pg_restore 把全部外键条目
|
|
@@ -474,7 +498,7 @@ inTransaction) {
|
|
|
474
498
|
* auth.uid() → uuid、auth.jwt() → jsonb、auth.role() → text、auth.email() → text,
|
|
475
499
|
* 全部返回 null(恢复过程中不会真调它们:COPY 不求值列默认,策略/函数体不执行);
|
|
476
500
|
* 角色 anon / authenticated / service_role(nologin):RLS 策略的 `to authenticated`
|
|
477
|
-
*
|
|
501
|
+
* 要它们在场才能建;恢复完重建授权(grants.ts)也要它们,演练因此和真实恢复走同一段。
|
|
478
502
|
* 刻意不建 auth.users 之类的表:空的 auth.users 会让 FK 校验在 post-data 真失败,
|
|
479
503
|
* 比"缺表跳过"更糟。FK → auth.users 仍按 SANDBOX_MANAGED_ERROR 的 relation 形态跳过。
|
|
480
504
|
*
|
|
@@ -752,7 +776,7 @@ function mergePasses(passes) {
|
|
|
752
776
|
* 出别的错时表和数据已经提交(committed);可能的原因只剩连接断开、锁槽这类和数据无关的情况——
|
|
753
777
|
* 被引用的表和唯一索引都已在主事务里建好。
|
|
754
778
|
*/
|
|
755
|
-
async function restoreInOneTransaction(bin, dumpPath, connString, common, env, childOpts) {
|
|
779
|
+
async function restoreInOneTransaction(bin, dumpPath, connString, common, env, childOpts, grantsToRestore) {
|
|
756
780
|
const fail = (failure) => ({ pass: { expectedSkips: 0, failures: [failure] } });
|
|
757
781
|
const listing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
758
782
|
if (listing.code !== 0) {
|
|
@@ -794,8 +818,24 @@ async function restoreInOneTransaction(bin, dumpPath, connString, common, env, c
|
|
|
794
818
|
return fail(`pg_restore was killed by a signal: ${firstRestoreError(run.stderr)}`);
|
|
795
819
|
if (run.code !== 0)
|
|
796
820
|
return fail(firstRestoreError(run.stderr));
|
|
821
|
+
// 授权紧跟着主事务、放在外键前面:提交到这里之间,恢复出来的对象用的是目标的默认授权(pg_restore
|
|
822
|
+
// 在子进程里,插不进它的事务)。外键那一步更可能失败,不能让它拖住授权
|
|
823
|
+
let grants;
|
|
824
|
+
try {
|
|
825
|
+
grants = await applyGrants(connString, grantsToRestore);
|
|
826
|
+
}
|
|
827
|
+
catch (error) {
|
|
828
|
+
const fallback = await lockDownAfterGrantFailure(connString, grantsToRestore.schemas);
|
|
829
|
+
return {
|
|
830
|
+
pass: {
|
|
831
|
+
expectedSkips: 0,
|
|
832
|
+
failures: [`setting grants for the Data API roles failed: ${error.message}; ${fallback}`],
|
|
833
|
+
},
|
|
834
|
+
committed: true,
|
|
835
|
+
};
|
|
836
|
+
}
|
|
797
837
|
if (!deferred.fks.length)
|
|
798
|
-
return { pass: { expectedSkips: 0, failures: [] } };
|
|
838
|
+
return { pass: { expectedSkips: 0, failures: [] }, grants };
|
|
799
839
|
try {
|
|
800
840
|
const client = await connectPg(connString);
|
|
801
841
|
try {
|
|
@@ -804,7 +844,7 @@ async function restoreInOneTransaction(bin, dumpPath, connString, common, env, c
|
|
|
804
844
|
stopOnError: true,
|
|
805
845
|
commentSql: deferred.commentSql,
|
|
806
846
|
});
|
|
807
|
-
return { pass: { expectedSkips: 0, failures: [] }, orphaned: added.orphaned };
|
|
847
|
+
return { pass: { expectedSkips: 0, failures: [] }, orphaned: added.orphaned, grants };
|
|
808
848
|
}
|
|
809
849
|
finally {
|
|
810
850
|
await client.end();
|
|
@@ -814,6 +854,7 @@ async function restoreInOneTransaction(bin, dumpPath, connString, common, env, c
|
|
|
814
854
|
return {
|
|
815
855
|
pass: { expectedSkips: 0, failures: [`adding foreign keys failed: ${error.message}`] },
|
|
816
856
|
committed: true,
|
|
857
|
+
grants,
|
|
817
858
|
};
|
|
818
859
|
}
|
|
819
860
|
}
|
|
@@ -865,13 +906,14 @@ export async function restoreDatabaseArtifact(opts) {
|
|
|
865
906
|
const common = ["--no-owner", "--no-privileges", "--dbname", url, opts.dumpPath];
|
|
866
907
|
const childOpts = { supabaseHost: isSupabaseHost(opts.connString), urlSslMode: urlSslModeOf(url) };
|
|
867
908
|
if (opts.target === "supabase") {
|
|
868
|
-
const { pass, orphaned, committed } = await restoreInOneTransaction(bin, opts.dumpPath, opts.connString, common, env, childOpts);
|
|
909
|
+
const { pass, orphaned, committed, grants } = await restoreInOneTransaction(bin, opts.dumpPath, opts.connString, common, env, childOpts, opts.grants);
|
|
869
910
|
return {
|
|
870
911
|
preData: pass,
|
|
871
912
|
postData: { expectedSkips: 0, failures: [] },
|
|
872
913
|
ok: pass.failures.length === 0,
|
|
873
914
|
orphanedForeignKeys: orphaned,
|
|
874
915
|
committed,
|
|
916
|
+
grants,
|
|
875
917
|
};
|
|
876
918
|
}
|
|
877
919
|
const jobs = Math.max(1, Math.floor(opts.jobs ?? 1));
|
|
@@ -956,19 +998,26 @@ export async function restoreDatabaseArtifact(opts) {
|
|
|
956
998
|
stopOnError: false,
|
|
957
999
|
commentSql: deferred.commentSql,
|
|
958
1000
|
});
|
|
959
|
-
//
|
|
960
|
-
passes.push({
|
|
961
|
-
expectedSkips: added.expectedSkips,
|
|
962
|
-
failures: [...added.failures, ...added.orphaned.map(sandboxOrphanFailure)],
|
|
963
|
-
});
|
|
1001
|
+
// 孤儿外键不算失败:真实恢复同样建成 NOT VALID、数据一行不少,演练报告里另列一项说明
|
|
1002
|
+
passes.push({ expectedSkips: added.expectedSkips, failures: added.failures });
|
|
964
1003
|
orphanedForeignKeys = added.orphaned;
|
|
965
1004
|
}
|
|
966
1005
|
finally {
|
|
967
1006
|
await client.end();
|
|
968
1007
|
}
|
|
969
1008
|
}
|
|
1009
|
+
let grants;
|
|
1010
|
+
try {
|
|
1011
|
+
grants = await applyGrants(opts.connString, opts.grants);
|
|
1012
|
+
}
|
|
1013
|
+
catch (error) {
|
|
1014
|
+
passes.push({
|
|
1015
|
+
expectedSkips: 0,
|
|
1016
|
+
failures: [`setting grants for the Data API roles failed: ${error.message}`],
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
970
1019
|
const postData = mergePasses(passes);
|
|
971
|
-
return { preData, postData, ok: postData.failures.length === 0, orphanedForeignKeys };
|
|
1020
|
+
return { preData, postData, ok: postData.failures.length === 0, orphanedForeignKeys, grants };
|
|
972
1021
|
}
|
|
973
1022
|
finally {
|
|
974
1023
|
await rm(listDir, { recursive: true, force: true });
|
package/dist/restore.js
CHANGED
|
@@ -11,7 +11,8 @@ import { checkExternalReferences, describe } from "./external-refs.js";
|
|
|
11
11
|
import { verifyRestored } from "./drill.js";
|
|
12
12
|
import { restoreStorage, planStorageRestore, } from "./storage-restore.js";
|
|
13
13
|
import { connectPg } from "./supabase-ca.js";
|
|
14
|
-
import {
|
|
14
|
+
import { orphanedForeignKeysCheck } from "./orphaned-foreign-keys.js";
|
|
15
|
+
import { grantsCheck } from "./grants.js";
|
|
15
16
|
import { localPgRestoreMajor, restoreToolTargetBlocker } from "./pgbin.js";
|
|
16
17
|
import { parsePgDumpMajor } from "./backup.js";
|
|
17
18
|
import { log } from "./log.js";
|
|
@@ -688,14 +689,23 @@ export async function runRestore(config, opts) {
|
|
|
688
689
|
}
|
|
689
690
|
}
|
|
690
691
|
log.step("Restoring database into target…");
|
|
691
|
-
const engine = await restoreDatabaseArtifact({
|
|
692
|
+
const engine = await restoreDatabaseArtifact({
|
|
693
|
+
dumpPath,
|
|
694
|
+
connString: targetUrl,
|
|
695
|
+
target: "supabase",
|
|
696
|
+
grants: { schemas: manifest.database.schemas, recorded: manifest.database.grants },
|
|
697
|
+
});
|
|
692
698
|
if (!engine.ok) {
|
|
693
699
|
const failures = [...engine.preData.failures, ...engine.postData.failures];
|
|
694
700
|
throw new Error(`database restore failed: ${failures.join(" | ")}.` +
|
|
695
701
|
(engine.committed
|
|
696
|
-
? " The tables and data were already committed to the target
|
|
697
|
-
|
|
698
|
-
|
|
702
|
+
? " The tables and data were already committed to the target, but the step after that failed" +
|
|
703
|
+
(engine.grants
|
|
704
|
+
? ": some or all of the foreign keys between the tables may be missing."
|
|
705
|
+
: ": the grants for anon, authenticated and service_role weren't set, and the foreign keys " +
|
|
706
|
+
"between the tables that are added after them may be missing too.") +
|
|
707
|
+
" Check the target before doing anything else; restore won't write into it again while those " +
|
|
708
|
+
"objects are there."
|
|
699
709
|
: await targetStateAfterFailure(targetUrl, manifest.database.schemas)) +
|
|
700
710
|
restoreFailureAdvice(failures.join(" ")));
|
|
701
711
|
}
|
|
@@ -705,17 +715,13 @@ export async function runRestore(config, opts) {
|
|
|
705
715
|
log.step("Verifying restored tables…");
|
|
706
716
|
const verified = await verifyRestored(targetUrl, manifest, dumpPath);
|
|
707
717
|
result.databaseChecks = verified.checks;
|
|
718
|
+
if (engine.grants)
|
|
719
|
+
result.databaseChecks.push(grantsCheck(engine.grants, "restore"));
|
|
708
720
|
result.databaseVerified = verified.checks.every((c) => c.pass);
|
|
709
721
|
if (orphaned.length) {
|
|
710
722
|
result.orphanedForeignKeys = orphaned;
|
|
711
723
|
// 数据一行不少,外键也在(只是不回头查已有的行):算通过,但写进报告让人看见
|
|
712
|
-
result.databaseChecks.push(
|
|
713
|
-
name: "foreign keys",
|
|
714
|
-
pass: true,
|
|
715
|
-
detail: `${orphaned.length} added as NOT VALID because the snapshot holds rows that break them: ` +
|
|
716
|
-
`${orphaned.map(describeOrphanedForeignKey).join("; ")}. New writes are still checked. ` +
|
|
717
|
-
`Clean up those rows, then run ALTER TABLE … VALIDATE CONSTRAINT to check the old ones too.`,
|
|
718
|
-
});
|
|
724
|
+
result.databaseChecks.push(orphanedForeignKeysCheck(orphaned));
|
|
719
725
|
}
|
|
720
726
|
for (const check of verified.checks) {
|
|
721
727
|
(check.pass ? log.ok : log.warn)(`${check.name}: ${check.detail}`);
|
package/package.json
CHANGED