backupdrill 2.8.1 → 2.9.1
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 +3 -0
- package/dist/drill.js +14 -3
- package/dist/grants.d.ts +81 -0
- package/dist/grants.js +413 -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/recovery-doc.js +19 -4
- package/dist/restore-engine.d.ts +13 -2
- package/dist/restore-engine.js +65 -8
- package/dist/restore.js +16 -4
- 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
|
+
Restoring by hand, set the grants after `pg_restore`. A snapshot made with 2.9.1 or later has the SQL in its `RECOVERY.md`: one `do` block that does what `restore` does. It takes those roles off everything the restore created, grants back what the source had, and skips with a warning any grant whose object isn't there. 2.9.0 wrote a revoke and the grants for each recorded object instead, which misses objects that changed while the backup ran, so restore those snapshots with `backupdrill restore`. Snapshots from before 2.9.0 have no record: run this to give the three roles 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
|
@@ -2,6 +2,7 @@ import type { BackupConfig } from "./config.js";
|
|
|
2
2
|
import type { Manifest } from "./manifest.js";
|
|
3
3
|
import { type SnapshotStore } from "./snapshot-store.js";
|
|
4
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 的项目里排序靠后的文件永远不被校验;
|
|
@@ -59,6 +60,8 @@ interface PostDataResult {
|
|
|
59
60
|
failures: string[];
|
|
60
61
|
/** 已同时计入 failures */
|
|
61
62
|
orphanedForeignKeys?: OrphanedForeignKey[];
|
|
63
|
+
/** 授权重建结果;失败时不存在,原因在 failures 里 */
|
|
64
|
+
grants?: GrantRestore;
|
|
62
65
|
}
|
|
63
66
|
/** 兼容层:历史签名保留,分类逻辑的单一权威在统一引擎(restore-engine.ts)。 */
|
|
64
67
|
export declare function classifyPostDataErrors(stderr: string): PostDataResult;
|
package/dist/drill.js
CHANGED
|
@@ -10,6 +10,7 @@ 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
12
|
import { orphanedForeignKeysCheck } from "./orphaned-foreign-keys.js";
|
|
13
|
+
import { grantsCheck } from "./grants.js";
|
|
13
14
|
import { localPgRestoreMajor, restoreToolBreaksOnTarget, sandboxMajorFor } from "./pgbin.js";
|
|
14
15
|
import { log } from "./log.js";
|
|
15
16
|
import { onInterrupt, stopOnInterrupt, throwIfInterrupted } from "./interrupt.js";
|
|
@@ -309,8 +310,15 @@ export function postDataResult(code, stderr) {
|
|
|
309
310
|
* 的托管对象跳过如实返回。pre-data 的 schema 冲突跳过(dump 自带 CREATE SCHEMA,
|
|
310
311
|
* 容器恒有 public)是非事件,不计入报告。
|
|
311
312
|
*/
|
|
312
|
-
async function pgRestore(dumpPath, connString, dumpedSchemas, jobs) {
|
|
313
|
-
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
|
+
});
|
|
314
322
|
if (result.preData.failures.length) {
|
|
315
323
|
throw new Error(`pg_restore failed: ${result.preData.failures.join(" | ")}`);
|
|
316
324
|
}
|
|
@@ -318,6 +326,7 @@ async function pgRestore(dumpPath, connString, dumpedSchemas, jobs) {
|
|
|
318
326
|
supabaseSkipped: result.postData.expectedSkips,
|
|
319
327
|
failures: result.postData.failures,
|
|
320
328
|
orphanedForeignKeys: result.orphanedForeignKeys,
|
|
329
|
+
grants: result.grants,
|
|
321
330
|
};
|
|
322
331
|
}
|
|
323
332
|
// ── 校验 ────────────────────────────────────────────────────────────
|
|
@@ -581,7 +590,7 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
581
590
|
log.step("Restoring into ephemeral Postgres…");
|
|
582
591
|
let postData;
|
|
583
592
|
try {
|
|
584
|
-
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);
|
|
585
594
|
}
|
|
586
595
|
catch (error) {
|
|
587
596
|
// 沙箱装不上扩展 + 错误特征命中"缺类型/schema/扩展" → 假设式归因到沙箱环境
|
|
@@ -617,6 +626,8 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
617
626
|
await opts.supervision?.observe({ phase: "verify" });
|
|
618
627
|
const verify = await verifyRestored(pg.connString, manifest, dumpPath);
|
|
619
628
|
checks.push(...verify.checks);
|
|
629
|
+
if (postData.grants)
|
|
630
|
+
checks.push(grantsCheck(postData.grants, "drill"));
|
|
620
631
|
const orphaned = postData.orphanedForeignKeys ?? [];
|
|
621
632
|
if (orphaned.length)
|
|
622
633
|
checks.push(orphanedForeignKeysCheck(orphaned));
|
package/dist/grants.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
* revoke: false = 只出授权语句(RECOVERY.md 的清权限按目标目录来,见 recoveryGrantsSql)。
|
|
36
|
+
*/
|
|
37
|
+
export declare function grantStatements(objects: GrantedObject[], opts: {
|
|
38
|
+
roles: readonly GrantRole[];
|
|
39
|
+
maintain: boolean;
|
|
40
|
+
revoke?: boolean;
|
|
41
|
+
}): string[];
|
|
42
|
+
/**
|
|
43
|
+
* 恢复端:在恢复出来的对象上照记录重建授权,一个事务内完成,提交前回读目录核对。
|
|
44
|
+
* 目标上的对象以目标目录为准:记录里有、目标上没有的(沙箱跳过的托管对象)略过;
|
|
45
|
+
* 目标上有、记录里没有的(备份转储完之后才建的)按"没有授权"处理,只清不授。
|
|
46
|
+
* recorded 为 undefined = 旧快照:public 里的表、序列、函数在目标已有授权之上补齐 Supabase 以前的默认授权。
|
|
47
|
+
*/
|
|
48
|
+
export declare function restoreGrants(client: Client, opts: {
|
|
49
|
+
schemas: string[];
|
|
50
|
+
recorded: GrantedObject[] | undefined;
|
|
51
|
+
}): Promise<GrantRestore>;
|
|
52
|
+
/**
|
|
53
|
+
* 补授权失败时的退路(只用于真实目标):把恢复出来的表、序列、函数上这几个角色的权限全部收走。
|
|
54
|
+
* 应用会 42501,但源库关着的东西不会因为目标的默认授权而开着。schema 不动,免得连带目标上别的东西。
|
|
55
|
+
*/
|
|
56
|
+
export declare function revokeApiAccess(client: Client, schemas: string[]): Promise<void>;
|
|
57
|
+
/** 演练和恢复报告里的一行。旧快照那句按场合说:恢复是已经开放了要收回,演练是提醒真恢复时会这样。 */
|
|
58
|
+
export declare function grantsCheck(outcome: GrantRestore, context: "drill" | "restore"): {
|
|
59
|
+
name: string;
|
|
60
|
+
pass: boolean;
|
|
61
|
+
detail: string;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用),做法和 restoreGrants 一样:
|
|
65
|
+
* 按恢复后的目录,先确认执行的角色是这些对象的属主(不是属主时 GRANT/REVOKE 只告警、不生效或只生效一半),
|
|
66
|
+
* 再把各 schema 下每个 schema、表、序列、函数上 PUBLIC 和三个角色的权限全部收走(扩展自带的对象不碰)、
|
|
67
|
+
* 回读确认收干净,最后逐条授回记录里的。授不上的(对象、列或参数类型不在这次恢复里)跳过并告警、不中断:
|
|
68
|
+
* 授权只会加权限,跳过一条最多让应用少一点访问,不会把该关的打开。前面几步出错就整段回滚、报错。
|
|
69
|
+
* 授权是在转储完之后读的:两次读之间删掉的对象在转储里、不在记录里,只按记录逐个收权就会漏掉它,
|
|
70
|
+
* 它会带着默认的 PUBLIC 执行权恢复出来(交叉审查 2026-10-31);反过来,之间新加的对象(列)在记录里、
|
|
71
|
+
* 不在转储里,直接授权会报错,在 Supabase 的 SQL 编辑器里整段回滚。所以整段放进一个 DO 块。
|
|
72
|
+
* 旧快照没有记录,给 Supabase 以前的默认授权。
|
|
73
|
+
* MAINTAIN 只会出现在 PG17+ 源库的记录里,而恢复目标的版本不低于源库,所以照写。
|
|
74
|
+
*
|
|
75
|
+
* 2.9.0 收的是授权数组(旧快照传 undefined),照旧接受:记录里每个备份的 schema 都有一条 schema 条目,
|
|
76
|
+
* 范围从它取。
|
|
77
|
+
*/
|
|
78
|
+
export declare function recoveryGrantsSql(database: {
|
|
79
|
+
schemas: string[];
|
|
80
|
+
grants?: GrantedObject[];
|
|
81
|
+
} | GrantedObject[] | undefined): string;
|
package/dist/grants.js
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
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
|
+
* revoke: false = 只出授权语句(RECOVERY.md 的清权限按目标目录来,见 recoveryGrantsSql)。
|
|
131
|
+
*/
|
|
132
|
+
export function grantStatements(objects, opts) {
|
|
133
|
+
const roles = GRANT_ROLES.filter((role) => opts.roles.includes(role));
|
|
134
|
+
const revokeFrom = roles.map(roleName).join(", ");
|
|
135
|
+
const statements = [];
|
|
136
|
+
const columns = [];
|
|
137
|
+
for (const o of objects) {
|
|
138
|
+
if (o.kind !== "column" && opts.revoke !== false) {
|
|
139
|
+
statements.push(`revoke all on ${objectClause(o)} from ${revokeFrom}`);
|
|
140
|
+
}
|
|
141
|
+
for (const role of roles) {
|
|
142
|
+
const privileges = (o.privileges[role] ?? []).filter((p) => GRANT_PRIVILEGES.includes(p) && (opts.maintain || p !== "MAINTAIN"));
|
|
143
|
+
if (!privileges.length)
|
|
144
|
+
continue;
|
|
145
|
+
if (o.kind === "column") {
|
|
146
|
+
const column = quoteIdent(o.column ?? "");
|
|
147
|
+
columns.push(`grant ${privileges.map((p) => `${p.toLowerCase()} (${column})`).join(", ")} on table ${qualifiedName(o)} to ${roleName(role)}`);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
statements.push(`grant ${privileges.map((p) => p.toLowerCase()).join(", ")} on ${objectClause(o)} to ${roleName(role)}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return [...statements, ...columns];
|
|
155
|
+
}
|
|
156
|
+
/** Supabase 以前给 public 里新对象的默认授权(pg_default_acl 实测:表 arwdDxtm、序列 rwU、函数 X)。 */
|
|
157
|
+
function legacyDefaultGrants(objects) {
|
|
158
|
+
const all = (privileges) => Object.fromEntries(API_ROLES.map((role) => [role, privileges]));
|
|
159
|
+
return objects
|
|
160
|
+
.filter((o) => o.schema === "public" && (o.kind === "table" || o.kind === "sequence" || o.kind === "routine"))
|
|
161
|
+
.map((o) => ({
|
|
162
|
+
...o,
|
|
163
|
+
privileges: {
|
|
164
|
+
...o.privileges,
|
|
165
|
+
...all(o.kind === "table"
|
|
166
|
+
? ["SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER", "MAINTAIN"]
|
|
167
|
+
: o.kind === "sequence"
|
|
168
|
+
? ["SELECT", "UPDATE", "USAGE"]
|
|
169
|
+
: ["EXECUTE"]),
|
|
170
|
+
},
|
|
171
|
+
}));
|
|
172
|
+
}
|
|
173
|
+
// 一次发太多条会让单条查询文本过大;几百条一批足够快
|
|
174
|
+
const STATEMENTS_PER_QUERY = 200;
|
|
175
|
+
/**
|
|
176
|
+
* 恢复端:在恢复出来的对象上照记录重建授权,一个事务内完成,提交前回读目录核对。
|
|
177
|
+
* 目标上的对象以目标目录为准:记录里有、目标上没有的(沙箱跳过的托管对象)略过;
|
|
178
|
+
* 目标上有、记录里没有的(备份转储完之后才建的)按"没有授权"处理,只清不授。
|
|
179
|
+
* recorded 为 undefined = 旧快照:public 里的表、序列、函数在目标已有授权之上补齐 Supabase 以前的默认授权。
|
|
180
|
+
*/
|
|
181
|
+
export async function restoreGrants(client, opts) {
|
|
182
|
+
return withEmptySearchPath(client, async () => {
|
|
183
|
+
const target = await targetFacts(client);
|
|
184
|
+
const onTarget = await catalogObjects(client, opts.schemas);
|
|
185
|
+
let planned;
|
|
186
|
+
if (opts.recorded === undefined) {
|
|
187
|
+
planned = legacyDefaultGrants(onTarget);
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
const recorded = new Map(opts.recorded.map((o) => [objectKey(o), o]));
|
|
191
|
+
// 授权在转储之后才读,转储期间新加的列不在归档里:只处理目标上真有的列
|
|
192
|
+
const columns = await targetColumns(client, opts.schemas);
|
|
193
|
+
planned = [
|
|
194
|
+
// 目标上的 schema、表、序列、函数都要过一遍:记录里没有的按"源库没给授权"处理
|
|
195
|
+
...onTarget
|
|
196
|
+
.filter((o) => o.kind !== "column")
|
|
197
|
+
.map((o) => ({ ...o, privileges: recorded.get(objectKey(o))?.privileges ?? {} })),
|
|
198
|
+
...opts.recorded.filter((o) => o.kind === "column" && columns.has(objectKey(o))),
|
|
199
|
+
];
|
|
200
|
+
}
|
|
201
|
+
await execute(client, grantStatements(planned, target));
|
|
202
|
+
await assertGrantsTookEffect(client, opts.schemas, planned, target);
|
|
203
|
+
return { mode: opts.recorded === undefined ? "legacy-defaults" : "recorded", objects: planned.length };
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* 补授权失败时的退路(只用于真实目标):把恢复出来的表、序列、函数上这几个角色的权限全部收走。
|
|
208
|
+
* 应用会 42501,但源库关着的东西不会因为目标的默认授权而开着。schema 不动,免得连带目标上别的东西。
|
|
209
|
+
*/
|
|
210
|
+
export async function revokeApiAccess(client, schemas) {
|
|
211
|
+
await withEmptySearchPath(client, async () => {
|
|
212
|
+
const target = await targetFacts(client);
|
|
213
|
+
const planned = (await catalogObjects(client, schemas))
|
|
214
|
+
.filter((o) => o.kind === "table" || o.kind === "sequence" || o.kind === "routine")
|
|
215
|
+
.map((o) => ({ ...o, privileges: {} }));
|
|
216
|
+
await execute(client, grantStatements(planned, target));
|
|
217
|
+
await assertGrantsTookEffect(client, schemas, planned, target);
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
async function targetColumns(client, schemas) {
|
|
221
|
+
const res = await client.query(`select n.nspname::text as schema, c.relname::text as name, a.attname::text as column_name
|
|
222
|
+
from pg_catalog.pg_attribute a
|
|
223
|
+
join pg_catalog.pg_class c on c.oid = a.attrelid
|
|
224
|
+
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
|
225
|
+
where n.nspname = any($1::text[]) and c.relkind in ('r', 'p', 'v', 'm', 'f')
|
|
226
|
+
and a.attnum > 0 and not a.attisdropped`, [schemas]);
|
|
227
|
+
return new Set(res.rows.map((r) => objectKey({ kind: "column", schema: r.schema, name: r.name, column: r.column_name })));
|
|
228
|
+
}
|
|
229
|
+
async function targetFacts(client) {
|
|
230
|
+
const version = await client.query("show server_version_num");
|
|
231
|
+
const roleRows = await client.query("select rolname from pg_catalog.pg_roles where rolname = any($1::text[])", [[...API_ROLES]]);
|
|
232
|
+
return {
|
|
233
|
+
roles: ["PUBLIC", ...roleRows.rows.map((r) => r.rolname)],
|
|
234
|
+
maintain: Number(version.rows[0].server_version_num) >= 170000,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
async function execute(client, statements) {
|
|
238
|
+
for (let i = 0; i < statements.length; i += STATEMENTS_PER_QUERY) {
|
|
239
|
+
await client.query(statements.slice(i, i + STATEMENTS_PER_QUERY).join(";\n"));
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
function effectivePrivileges(o, role, target) {
|
|
243
|
+
return (o.privileges[role] ?? [])
|
|
244
|
+
.filter((p) => GRANT_PRIVILEGES.includes(p) && (target.maintain || p !== "MAINTAIN"))
|
|
245
|
+
.sort()
|
|
246
|
+
.join(",");
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* GRANT/REVOKE 遇到不归自己管的对象只给 WARNING、什么也不做(比如恢复用的角色不是属主)。
|
|
250
|
+
* 回读目录逐个对象比,对不上就报错,让事务回滚、调用方走退路,不把"以为设好了"当成功。
|
|
251
|
+
*/
|
|
252
|
+
async function assertGrantsTookEffect(client, schemas, planned, target) {
|
|
253
|
+
const actual = new Map((await catalogObjects(client, schemas)).map((o) => [objectKey(o), o]));
|
|
254
|
+
const off = planned.filter((o) => {
|
|
255
|
+
const now = actual.get(objectKey(o)) ?? { ...o, privileges: {} };
|
|
256
|
+
return target.roles.some((role) => effectivePrivileges(o, role, target) !== effectivePrivileges(now, role, target));
|
|
257
|
+
});
|
|
258
|
+
if (!off.length)
|
|
259
|
+
return;
|
|
260
|
+
const named = off
|
|
261
|
+
.slice(0, 3)
|
|
262
|
+
.map((o) => `${o.kind} ${o.schema}${o.name ? `.${o.name}` : ""}${o.column ? `.${o.column}` : ""}`)
|
|
263
|
+
.join(", ");
|
|
264
|
+
throw new Error(`grants didn't take effect on ${off.length} object(s) (${named}${off.length > 3 ? ", …" : ""}); ` +
|
|
265
|
+
`the role running the restore probably doesn't own them`);
|
|
266
|
+
}
|
|
267
|
+
/** 演练和恢复报告里的一行。旧快照那句按场合说:恢复是已经开放了要收回,演练是提醒真恢复时会这样。 */
|
|
268
|
+
export function grantsCheck(outcome, context) {
|
|
269
|
+
const legacyScope = `Supabase's old default access to the ${outcome.objects} table(s), sequence(s) and function(s) in public`;
|
|
270
|
+
return {
|
|
271
|
+
name: "API grants",
|
|
272
|
+
pass: true,
|
|
273
|
+
detail: outcome.mode === "recorded"
|
|
274
|
+
? `access for anon, authenticated and service_role set as it was at backup time on ${outcome.objects} object(s)`
|
|
275
|
+
: context === "restore"
|
|
276
|
+
? `this snapshot was taken before BackupDrill recorded grants, so anon, authenticated and service_role got ` +
|
|
277
|
+
`${legacyScope}. Revoke it on anything you kept private`
|
|
278
|
+
: `this snapshot was taken before BackupDrill recorded grants, so restoring it gives anon, authenticated and ` +
|
|
279
|
+
`service_role ${legacyScope}. Newer backups record the grants`,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/** 选一个不出现在任何内容里的 dollar-quote 标签,内容原样放进去不用转义。 */
|
|
283
|
+
function dollarQuoteTag(base, contents) {
|
|
284
|
+
for (let i = 0;; i++) {
|
|
285
|
+
const tag = `$${base}${i || ""}$`;
|
|
286
|
+
if (!contents.some((text) => text.includes(tag)))
|
|
287
|
+
return tag;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function sqlLiteral(value) {
|
|
291
|
+
return `'${value.replace(/'/g, "''")}'`;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用),做法和 restoreGrants 一样:
|
|
295
|
+
* 按恢复后的目录,先确认执行的角色是这些对象的属主(不是属主时 GRANT/REVOKE 只告警、不生效或只生效一半),
|
|
296
|
+
* 再把各 schema 下每个 schema、表、序列、函数上 PUBLIC 和三个角色的权限全部收走(扩展自带的对象不碰)、
|
|
297
|
+
* 回读确认收干净,最后逐条授回记录里的。授不上的(对象、列或参数类型不在这次恢复里)跳过并告警、不中断:
|
|
298
|
+
* 授权只会加权限,跳过一条最多让应用少一点访问,不会把该关的打开。前面几步出错就整段回滚、报错。
|
|
299
|
+
* 授权是在转储完之后读的:两次读之间删掉的对象在转储里、不在记录里,只按记录逐个收权就会漏掉它,
|
|
300
|
+
* 它会带着默认的 PUBLIC 执行权恢复出来(交叉审查 2026-10-31);反过来,之间新加的对象(列)在记录里、
|
|
301
|
+
* 不在转储里,直接授权会报错,在 Supabase 的 SQL 编辑器里整段回滚。所以整段放进一个 DO 块。
|
|
302
|
+
* 旧快照没有记录,给 Supabase 以前的默认授权。
|
|
303
|
+
* MAINTAIN 只会出现在 PG17+ 源库的记录里,而恢复目标的版本不低于源库,所以照写。
|
|
304
|
+
*
|
|
305
|
+
* 2.9.0 收的是授权数组(旧快照传 undefined),照旧接受:记录里每个备份的 schema 都有一条 schema 条目,
|
|
306
|
+
* 范围从它取。
|
|
307
|
+
*/
|
|
308
|
+
export function recoveryGrantsSql(database) {
|
|
309
|
+
const recorded = Array.isArray(database) ? database : database?.grants;
|
|
310
|
+
if (recorded === undefined) {
|
|
311
|
+
return [
|
|
312
|
+
"grant all on all tables in schema public to anon, authenticated, service_role;",
|
|
313
|
+
"grant all on all sequences in schema public to anon, authenticated, service_role;",
|
|
314
|
+
"grant execute on all functions in schema public to anon, authenticated, service_role;",
|
|
315
|
+
].join("\n");
|
|
316
|
+
}
|
|
317
|
+
const schemaNames = Array.isArray(database) ? [...new Set(database.map((g) => g.schema))] : database.schemas;
|
|
318
|
+
const grants = grantStatements(recorded, { roles: GRANT_ROLES, maintain: true, revoke: false });
|
|
319
|
+
const inner = dollarQuoteTag("g", grants);
|
|
320
|
+
const outer = dollarQuoteTag("grants", [...grants, ...schemaNames, inner]);
|
|
321
|
+
const schemas = `array[${schemaNames.map(sqlLiteral).join(", ")}]::text[]`;
|
|
322
|
+
const grantArray = grants.length
|
|
323
|
+
? `array[\n${grants.map((g) => ` ${inner}${g}${inner}`).join(",\n")}\n ]`
|
|
324
|
+
: "array[]::text[]";
|
|
325
|
+
const notFromExtension = (catalog, alias) => `not exists (select 1 from pg_catalog.pg_depend d where d.classid = '${catalog}'::pg_catalog.regclass ` +
|
|
326
|
+
`and d.objid = ${alias}.oid and d.deptype = 'e')`;
|
|
327
|
+
const from = "public, anon, authenticated, service_role";
|
|
328
|
+
// 恢复出来的对象(扩展自带的除外):名字、收权语句(列没有,清表权限会连带清掉)、属主、当前 ACL。
|
|
329
|
+
// 下面三处都用它,每次现查
|
|
330
|
+
const restoredObjects = `
|
|
331
|
+
select pg_catalog.format('schema %I', n.nspname) as object,
|
|
332
|
+
pg_catalog.format('revoke all on schema %I from ${from}', n.nspname) as revoke_sql,
|
|
333
|
+
n.nspowner as owner,
|
|
334
|
+
coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner)) as acl
|
|
335
|
+
from pg_catalog.pg_namespace n
|
|
336
|
+
where n.nspname = any (${schemas})
|
|
337
|
+
union all
|
|
338
|
+
select pg_catalog.format('%I.%I', n.nspname, c.relname),
|
|
339
|
+
pg_catalog.format('revoke all on %s %I.%I from ${from}',
|
|
340
|
+
case when c.relkind = 'S' then 'sequence' else 'table' end, n.nspname, c.relname),
|
|
341
|
+
c.relowner,
|
|
342
|
+
coalesce(c.relacl, pg_catalog.acldefault(case when c.relkind = 'S' then 's' else 'r' end::"char", c.relowner))
|
|
343
|
+
from pg_catalog.pg_class c
|
|
344
|
+
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
|
345
|
+
where n.nspname = any (${schemas})
|
|
346
|
+
and c.relkind in ('r', 'p', 'v', 'm', 'f', 'S')
|
|
347
|
+
and ${notFromExtension("pg_catalog.pg_class", "c")}
|
|
348
|
+
union all
|
|
349
|
+
select pg_catalog.format('%I.%I.%I', n.nspname, c.relname, a.attname), null, c.relowner, a.attacl
|
|
350
|
+
from pg_catalog.pg_attribute a
|
|
351
|
+
join pg_catalog.pg_class c on c.oid = a.attrelid
|
|
352
|
+
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
|
353
|
+
where n.nspname = any (${schemas})
|
|
354
|
+
and a.attnum > 0 and not a.attisdropped and a.attacl is not null
|
|
355
|
+
and ${notFromExtension("pg_catalog.pg_class", "c")}
|
|
356
|
+
union all
|
|
357
|
+
select pg_catalog.format('%I.%I(%s)', n.nspname, p.proname, sig.args),
|
|
358
|
+
pg_catalog.format('revoke all on routine %I.%I(%s) from ${from}', n.nspname, p.proname, sig.args),
|
|
359
|
+
p.proowner,
|
|
360
|
+
coalesce(p.proacl, pg_catalog.acldefault('f', p.proowner))
|
|
361
|
+
from pg_catalog.pg_proc p
|
|
362
|
+
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
|
|
363
|
+
cross join lateral (
|
|
364
|
+
select case when p.prokind = 'a' then pg_catalog.oidvectortypes(p.proargtypes)
|
|
365
|
+
else pg_catalog.pg_get_function_identity_arguments(p.oid) end as args
|
|
366
|
+
) sig
|
|
367
|
+
where n.nspname = any (${schemas})
|
|
368
|
+
and ${notFromExtension("pg_catalog.pg_proc", "p")}`;
|
|
369
|
+
return `do ${outer}
|
|
370
|
+
declare
|
|
371
|
+
statement text;
|
|
372
|
+
problem text;
|
|
373
|
+
begin
|
|
374
|
+
perform pg_catalog.set_config('search_path', '', true);
|
|
375
|
+
-- 0. Run as the role that owns what the restore created: for anyone else, GRANT and REVOKE
|
|
376
|
+
-- only warn and change nothing, or only part of it
|
|
377
|
+
select pg_catalog.string_agg(o.object, ', ') into problem
|
|
378
|
+
from (${restoredObjects}
|
|
379
|
+
) o
|
|
380
|
+
where not pg_catalog.pg_has_role(current_user, o.owner, 'USAGE');
|
|
381
|
+
if problem is not null then
|
|
382
|
+
raise exception 'run this as the role that ran pg_restore, which owns the restored objects; % does not own: %',
|
|
383
|
+
current_user, pg_catalog.left(problem, 500);
|
|
384
|
+
end if;
|
|
385
|
+
-- 1. Take PUBLIC, anon, authenticated and service_role off everything the restore created
|
|
386
|
+
-- (objects that belong to an extension are left alone), then check nothing is left
|
|
387
|
+
for statement in select o.revoke_sql from (${restoredObjects}
|
|
388
|
+
) o where o.revoke_sql is not null
|
|
389
|
+
loop
|
|
390
|
+
execute statement;
|
|
391
|
+
end loop;
|
|
392
|
+
select pg_catalog.string_agg(distinct o.object, ', ') into problem
|
|
393
|
+
from (${restoredObjects}
|
|
394
|
+
) o
|
|
395
|
+
cross join lateral pg_catalog.aclexplode(o.acl) x
|
|
396
|
+
where x.grantee = 0
|
|
397
|
+
or x.grantee in (select r.oid from pg_catalog.pg_roles r where r.rolname in ('anon', 'authenticated', 'service_role'));
|
|
398
|
+
if problem is not null then
|
|
399
|
+
raise exception 'could not take access away on: %', pg_catalog.left(problem, 500);
|
|
400
|
+
end if;
|
|
401
|
+
-- 2. Grant back what the source had at backup time. A grant that fails (its object, column or
|
|
402
|
+
-- argument type isn't in this restore) is skipped with a warning: it can only leave less access
|
|
403
|
+
for statement in select pg_catalog.unnest(${grantArray})
|
|
404
|
+
loop
|
|
405
|
+
begin
|
|
406
|
+
execute statement;
|
|
407
|
+
exception when others then
|
|
408
|
+
raise warning 'not granted (%): %', sqlerrm, statement;
|
|
409
|
+
end;
|
|
410
|
+
end loop;
|
|
411
|
+
end
|
|
412
|
+
${outer};`;
|
|
413
|
+
}
|
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))
|
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,23 @@ 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
|
+
? `Run this block in the SQL editor or psql. It first takes access away from
|
|
115
|
+
these roles (and \`PUBLIC\`) on everything the restore created, then grants back
|
|
116
|
+
what the source had at backup time (the same list is in manifest.json under
|
|
117
|
+
\`database.grants\`). A grant whose object isn't in this restore is skipped with a warning:`
|
|
118
|
+
: `This snapshot was taken before BackupDrill recorded grants. The statements below
|
|
119
|
+
give the three roles Supabase's old default access to everything in \`public\`;
|
|
120
|
+
afterwards, revoke it on any table you had kept private:`}
|
|
121
|
+
|
|
122
|
+
\`\`\`sql
|
|
123
|
+
${recoveryGrantsSql(db)}
|
|
124
|
+
\`\`\`
|
|
110
125
|
|
|
111
126
|
## Restore Storage files
|
|
112
127
|
|
|
@@ -128,7 +143,7 @@ referenced outside the snapshot (such as \`auth.users\`) are on the target, inst
|
|
|
128
143
|
the extensions, restores the database in a single transaction through the same
|
|
129
144
|
engine the weekly drills use (an SQL error rolls it back and the extensions stay
|
|
130
145
|
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
|
|
146
|
+
retrying), sets the grants above, verifies table counts and row presence afterwards, then rebuilds buckets, uploads the
|
|
132
147
|
Storage files back and reconciles every one against the target.
|
|
133
148
|
|
|
134
149
|
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. ≡
|
|
@@ -37,12 +38,20 @@ export interface EngineResult {
|
|
|
37
38
|
ok: boolean;
|
|
38
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
|
}
|
|
49
|
+
/** 恢复完要重建授权的范围与依据:manifest.database.schemas 和 manifest.database.grants。 */
|
|
50
|
+
export interface GrantsToRestore {
|
|
51
|
+
schemas: string[];
|
|
52
|
+
/** undefined = 旧快照没有记录,按 Supabase 以前的默认授权补 public */
|
|
53
|
+
recorded: GrantedObject[] | undefined;
|
|
54
|
+
}
|
|
46
55
|
/**
|
|
47
56
|
* 新版 pg_restore 的脚本首尾各有一条 psql 元命令(\restrict <key> / \unrestrict <key>),node-pg 执行不了。
|
|
48
57
|
* 只认位置:开头那条是第一行非空、非 -- 注释的行,结尾那条是最后一行非空行。注释正文是字符串,
|
|
@@ -139,7 +148,7 @@ inTransaction?: Client): Promise<string[]>;
|
|
|
139
148
|
* auth.uid() → uuid、auth.jwt() → jsonb、auth.role() → text、auth.email() → text,
|
|
140
149
|
* 全部返回 null(恢复过程中不会真调它们:COPY 不求值列默认,策略/函数体不执行);
|
|
141
150
|
* 角色 anon / authenticated / service_role(nologin):RLS 策略的 `to authenticated`
|
|
142
|
-
*
|
|
151
|
+
* 要它们在场才能建;恢复完重建授权(grants.ts)也要它们,演练因此和真实恢复走同一段。
|
|
143
152
|
* 刻意不建 auth.users 之类的表:空的 auth.users 会让 FK 校验在 post-data 真失败,
|
|
144
153
|
* 比"缺表跳过"更糟。FK → auth.users 仍按 SANDBOX_MANAGED_ERROR 的 relation 形态跳过。
|
|
145
154
|
*
|
|
@@ -235,6 +244,8 @@ export declare function restoreDatabaseArtifact(opts: {
|
|
|
235
244
|
dumpedSchemas?: string[];
|
|
236
245
|
/** pg_restore 并行路数;不传或 ≤1 = 单连接两遍。 */
|
|
237
246
|
jobs?: number;
|
|
247
|
+
/** 恢复完照它重建 PUBLIC 和 API 角色的授权;沙箱和真实目标一样做 */
|
|
248
|
+
grants: GrantsToRestore;
|
|
238
249
|
}): Promise<EngineResult>;
|
|
239
250
|
/**
|
|
240
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
|
//
|
|
@@ -21,6 +21,7 @@ import { join } from "node:path";
|
|
|
21
21
|
import { MAX_COPY_HEADER, parseCopyHeader, parseCreatedTables, parseCreateSchemas, parseForeignKeys, } from "./dump-sql.js";
|
|
22
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,6 +101,34 @@ export function refFromStorageEndpoint(endpoint) {
|
|
|
100
101
|
return null;
|
|
101
102
|
}
|
|
102
103
|
}
|
|
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
|
+
}
|
|
131
|
+
}
|
|
103
132
|
/**
|
|
104
133
|
* 从目录条目里挑出交给 addForeignKeys 的外键(isDeferrableForeignKey)。让 pg_restore 把全部外键条目
|
|
105
134
|
* 写成 SQL,第 i 条语句对第 i 行(-L 按清单顺序输出)。对不上数或对不上名字(认不出的外键形态)
|
|
@@ -469,7 +498,7 @@ inTransaction) {
|
|
|
469
498
|
* auth.uid() → uuid、auth.jwt() → jsonb、auth.role() → text、auth.email() → text,
|
|
470
499
|
* 全部返回 null(恢复过程中不会真调它们:COPY 不求值列默认,策略/函数体不执行);
|
|
471
500
|
* 角色 anon / authenticated / service_role(nologin):RLS 策略的 `to authenticated`
|
|
472
|
-
*
|
|
501
|
+
* 要它们在场才能建;恢复完重建授权(grants.ts)也要它们,演练因此和真实恢复走同一段。
|
|
473
502
|
* 刻意不建 auth.users 之类的表:空的 auth.users 会让 FK 校验在 post-data 真失败,
|
|
474
503
|
* 比"缺表跳过"更糟。FK → auth.users 仍按 SANDBOX_MANAGED_ERROR 的 relation 形态跳过。
|
|
475
504
|
*
|
|
@@ -747,7 +776,7 @@ function mergePasses(passes) {
|
|
|
747
776
|
* 出别的错时表和数据已经提交(committed);可能的原因只剩连接断开、锁槽这类和数据无关的情况——
|
|
748
777
|
* 被引用的表和唯一索引都已在主事务里建好。
|
|
749
778
|
*/
|
|
750
|
-
async function restoreInOneTransaction(bin, dumpPath, connString, common, env, childOpts) {
|
|
779
|
+
async function restoreInOneTransaction(bin, dumpPath, connString, common, env, childOpts, grantsToRestore) {
|
|
751
780
|
const fail = (failure) => ({ pass: { expectedSkips: 0, failures: [failure] } });
|
|
752
781
|
const listing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
753
782
|
if (listing.code !== 0) {
|
|
@@ -789,8 +818,24 @@ async function restoreInOneTransaction(bin, dumpPath, connString, common, env, c
|
|
|
789
818
|
return fail(`pg_restore was killed by a signal: ${firstRestoreError(run.stderr)}`);
|
|
790
819
|
if (run.code !== 0)
|
|
791
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
|
+
}
|
|
792
837
|
if (!deferred.fks.length)
|
|
793
|
-
return { pass: { expectedSkips: 0, failures: [] } };
|
|
838
|
+
return { pass: { expectedSkips: 0, failures: [] }, grants };
|
|
794
839
|
try {
|
|
795
840
|
const client = await connectPg(connString);
|
|
796
841
|
try {
|
|
@@ -799,7 +844,7 @@ async function restoreInOneTransaction(bin, dumpPath, connString, common, env, c
|
|
|
799
844
|
stopOnError: true,
|
|
800
845
|
commentSql: deferred.commentSql,
|
|
801
846
|
});
|
|
802
|
-
return { pass: { expectedSkips: 0, failures: [] }, orphaned: added.orphaned };
|
|
847
|
+
return { pass: { expectedSkips: 0, failures: [] }, orphaned: added.orphaned, grants };
|
|
803
848
|
}
|
|
804
849
|
finally {
|
|
805
850
|
await client.end();
|
|
@@ -809,6 +854,7 @@ async function restoreInOneTransaction(bin, dumpPath, connString, common, env, c
|
|
|
809
854
|
return {
|
|
810
855
|
pass: { expectedSkips: 0, failures: [`adding foreign keys failed: ${error.message}`] },
|
|
811
856
|
committed: true,
|
|
857
|
+
grants,
|
|
812
858
|
};
|
|
813
859
|
}
|
|
814
860
|
}
|
|
@@ -860,13 +906,14 @@ export async function restoreDatabaseArtifact(opts) {
|
|
|
860
906
|
const common = ["--no-owner", "--no-privileges", "--dbname", url, opts.dumpPath];
|
|
861
907
|
const childOpts = { supabaseHost: isSupabaseHost(opts.connString), urlSslMode: urlSslModeOf(url) };
|
|
862
908
|
if (opts.target === "supabase") {
|
|
863
|
-
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);
|
|
864
910
|
return {
|
|
865
911
|
preData: pass,
|
|
866
912
|
postData: { expectedSkips: 0, failures: [] },
|
|
867
913
|
ok: pass.failures.length === 0,
|
|
868
914
|
orphanedForeignKeys: orphaned,
|
|
869
915
|
committed,
|
|
916
|
+
grants,
|
|
870
917
|
};
|
|
871
918
|
}
|
|
872
919
|
const jobs = Math.max(1, Math.floor(opts.jobs ?? 1));
|
|
@@ -959,8 +1006,18 @@ export async function restoreDatabaseArtifact(opts) {
|
|
|
959
1006
|
await client.end();
|
|
960
1007
|
}
|
|
961
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
|
+
}
|
|
962
1019
|
const postData = mergePasses(passes);
|
|
963
|
-
return { preData, postData, ok: postData.failures.length === 0, orphanedForeignKeys };
|
|
1020
|
+
return { preData, postData, ok: postData.failures.length === 0, orphanedForeignKeys, grants };
|
|
964
1021
|
}
|
|
965
1022
|
finally {
|
|
966
1023
|
await rm(listDir, { recursive: true, force: true });
|
package/dist/restore.js
CHANGED
|
@@ -12,6 +12,7 @@ import { verifyRestored } from "./drill.js";
|
|
|
12
12
|
import { restoreStorage, planStorageRestore, } from "./storage-restore.js";
|
|
13
13
|
import { connectPg } from "./supabase-ca.js";
|
|
14
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,6 +715,8 @@ 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;
|
package/package.json
CHANGED