backupdrill 2.9.0 → 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 CHANGED
@@ -227,7 +227,7 @@ So each backup also records, in `manifest.json` under `database.grants`, what `a
227
227
 
228
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
229
 
230
- By hand, to get back Supabase's old defaults in `public` (then revoke on the tables you keep private):
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
231
 
232
232
  ```sql
233
233
  grant all on all tables in schema public to anon, authenticated, service_role;
package/dist/grants.d.ts CHANGED
@@ -31,11 +31,13 @@ export declare function captureGrants(client: Client, schemas: string[]): Promis
31
31
  * 把一组对象的授权写成 SQL:schema、表、序列、函数先清掉这几个角色的全部权限再照记录授,
32
32
  * 列级授权放在最后(清表权限会连带清掉列权限)。schema 也要清:源库可能靠不给 USAGE 把整个
33
33
  * schema 关起来,目标上的 public 却是 Supabase 默认开放的。
34
- * roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN。
34
+ * roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN;
35
+ * revoke: false = 只出授权语句(RECOVERY.md 的清权限按目标目录来,见 recoveryGrantsSql)。
35
36
  */
36
37
  export declare function grantStatements(objects: GrantedObject[], opts: {
37
38
  roles: readonly GrantRole[];
38
39
  maintain: boolean;
40
+ revoke?: boolean;
39
41
  }): string[];
40
42
  /**
41
43
  * 恢复端:在恢复出来的对象上照记录重建授权,一个事务内完成,提交前回读目录核对。
@@ -59,8 +61,21 @@ export declare function grantsCheck(outcome: GrantRestore, context: "drill" | "r
59
61
  detail: string;
60
62
  };
61
63
  /**
62
- * RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用)。有记录就逐个对象照记录重建,
63
- * 和 restoreGrants 同一套语句;旧快照没有记录,给 Supabase 以前的默认授权。
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 以前的默认授权。
64
73
  * MAINTAIN 只会出现在 PG17+ 源库的记录里,而恢复目标的版本不低于源库,所以照写。
74
+ *
75
+ * 2.9.0 收的是授权数组(旧快照传 undefined),照旧接受:记录里每个备份的 schema 都有一条 schema 条目,
76
+ * 范围从它取。
65
77
  */
66
- export declare function recoveryGrantsSql(grants: GrantedObject[] | undefined): string;
78
+ export declare function recoveryGrantsSql(database: {
79
+ schemas: string[];
80
+ grants?: GrantedObject[];
81
+ } | GrantedObject[] | undefined): string;
package/dist/grants.js CHANGED
@@ -126,7 +126,8 @@ function roleName(role) {
126
126
  * 把一组对象的授权写成 SQL:schema、表、序列、函数先清掉这几个角色的全部权限再照记录授,
127
127
  * 列级授权放在最后(清表权限会连带清掉列权限)。schema 也要清:源库可能靠不给 USAGE 把整个
128
128
  * schema 关起来,目标上的 public 却是 Supabase 默认开放的。
129
- * roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN。
129
+ * roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN;
130
+ * revoke: false = 只出授权语句(RECOVERY.md 的清权限按目标目录来,见 recoveryGrantsSql)。
130
131
  */
131
132
  export function grantStatements(objects, opts) {
132
133
  const roles = GRANT_ROLES.filter((role) => opts.roles.includes(role));
@@ -134,7 +135,7 @@ export function grantStatements(objects, opts) {
134
135
  const statements = [];
135
136
  const columns = [];
136
137
  for (const o of objects) {
137
- if (o.kind !== "column") {
138
+ if (o.kind !== "column" && opts.revoke !== false) {
138
139
  statements.push(`revoke all on ${objectClause(o)} from ${revokeFrom}`);
139
140
  }
140
141
  for (const role of roles) {
@@ -278,19 +279,135 @@ export function grantsCheck(outcome, context) {
278
279
  `service_role ${legacyScope}. Newer backups record the grants`,
279
280
  };
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
+ }
281
293
  /**
282
- * RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用)。有记录就逐个对象照记录重建,
283
- * 和 restoreGrants 同一套语句;旧快照没有记录,给 Supabase 以前的默认授权。
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 以前的默认授权。
284
303
  * MAINTAIN 只会出现在 PG17+ 源库的记录里,而恢复目标的版本不低于源库,所以照写。
304
+ *
305
+ * 2.9.0 收的是授权数组(旧快照传 undefined),照旧接受:记录里每个备份的 schema 都有一条 schema 条目,
306
+ * 范围从它取。
285
307
  */
286
- export function recoveryGrantsSql(grants) {
287
- if (grants === undefined) {
308
+ export function recoveryGrantsSql(database) {
309
+ const recorded = Array.isArray(database) ? database : database?.grants;
310
+ if (recorded === undefined) {
288
311
  return [
289
312
  "grant all on all tables in schema public to anon, authenticated, service_role;",
290
313
  "grant all on all sequences in schema public to anon, authenticated, service_role;",
291
314
  "grant execute on all functions in schema public to anon, authenticated, service_role;",
292
315
  ].join("\n");
293
316
  }
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)";
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};`;
296
413
  }
@@ -111,14 +111,16 @@ it drops and recreates \`public\`, and the grants Supabase put on it go with it.
111
111
  5. Set the grants for \`anon\`, \`authenticated\` and \`service_role\`. The dump
112
112
  carries none. With Supabase's new defaults, supabase-js requests to restored
113
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\`):`
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:`
116
118
  : `This snapshot was taken before BackupDrill recorded grants. The statements below
117
119
  give the three roles Supabase's old default access to everything in \`public\`;
118
120
  afterwards, revoke it on any table you had kept private:`}
119
121
 
120
122
  \`\`\`sql
121
- ${recoveryGrantsSql(db.grants)}
123
+ ${recoveryGrantsSql(db)}
122
124
  \`\`\`
123
125
 
124
126
  ## Restore Storage files
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backupdrill",
3
- "version": "2.9.0",
3
+ "version": "2.9.1",
4
4
  "description": "Open-source CLI to back up a Supabase project — Postgres database and Storage files — to your own S3/R2/B2 bucket, with a checksummed manifest.",
5
5
  "type": "module",
6
6
  "bin": {