@rebasepro/server-postgres 0.29.1 → 0.29.2
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/dist/{BranchService-BIIBF5ZL.js → BranchService-X9R505mP.js} +3 -3
- package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-X9R505mP.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +64 -4
- package/dist/PostgresBootstrapper.d.ts +20 -0
- package/dist/auth/ensure-tables.d.ts +2 -2
- package/dist/auth/schema-version.d.ts +5 -5
- package/dist/auth/services.d.ts +9 -9
- package/dist/{backup-cli-QcOpmRpQ.js → backup-cli-CwiJEp_J.js} +3 -3
- package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CwiJEp_J.js.map} +1 -1
- package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CbZj9ovZ.js} +2 -2
- package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CbZj9ovZ.js.map} +1 -1
- package/dist/{cli-console-DTsm96lW.js → cli-console-DDkNetCz.js} +6 -6
- package/dist/{cli-console-DTsm96lW.js.map → cli-console-DDkNetCz.js.map} +1 -1
- package/dist/{cli-errors-DwqFRIWz.js → cli-errors-C73Qy7WJ.js} +5 -5
- package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-C73Qy7WJ.js.map} +1 -1
- package/dist/cli.js +165 -49
- package/dist/cli.js.map +1 -1
- package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
- package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
- package/dist/data-transformer.d.ts +2 -2
- package/dist/database-health.d.ts +2 -1
- package/dist/{database-preflight-D5JtPt8i.js → database-preflight-DIauc8i5.js} +36 -3
- package/dist/database-preflight-DIauc8i5.js.map +1 -0
- package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
- package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
- package/dist/{deferred-index-build-B8feKnUj.js → deferred-index-build-DDdnjaOW.js} +18 -6
- package/dist/deferred-index-build-DDdnjaOW.js.map +1 -0
- package/dist/{doctor-BaR11xUe.js → doctor-DwMXljiq.js} +11 -11
- package/dist/doctor-DwMXljiq.js.map +1 -0
- package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-DJsOMpaI.js} +23 -13
- package/dist/ensure-collection-policies-DJsOMpaI.js.map +1 -0
- package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-h1mUO7Uu.js} +11 -8
- package/dist/ensure-collection-tables-h1mUO7Uu.js.map +1 -0
- package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-CUqYgMvo.js} +4 -4
- package/dist/ensure-tables-CUqYgMvo.js.map +1 -0
- package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-z7ustOl_.js} +3 -3
- package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-z7ustOl_.js.map} +1 -1
- package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-BIUqhSzh.js} +2 -2
- package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-BIUqhSzh.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-BBXjxm5z.js} +3 -3
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-BBXjxm5z.js.map} +1 -1
- package/dist/{generate-files-Bl3_D_oP.js → generate-files-BkiRFoV1.js} +3 -3
- package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-BkiRFoV1.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-G9PvjHrr.js} +10 -5
- package/dist/{generate-postgres-ddl-logic-BC3JA93M.js.map → generate-postgres-ddl-logic-G9PvjHrr.js.map} +1 -1
- package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-D2soazQU.js} +8 -5
- package/dist/generated-schema-diff-D2soazQU.js.map +1 -0
- package/dist/history/HistoryService.d.ts +2 -3
- package/dist/history/ensure-history-table.d.ts +8 -3
- package/dist/index.es.js +15 -15
- package/dist/interfaces.d.ts +24 -2
- package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
- package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
- package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CveNQli3.js} +163 -502
- package/dist/migrate-baseline-CveNQli3.js.map +1 -0
- package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-C4qbQ0jK.js} +42 -13
- package/dist/migrate-policy-stamps-C4qbQ0jK.js.map +1 -0
- package/dist/{open-rebase-CiO_sjMT.js → open-rebase-Cvid3iwR.js} +1395 -656
- package/dist/open-rebase-Cvid3iwR.js.map +1 -0
- package/dist/open-rebase.d.ts +1 -1
- package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-80uTIHQs.js} +2 -2
- package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-80uTIHQs.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +24 -37
- package/dist/{plan-schema-BYxOzflz.js → plan-schema-CMhNYEYF.js} +21 -6
- package/dist/plan-schema-CMhNYEYF.js.map +1 -0
- package/dist/{policy-drift-DKuTJHfc.js → policy-drift-Bx6663KD.js} +29 -6
- package/dist/policy-drift-Bx6663KD.js.map +1 -0
- package/dist/push-index-adoption-C-TpM445.js +22 -0
- package/dist/push-index-adoption-C-TpM445.js.map +1 -0
- package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-xbpgZEJK.js} +4 -4
- package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-xbpgZEJK.js.map} +1 -1
- package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-D-JEv0Gn.js} +2 -2
- package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-D-JEv0Gn.js.map} +1 -1
- package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-7UKspspl.js} +4 -4
- package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-7UKspspl.js.map} +1 -1
- package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BOw5PtU8.js} +14 -8
- package/dist/push-policy-plan-BOw5PtU8.js.map +1 -0
- package/dist/read-routing.d.ts +10 -30
- package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Di-fTGti.js} +15 -2
- package/dist/render-ddl-Di-fTGti.js.map +1 -0
- package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Bxxskru9.js} +10 -10
- package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Bxxskru9.js.map} +1 -1
- package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-BCW4v0rq.js} +2 -2
- package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-BCW4v0rq.js.map} +1 -1
- package/dist/rls-bootstrap-sql-CxszeSc7.js +534 -0
- package/dist/rls-bootstrap-sql-CxszeSc7.js.map +1 -0
- package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-CyUCPDH8.js} +213 -10
- package/dist/rls-enforcement-CyUCPDH8.js.map +1 -0
- package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
- package/dist/rls-settings-BCGMIig3.js.map +1 -0
- package/dist/schema/doctor-cli.js +9 -9
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/drizzle-ddl.d.ts +2 -2
- package/dist/schema/ensure-collection-policies.d.ts +15 -3
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/index-adoption.d.ts +99 -0
- package/dist/schema/introspect-db-logic.d.ts +2 -1
- package/dist/schema/introspect-db.js +3 -3
- package/dist/schema/migrate-policy-stamps.d.ts +19 -1
- package/dist/schema/plan/diff-plan.d.ts +8 -1
- package/dist/schema/plan/render-ddl.d.ts +7 -0
- package/dist/schema/plan/types.d.ts +2 -0
- package/dist/schema/push-index-adoption.d.ts +10 -0
- package/dist/schema/push-policy-plan.d.ts +5 -1
- package/dist/schema/rls-bootstrap-sql.d.ts +13 -2
- package/dist/schema/search-column.d.ts +2 -2
- package/dist/search-column-BM-GV6vH.js.map +1 -1
- package/dist/security/policy-drift.d.ts +19 -1
- package/dist/security/rls-enforcement.d.ts +87 -1
- package/dist/security/rls-settings.d.ts +33 -0
- package/dist/services/FetchService.d.ts +33 -8
- package/dist/services/PersistService.d.ts +75 -4
- package/dist/services/RelationService.d.ts +1 -1
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
- package/dist/services/channel-bus/index.d.ts +2 -2
- package/dist/services/channel-history.d.ts +2 -2
- package/dist/services/channel-presence.d.ts +3 -3
- package/dist/services/dataService.d.ts +6 -2
- package/dist/services/realtimeService.d.ts +18 -5
- package/dist/services/socket-liveness.d.ts +6 -1
- package/dist/types.d.ts +1 -1
- package/dist/utils/drizzle-conditions.d.ts +12 -0
- package/dist/utils/positional-params.d.ts +40 -0
- package/dist/{websocket-B33YjKhs.js → websocket-BSYV_KSw.js} +3 -3
- package/dist/websocket-BSYV_KSw.js.map +1 -0
- package/dist/websocket.d.ts +14 -3
- package/package.json +7 -7
- package/dist/database-preflight-D5JtPt8i.js.map +0 -1
- package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
- package/dist/doctor-BaR11xUe.js.map +0 -1
- package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
- package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
- package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
- package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
- package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
- package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
- package/dist/open-rebase-CiO_sjMT.js.map +0 -1
- package/dist/plan-schema-BYxOzflz.js.map +0 -1
- package/dist/policy-drift-DKuTJHfc.js.map +0 -1
- package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
- package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
- package/dist/rls-enforcement-BO618rnr.js.map +0 -1
- package/dist/rls-settings-De5NoHHy.js.map +0 -1
- package/dist/websocket-B33YjKhs.js.map +0 -1
package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-BCW4v0rq.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request-role-migration-D9BZ5Uba.js","names":[],"sources":["../src/security/request-role-migration.ts"],"sourcesContent":["import { ensureAppRole, recordRequestRoles, type RawSqlRunner } from \"./rls-enforcement\";\n\n/**\n * Move a database from one set of request roles to another — what\n * `rebase db request-role migrate --to …` runs.\n *\n * A role belongs to the cluster, so renaming one (`ALTER ROLE … RENAME`) moves\n * every database's grants at once, including another project's that shares\n * it. This instead creates the new role(s) and re-issues, in THIS database\n * only, every grant the old ones hold here: tables and views, columns,\n * sequences, schemas, functions, the default privileges this connection set,\n * and the memberships that carry other roles' policies (`rls.inheritRoles`).\n * Policies that name an old role in their `TO` list are re-pointed. The old\n * roles are left as they are — another database may still use them — and the\n * statements to take their grants back here are returned for the operator.\n */\nexport interface RequestRoleMigrationPlan {\n /** What to run, in order, to give the new roles what the old ones hold here. */\n statements: string[];\n /** What would take the old roles' grants back in this database, for the operator to run once satisfied. */\n revokeOld: string[];\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\nconst sqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\nconst textArray = (values: readonly string[]): string =>\n values.length === 0 ? \"ARRAY[]::text[]\" : `ARRAY[${values.map(sqlLiteral).join(\", \")}]::text[]`;\n\n/** Which new role(s) each old role's grants go to: one old to every new, or pairwise. */\nfunction roleMapping(from: readonly string[], to: readonly string[]): Map<string, string[]> {\n if (from.length === 1) return new Map([[from[0], [...to]]]);\n if (from.length === to.length) return new Map(from.map((role, i) => [role, [to[i]]]));\n throw new Error(\n `Cannot map ${from.length} request roles (${from.join(\", \")}) onto ${to.length} (${to.join(\", \")}): ` +\n \"move from one role to any number, or between two lists of the same length (pairwise, in order).\"\n );\n}\n\n/**\n * Read the catalogue and plan the move. Writes nothing; {@link migrateRequestRoles}\n * runs the plan.\n */\nexport async function planRequestRoleMigration(\n run: RawSqlRunner,\n from: readonly string[],\n to: readonly string[]\n): Promise<RequestRoleMigrationPlan> {\n const mapping = roleMapping(from, to);\n const statements: string[] = [];\n const revokeOld: string[] = [];\n const grantee = `(SELECT oid FROM pg_roles WHERE rolname = r.name)`;\n const userSchemas = \"n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg\\\\_%'\";\n const oldRoles = textArray(from);\n\n const relations = await run(`\n SELECT r.name AS role, n.nspname AS schema, c.relname AS name, c.relkind AS kind,\n a.privilege_type AS privilege, a.is_grantable AS grantable\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_class c ON c.relacl IS NOT NULL\n JOIN pg_namespace n ON n.oid = c.relnamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(c.relacl) a\n WHERE a.grantee = ${grantee} AND c.relkind IN ('r', 'v', 'm', 'f', 'p', 'S')\n ORDER BY 2, 3, 5\n `);\n for (const row of relations) {\n const target = `${row.kind === \"S\" ? \"SEQUENCE\" : \"TABLE\"} ${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))}`;\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} ON ${target} TO ${quoteIdent(role)}${row.grantable === true ? \" WITH GRANT OPTION\" : \"\"}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} ON ${target} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const columns = await run(`\n SELECT r.name AS role, n.nspname AS schema, c.relname AS name, att.attname AS col, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_attribute att ON att.attacl IS NOT NULL AND NOT att.attisdropped\n JOIN pg_class c ON c.oid = att.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(att.attacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2, 3, 4\n `);\n for (const row of columns) {\n const target = `${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))}`;\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} (${quoteIdent(String(row.col))}) ON TABLE ${target} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} (${quoteIdent(String(row.col))}) ON TABLE ${target} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const schemas = await run(`\n SELECT r.name AS role, n.nspname AS schema, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_namespace n ON n.nspacl IS NOT NULL AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(n.nspacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2\n `);\n for (const row of schemas) {\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} ON SCHEMA ${quoteIdent(String(row.schema))} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} ON SCHEMA ${quoteIdent(String(row.schema))} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const functions = await run(`\n SELECT r.name AS role, p.oid::regprocedure::text AS signature\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_proc p ON p.proacl IS NOT NULL\n JOIN pg_namespace n ON n.oid = p.pronamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(p.proacl) a\n WHERE a.grantee = ${grantee} AND a.privilege_type = 'EXECUTE'\n ORDER BY 2\n `);\n for (const row of functions) {\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT EXECUTE ON FUNCTION ${row.signature} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE EXECUTE ON FUNCTION ${row.signature} FROM ${quoteIdent(String(row.role))}`);\n }\n\n // Default privileges this connection set: what makes tables created later\n // reachable. Ones another role set are that role's to change.\n const defaults = await run(`\n SELECT r.name AS role, n.nspname AS schema, d.defaclobjtype AS kind, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_default_acl d ON d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace\n CROSS JOIN LATERAL aclexplode(d.defaclacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2, 3, 4\n `);\n const objectKinds: Record<string, string> = { r: \"TABLES\", S: \"SEQUENCES\", f: \"FUNCTIONS\", T: \"TYPES\", n: \"SCHEMAS\" };\n for (const row of defaults) {\n const kind = objectKinds[String(row.kind)];\n if (!kind) continue;\n const scope = row.schema ? ` IN SCHEMA ${quoteIdent(String(row.schema))}` : \"\";\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`ALTER DEFAULT PRIVILEGES${scope} GRANT ${row.privilege} ON ${kind} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`ALTER DEFAULT PRIVILEGES${scope} REVOKE ${row.privilege} ON ${kind} FROM ${quoteIdent(String(row.role))}`);\n }\n\n // Memberships that carry another role's policies (rls.inheritRoles):\n // the inherit option goes with them, from PostgreSQL 16.\n // `inherit_option` is a column from 16 on, and naming it before then fails\n // the statement whatever a CASE around it says.\n const [server] = await run(\"SELECT current_setting('server_version_num')::int >= 160000 AS per_grant\");\n const memberships = await run(`\n SELECT r.name AS role, g.rolname AS member_of,\n ${server?.per_grant === true ? \"m.inherit_option\" : \"false\"} AS inherits\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_auth_members m ON m.member = ${grantee}\n JOIN pg_roles g ON g.oid = m.roleid\n ORDER BY 2\n `);\n for (const row of memberships) {\n const option = row.inherits === true ? \" WITH INHERIT TRUE, SET FALSE\" : \"\";\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${quoteIdent(String(row.member_of))} TO ${quoteIdent(role)}${option}`);\n }\n }\n\n // Policies that name an old role: re-pointed, keeping every other role.\n const policies = await run(`\n SELECT p.schemaname AS schema, p.tablename AS name, p.policyname AS policy, p.roles::text[] AS roles\n FROM pg_policies p\n WHERE p.roles && ${oldRoles}::name[]\n ORDER BY 1, 2, 3\n `);\n for (const row of policies) {\n const current = Array.isArray(row.roles)\n ? row.roles.map(String)\n : String(row.roles ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean);\n const next = Array.from(new Set(current.flatMap((r) => mapping.get(r) ?? [r])));\n statements.push(\n `ALTER POLICY ${quoteIdent(String(row.policy))} ON ${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))} ` +\n `TO ${next.map((r) => (r === \"public\" ? \"public\" : quoteIdent(r))).join(\", \")}`\n );\n }\n\n return { statements, revokeOld };\n}\n\n/**\n * Provision the new role(s), run the plan, and record the new roles — in one\n * transaction where the runner has one, so a failure leaves the database on\n * its old roles. Returns the plan that ran.\n */\nexport async function migrateRequestRoles(\n run: RawSqlRunner,\n options: { from: readonly string[]; to: readonly string[]; schemas: readonly string[] }\n): Promise<RequestRoleMigrationPlan> {\n const plan = await planRequestRoleMigration(run, options.from, options.to);\n // The role and the right to switch into it; the grants come from the plan.\n for (const role of options.to) await ensureAppRole(run, [...options.schemas], { role, grants: \"none\" });\n for (const statement of plan.statements) await run(statement);\n await recordRequestRoles(run, options.to);\n return plan;\n}\n"],"mappings":";;;;AAuBA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;AAC5E,IAAM,cAAc,UAA0B,IAAI,MAAM,QAAQ,MAAM,IAAI,EAAE;AAC5E,IAAM,aAAa,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I,SAAS,EAAE,CAAC,CAAC,QAAQ,YAAY,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;EAC/E,MAAM,OAAO,MAAM,KAAK,IAAI,IAAI,QAAQ,SAAS,MAAM,QAAQ,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;EAC9E,WAAW,KACP,gBAAgB,WAAW,OAAO,IAAI,MAAM,CAAC,EAAE,MAAM,WAAW,OAAO,IAAI,MAAM,CAAC,EAAE,GAAG,WAAW,OAAO,IAAI,IAAI,CAAC,EAAE,MAC9G,KAAK,KAAK,MAAO,MAAM,WAAW,WAAW,WAAW,CAAC,CAAE,CAAC,CAAC,KAAK,IAAI,GAChF;CACJ;CAEA,OAAO;EAAE;EAAY;CAAU;AACnC;;;;;;AAOA,eAAsB,oBAClB,KACA,SACiC;CACjC,MAAM,OAAO,MAAM,yBAAyB,KAAK,QAAQ,MAAM,QAAQ,EAAE;CAEzE,KAAK,MAAM,QAAQ,QAAQ,IAAI,MAAM,cAAc,KAAK,CAAC,GAAG,QAAQ,OAAO,GAAG;EAAE;EAAM,QAAQ;CAAO,CAAC;CACtG,KAAK,MAAM,aAAa,KAAK,YAAY,MAAM,IAAI,SAAS;CAC5D,MAAM,mBAAmB,KAAK,QAAQ,EAAE;CACxC,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"request-role-migration-BCW4v0rq.js","names":[],"sources":["../src/security/request-role-migration.ts"],"sourcesContent":["import { ensureAppRole, recordRequestRoles, type RawSqlRunner } from \"./rls-enforcement\";\n\n/**\n * Move a database from one set of request roles to another — what\n * `rebase db request-role migrate --to …` runs.\n *\n * A role belongs to the cluster, so renaming one (`ALTER ROLE … RENAME`) moves\n * every database's grants at once, including another project's that shares\n * it. This instead creates the new role(s) and re-issues, in THIS database\n * only, every grant the old ones hold here: tables and views, columns,\n * sequences, schemas, functions, the default privileges this connection set,\n * and the memberships that carry other roles' policies (`rls.inheritRoles`).\n * Policies that name an old role in their `TO` list are re-pointed. The old\n * roles are left as they are — another database may still use them — and the\n * statements to take their grants back here are returned for the operator.\n */\nexport interface RequestRoleMigrationPlan {\n /** What to run, in order, to give the new roles what the old ones hold here. */\n statements: string[];\n /** What would take the old roles' grants back in this database, for the operator to run once satisfied. */\n revokeOld: string[];\n}\n\nconst quoteIdent = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\nconst sqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\nconst textArray = (values: readonly string[]): string =>\n values.length === 0 ? \"ARRAY[]::text[]\" : `ARRAY[${values.map(sqlLiteral).join(\", \")}]::text[]`;\n\n/** Which new role(s) each old role's grants go to: one old to every new, or pairwise. */\nfunction roleMapping(from: readonly string[], to: readonly string[]): Map<string, string[]> {\n if (from.length === 1) return new Map([[from[0], [...to]]]);\n if (from.length === to.length) return new Map(from.map((role, i) => [role, [to[i]]]));\n throw new Error(\n `Cannot map ${from.length} request roles (${from.join(\", \")}) onto ${to.length} (${to.join(\", \")}): ` +\n \"move from one role to any number, or between two lists of the same length (pairwise, in order).\"\n );\n}\n\n/**\n * Read the catalogue and plan the move. Writes nothing; {@link migrateRequestRoles}\n * runs the plan.\n */\nexport async function planRequestRoleMigration(\n run: RawSqlRunner,\n from: readonly string[],\n to: readonly string[]\n): Promise<RequestRoleMigrationPlan> {\n const mapping = roleMapping(from, to);\n const statements: string[] = [];\n const revokeOld: string[] = [];\n const grantee = `(SELECT oid FROM pg_roles WHERE rolname = r.name)`;\n const userSchemas = \"n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg\\\\_%'\";\n const oldRoles = textArray(from);\n\n const relations = await run(`\n SELECT r.name AS role, n.nspname AS schema, c.relname AS name, c.relkind AS kind,\n a.privilege_type AS privilege, a.is_grantable AS grantable\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_class c ON c.relacl IS NOT NULL\n JOIN pg_namespace n ON n.oid = c.relnamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(c.relacl) a\n WHERE a.grantee = ${grantee} AND c.relkind IN ('r', 'v', 'm', 'f', 'p', 'S')\n ORDER BY 2, 3, 5\n `);\n for (const row of relations) {\n const target = `${row.kind === \"S\" ? \"SEQUENCE\" : \"TABLE\"} ${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))}`;\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} ON ${target} TO ${quoteIdent(role)}${row.grantable === true ? \" WITH GRANT OPTION\" : \"\"}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} ON ${target} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const columns = await run(`\n SELECT r.name AS role, n.nspname AS schema, c.relname AS name, att.attname AS col, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_attribute att ON att.attacl IS NOT NULL AND NOT att.attisdropped\n JOIN pg_class c ON c.oid = att.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(att.attacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2, 3, 4\n `);\n for (const row of columns) {\n const target = `${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))}`;\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} (${quoteIdent(String(row.col))}) ON TABLE ${target} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} (${quoteIdent(String(row.col))}) ON TABLE ${target} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const schemas = await run(`\n SELECT r.name AS role, n.nspname AS schema, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_namespace n ON n.nspacl IS NOT NULL AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(n.nspacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2\n `);\n for (const row of schemas) {\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${row.privilege} ON SCHEMA ${quoteIdent(String(row.schema))} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE ${row.privilege} ON SCHEMA ${quoteIdent(String(row.schema))} FROM ${quoteIdent(String(row.role))}`);\n }\n\n const functions = await run(`\n SELECT r.name AS role, p.oid::regprocedure::text AS signature\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_proc p ON p.proacl IS NOT NULL\n JOIN pg_namespace n ON n.oid = p.pronamespace AND ${userSchemas}\n CROSS JOIN LATERAL aclexplode(p.proacl) a\n WHERE a.grantee = ${grantee} AND a.privilege_type = 'EXECUTE'\n ORDER BY 2\n `);\n for (const row of functions) {\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT EXECUTE ON FUNCTION ${row.signature} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`REVOKE EXECUTE ON FUNCTION ${row.signature} FROM ${quoteIdent(String(row.role))}`);\n }\n\n // Default privileges this connection set: what makes tables created later\n // reachable. Ones another role set are that role's to change.\n const defaults = await run(`\n SELECT r.name AS role, n.nspname AS schema, d.defaclobjtype AS kind, a.privilege_type AS privilege\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_default_acl d ON d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)\n LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace\n CROSS JOIN LATERAL aclexplode(d.defaclacl) a\n WHERE a.grantee = ${grantee}\n ORDER BY 2, 3, 4\n `);\n const objectKinds: Record<string, string> = { r: \"TABLES\", S: \"SEQUENCES\", f: \"FUNCTIONS\", T: \"TYPES\", n: \"SCHEMAS\" };\n for (const row of defaults) {\n const kind = objectKinds[String(row.kind)];\n if (!kind) continue;\n const scope = row.schema ? ` IN SCHEMA ${quoteIdent(String(row.schema))}` : \"\";\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`ALTER DEFAULT PRIVILEGES${scope} GRANT ${row.privilege} ON ${kind} TO ${quoteIdent(role)}`);\n }\n revokeOld.push(`ALTER DEFAULT PRIVILEGES${scope} REVOKE ${row.privilege} ON ${kind} FROM ${quoteIdent(String(row.role))}`);\n }\n\n // Memberships that carry another role's policies (rls.inheritRoles):\n // the inherit option goes with them, from PostgreSQL 16.\n // `inherit_option` is a column from 16 on, and naming it before then fails\n // the statement whatever a CASE around it says.\n const [server] = await run(\"SELECT current_setting('server_version_num')::int >= 160000 AS per_grant\");\n const memberships = await run(`\n SELECT r.name AS role, g.rolname AS member_of,\n ${server?.per_grant === true ? \"m.inherit_option\" : \"false\"} AS inherits\n FROM unnest(${oldRoles}) AS r(name)\n JOIN pg_auth_members m ON m.member = ${grantee}\n JOIN pg_roles g ON g.oid = m.roleid\n ORDER BY 2\n `);\n for (const row of memberships) {\n const option = row.inherits === true ? \" WITH INHERIT TRUE, SET FALSE\" : \"\";\n for (const role of mapping.get(String(row.role)) ?? []) {\n statements.push(`GRANT ${quoteIdent(String(row.member_of))} TO ${quoteIdent(role)}${option}`);\n }\n }\n\n // Policies that name an old role: re-pointed, keeping every other role.\n const policies = await run(`\n SELECT p.schemaname AS schema, p.tablename AS name, p.policyname AS policy, p.roles::text[] AS roles\n FROM pg_policies p\n WHERE p.roles && ${oldRoles}::name[]\n ORDER BY 1, 2, 3\n `);\n for (const row of policies) {\n const current = Array.isArray(row.roles)\n ? row.roles.map(String)\n : String(row.roles ?? \"\").replace(/^\\{|\\}$/g, \"\").split(\",\").filter(Boolean);\n const next = Array.from(new Set(current.flatMap((r) => mapping.get(r) ?? [r])));\n statements.push(\n `ALTER POLICY ${quoteIdent(String(row.policy))} ON ${quoteIdent(String(row.schema))}.${quoteIdent(String(row.name))} ` +\n `TO ${next.map((r) => (r === \"public\" ? \"public\" : quoteIdent(r))).join(\", \")}`\n );\n }\n\n return { statements, revokeOld };\n}\n\n/**\n * Provision the new role(s), run the plan, and record the new roles — in one\n * transaction where the runner has one, so a failure leaves the database on\n * its old roles. Returns the plan that ran.\n */\nexport async function migrateRequestRoles(\n run: RawSqlRunner,\n options: { from: readonly string[]; to: readonly string[]; schemas: readonly string[] }\n): Promise<RequestRoleMigrationPlan> {\n const plan = await planRequestRoleMigration(run, options.from, options.to);\n // The role and the right to switch into it; the grants come from the plan.\n for (const role of options.to) await ensureAppRole(run, [...options.schemas], { role, grants: \"none\" });\n for (const statement of plan.statements) await run(statement);\n await recordRequestRoles(run, options.to);\n return plan;\n}\n"],"mappings":";;;;AAuBA,IAAM,cAAc,SAAyB,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE;AAC5E,IAAM,cAAc,UAA0B,IAAI,MAAM,QAAQ,MAAM,IAAI,EAAE;AAC5E,IAAM,aAAa,WACf,OAAO,WAAW,IAAI,oBAAoB,SAAS,OAAO,IAAI,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE;;AAGzF,SAAS,YAAY,MAAyB,IAA8C;CACxF,IAAI,KAAK,WAAW,GAAG,uBAAO,IAAI,IAAI,CAAC,CAAC,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;CAC1D,IAAI,KAAK,WAAW,GAAG,QAAQ,OAAO,IAAI,IAAI,KAAK,KAAK,MAAM,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;CACpF,MAAM,IAAI,MACN,cAAc,KAAK,OAAO,kBAAkB,KAAK,KAAK,IAAI,EAAE,SAAS,GAAG,OAAO,IAAI,GAAG,KAAK,IAAI,EAAE,mGAErG;AACJ;;;;;AAMA,eAAsB,yBAClB,KACA,MACA,IACiC;CACjC,MAAM,UAAU,YAAY,MAAM,EAAE;CACpC,MAAM,aAAuB,CAAC;CAC9B,MAAM,YAAsB,CAAC;CAC7B,MAAM,UAAU;CAChB,MAAM,cAAc;CACpB,MAAM,WAAW,UAAU,IAAI;CAE/B,MAAM,YAAY,MAAM,IAAI;;;sBAGV,SAAS;;4DAE6B,YAAY;;4BAE5C,QAAQ;;KAE/B;CACD,KAAK,MAAM,OAAO,WAAW;EACzB,MAAM,SAAS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ACX"}
|
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "module";
|
|
2
|
+
__createRequire(import.meta.url);
|
|
3
|
+
import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
|
|
4
|
+
import { LEGACY_RLS_SCHEMA, REBASE_ADMIN_ROLE, REBASE_SCHEMA } from "@rebasepro/types";
|
|
5
|
+
import { sqlRows } from "@rebasepro/common";
|
|
6
|
+
//#region src/schema/rls-bootstrap-sql.ts
|
|
7
|
+
var rls_bootstrap_sql_exports = /* @__PURE__ */ __exportAll({
|
|
8
|
+
ADMIN_POLICY_ROLE_SQL: () => ADMIN_POLICY_ROLE_SQL,
|
|
9
|
+
DROP_LEGACY_AUTH_SCHEMA_SQL: () => DROP_LEGACY_AUTH_SCHEMA_SQL,
|
|
10
|
+
LEGACY_AUTH_SCHEMA_CONTENTS_SQL: () => LEGACY_AUTH_SCHEMA_CONTENTS_SQL,
|
|
11
|
+
LEGACY_RLS_DEPENDENTS_SQL: () => LEGACY_RLS_DEPENDENTS_SQL,
|
|
12
|
+
LEGACY_RLS_FUNCTION_DEPENDENTS_SQL: () => LEGACY_RLS_FUNCTION_DEPENDENTS_SQL,
|
|
13
|
+
REQUEST_ROLE_FUNCTION_SQL: () => REQUEST_ROLE_FUNCTION_SQL,
|
|
14
|
+
RLS_BOOTSTRAP_SQL: () => RLS_BOOTSTRAP_SQL,
|
|
15
|
+
RLS_BOOTSTRAP_STATEMENTS: () => RLS_BOOTSTRAP_STATEMENTS,
|
|
16
|
+
dropLegacyAuthSchema: () => dropLegacyAuthSchema,
|
|
17
|
+
ensureAdminPolicyRole: () => ensureAdminPolicyRole,
|
|
18
|
+
ensureRequestRoleFunction: () => ensureRequestRoleFunction,
|
|
19
|
+
rlsRuntimeIsCurrent: () => rlsRuntimeIsCurrent
|
|
20
|
+
});
|
|
21
|
+
/**
|
|
22
|
+
* Canonical SQL bootstrap for the RLS helper functions.
|
|
23
|
+
*
|
|
24
|
+
* Generated RLS policies reference `rebase.uid()` / `rebase.roles()` /
|
|
25
|
+
* `rebase.jwt()`, so any SQL stream that can contain policies must be
|
|
26
|
+
* self-contained: it has to (re)create these helpers first. This matters for
|
|
27
|
+
* the migration directory in particular — Atlas replays migrations against a
|
|
28
|
+
* clean dev database where no out-of-band bootstrap has ever run, so a
|
|
29
|
+
* migration carrying policies without this preamble fails with
|
|
30
|
+
* "function rebase.uid() does not exist".
|
|
31
|
+
*
|
|
32
|
+
* Idempotent (`IF NOT EXISTS` / `OR REPLACE`) so it can be prepended to every
|
|
33
|
+
* policies block and re-applied freely. The runtime boot path
|
|
34
|
+
* (`auth/ensure-tables.ts`) creates the same functions under an advisory lock
|
|
35
|
+
* for HMR-safety; keep the definitions in sync.
|
|
36
|
+
*
|
|
37
|
+
* ## Creating the `rebase` schema here is now safe, and required
|
|
38
|
+
*
|
|
39
|
+
* It deliberately did not, once. These functions lived in a schema called
|
|
40
|
+
* `auth`, and the note here read: creating `rebase` would leak it into Atlas's
|
|
41
|
+
* replayed migration state, and — absent from the desired `schema.sql` — Atlas
|
|
42
|
+
* would then plan `DROP SCHEMA "rebase" CASCADE`, taking the auth tables with
|
|
43
|
+
* it. That reasoning still holds; what changed is the second half of it. The
|
|
44
|
+
* DDL generator now emits `CREATE SCHEMA IF NOT EXISTS "rebase"`
|
|
45
|
+
* unconditionally, so the schema is always in the desired state and the diff is
|
|
46
|
+
* empty. (It used to appear only when some collection happened to declare
|
|
47
|
+
* `schema: "rebase"` — true for the scaffold's users collection, and not a
|
|
48
|
+
* property anything guaranteed.) `db push` additionally excludes the whole
|
|
49
|
+
* schema from the declarative apply.
|
|
50
|
+
*
|
|
51
|
+
* See `@rebasepro/types`' `rls-functions` for why the functions moved out of
|
|
52
|
+
* `auth` at all: the short version is that the name was Supabase's, and
|
|
53
|
+
* `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` cannot be applied over
|
|
54
|
+
* Supabase's `RETURNS uuid` — Postgres refuses, and the refusal used to be
|
|
55
|
+
* swallowed.
|
|
56
|
+
*/
|
|
57
|
+
/**
|
|
58
|
+
* The bootstrap as individual statements.
|
|
59
|
+
*
|
|
60
|
+
* Kept as an array because the two consumers need different shapes and only one
|
|
61
|
+
* of them can take a multi-command string: the migration preamble is written to
|
|
62
|
+
* a file and replayed by Atlas, but the boot path runs through drizzle, whose
|
|
63
|
+
* node-postgres handle speaks the extended query protocol and rejects more than
|
|
64
|
+
* one command per call. Splitting a joined string back apart on `$$;` would be
|
|
65
|
+
* a parser for a problem that does not need one.
|
|
66
|
+
*/
|
|
67
|
+
var RLS_BOOTSTRAP_STATEMENTS = [
|
|
68
|
+
`CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`,
|
|
69
|
+
`CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.uid() RETURNS text AS $$
|
|
70
|
+
SELECT COALESCE(
|
|
71
|
+
NULLIF(current_setting('app.uid', true), ''),
|
|
72
|
+
NULLIF(current_setting('app.user_id', true), '')
|
|
73
|
+
);
|
|
74
|
+
$$ LANGUAGE sql STABLE PARALLEL SAFE`,
|
|
75
|
+
`CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.jwt() RETURNS jsonb AS $$
|
|
76
|
+
SELECT COALESCE(
|
|
77
|
+
NULLIF(current_setting('app.jwt', true), ''),
|
|
78
|
+
'{}'
|
|
79
|
+
)::jsonb;
|
|
80
|
+
$$ LANGUAGE sql STABLE PARALLEL SAFE`,
|
|
81
|
+
`CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.roles() RETURNS text AS $$
|
|
82
|
+
SELECT COALESCE(NULLIF(current_setting('app.user_roles', true), ''), '');
|
|
83
|
+
$$ LANGUAGE sql STABLE PARALLEL SAFE`,
|
|
84
|
+
`CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_anonymous() RETURNS boolean AS $$
|
|
85
|
+
SELECT COALESCE(NULLIF(current_setting('app.is_anonymous', true), ''), 'false')::boolean;
|
|
86
|
+
$$ LANGUAGE sql STABLE PARALLEL SAFE`
|
|
87
|
+
];
|
|
88
|
+
/** Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one comparable string. */
|
|
89
|
+
var describeFunction = (facts) => JSON.stringify([
|
|
90
|
+
facts.returns.toLowerCase(),
|
|
91
|
+
facts.language.toLowerCase(),
|
|
92
|
+
facts.volatility,
|
|
93
|
+
facts.strict,
|
|
94
|
+
facts.parallel,
|
|
95
|
+
facts.securityDefiner,
|
|
96
|
+
facts.leakproof,
|
|
97
|
+
facts.cost,
|
|
98
|
+
facts.hasConfig,
|
|
99
|
+
facts.body
|
|
100
|
+
]);
|
|
101
|
+
/**
|
|
102
|
+
* What each `CREATE OR REPLACE FUNCTION` in {@link RLS_BOOTSTRAP_STATEMENTS}
|
|
103
|
+
* would leave in the catalogue, by `schema.name`. Parsed
|
|
104
|
+
* from the statements themselves, so the two cannot drift; a statement this
|
|
105
|
+
* does not recognise makes {@link rlsRuntimeIsCurrent} answer "no", and the
|
|
106
|
+
* bootstrap runs as it always did.
|
|
107
|
+
*/
|
|
108
|
+
var expectedRlsFunctions = () => {
|
|
109
|
+
const expected = /* @__PURE__ */ new Map();
|
|
110
|
+
for (const statement of RLS_BOOTSTRAP_STATEMENTS) {
|
|
111
|
+
if (/^CREATE SCHEMA IF NOT EXISTS /.test(statement)) continue;
|
|
112
|
+
const match = /^CREATE OR REPLACE FUNCTION (\w+)\.(\w+)\(\) RETURNS (\w+) AS \$\$([\s\S]*)\$\$ LANGUAGE (\w+) (IMMUTABLE|STABLE|VOLATILE)(?: PARALLEL (SAFE|RESTRICTED|UNSAFE))?$/.exec(statement);
|
|
113
|
+
if (!match) return void 0;
|
|
114
|
+
const [, schema, name, returns, body, language, volatility, parallel] = match;
|
|
115
|
+
expected.set(`${schema}.${name}`, describeFunction({
|
|
116
|
+
returns,
|
|
117
|
+
language,
|
|
118
|
+
volatility: volatility[0].toLowerCase(),
|
|
119
|
+
strict: false,
|
|
120
|
+
parallel: (parallel ?? "UNSAFE")[0].toLowerCase(),
|
|
121
|
+
securityDefiner: false,
|
|
122
|
+
leakproof: false,
|
|
123
|
+
cost: 100,
|
|
124
|
+
hasConfig: false,
|
|
125
|
+
body
|
|
126
|
+
}));
|
|
127
|
+
}
|
|
128
|
+
return expected;
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Whether the `rebase` schema and every RLS helper function are exactly what
|
|
132
|
+
* {@link RLS_BOOTSTRAP_STATEMENTS} would make them — one catalogue read.
|
|
133
|
+
*
|
|
134
|
+
* The boot ran those statements unconditionally, on every boot and on every
|
|
135
|
+
* source: four `CREATE OR REPLACE FUNCTION`s in a transaction under an
|
|
136
|
+
* advisory lock. Replacing a function rewrites its `pg_proc` row even when
|
|
137
|
+
* nothing changed, and every cached plan that inlined it — every plan of every
|
|
138
|
+
* statement a policy applies to, on every connection — is invalidated by it.
|
|
139
|
+
* A function that differs in anything `CREATE OR REPLACE` sets (body,
|
|
140
|
+
* language, volatility, strictness, parallel safety, security, leakproofness,
|
|
141
|
+
* cost, `SET` options), or is missing, answers `false`, and the statements run
|
|
142
|
+
* as before.
|
|
143
|
+
*/
|
|
144
|
+
async function rlsRuntimeIsCurrent(run) {
|
|
145
|
+
const expected = expectedRlsFunctions();
|
|
146
|
+
if (!expected) return false;
|
|
147
|
+
const rows = await run(`SELECT n.nspname AS schema, p.proname AS name, pg_get_function_identity_arguments(p.oid) AS args,
|
|
148
|
+
format_type(p.prorettype, NULL) AS returns, l.lanname AS language,
|
|
149
|
+
p.provolatile::text AS volatility, p.proisstrict AS strict, p.proparallel::text AS parallel,
|
|
150
|
+
p.prosecdef AS security_definer, p.proleakproof AS leakproof, p.procost AS cost,
|
|
151
|
+
p.proconfig IS NOT NULL AS has_config, p.prosrc AS body
|
|
152
|
+
FROM pg_proc p
|
|
153
|
+
JOIN pg_namespace n ON p.pronamespace = n.oid
|
|
154
|
+
JOIN pg_language l ON p.prolang = l.oid
|
|
155
|
+
WHERE (n.nspname, p.proname) IN (${[...expected.keys()].map((key) => key.split(".")).map(([schema, name]) => `('${schema}', '${name}')`).join(", ")})`);
|
|
156
|
+
const live = /* @__PURE__ */ new Map();
|
|
157
|
+
for (const row of rows) {
|
|
158
|
+
if (String(row.args ?? "") !== "") continue;
|
|
159
|
+
live.set(`${row.schema}.${row.name}`, describeFunction({
|
|
160
|
+
returns: String(row.returns),
|
|
161
|
+
language: String(row.language),
|
|
162
|
+
volatility: String(row.volatility),
|
|
163
|
+
strict: row.strict === true,
|
|
164
|
+
parallel: String(row.parallel),
|
|
165
|
+
securityDefiner: row.security_definer === true,
|
|
166
|
+
leakproof: row.leakproof === true,
|
|
167
|
+
cost: Number(row.cost),
|
|
168
|
+
hasConfig: row.has_config === true,
|
|
169
|
+
body: String(row.body)
|
|
170
|
+
}));
|
|
171
|
+
}
|
|
172
|
+
for (const [key, definition] of expected) if (live.get(key) !== definition) return false;
|
|
173
|
+
return true;
|
|
174
|
+
}
|
|
175
|
+
/** The same statements as one script, for migration files and raw clients. */
|
|
176
|
+
var RLS_BOOTSTRAP_SQL = "-- Rebase schema + RLS helper functions (required by the policies below)\n" + RLS_BOOTSTRAP_STATEMENTS.map((s) => `${s};`).join("\n\n") + "\n";
|
|
177
|
+
/**
|
|
178
|
+
* The three functions every pre-1.0 release put in `auth`. (The auth tables
|
|
179
|
+
* lived in `rebase`, or wherever the users collection was declared.)
|
|
180
|
+
*
|
|
181
|
+
* `uid()` is matched on either spelling of the principal because Rebase wrote
|
|
182
|
+
* both. Until v0.10.0 its body was
|
|
183
|
+
* `SELECT NULLIF(current_setting('app.user_id', true), '')`; v0.10.0 renamed
|
|
184
|
+
* the GUC to `app.uid` and kept `app.user_id` as a fallback; v0.14.0 moved the
|
|
185
|
+
* helpers to `rebase`. A database last booted before v0.10.0 therefore holds an
|
|
186
|
+
* `auth.uid()` that reads `app.user_id` alone — as does anything that copied
|
|
187
|
+
* that body, the Rebase control plane included — and matching `app.uid` only
|
|
188
|
+
* left every one of them in place, with the schema around it.
|
|
189
|
+
*
|
|
190
|
+
* This is the one place either spelling is listed: the drop and the report of
|
|
191
|
+
* what it left are both generated from it, so they cannot disagree about which
|
|
192
|
+
* functions are Rebase's.
|
|
193
|
+
*/
|
|
194
|
+
var LEGACY_AUTH_HELPERS = [
|
|
195
|
+
{
|
|
196
|
+
name: "uid",
|
|
197
|
+
returns: "text",
|
|
198
|
+
reads: ["app.uid", "app.user_id"]
|
|
199
|
+
},
|
|
200
|
+
{
|
|
201
|
+
name: "jwt",
|
|
202
|
+
returns: "jsonb",
|
|
203
|
+
reads: ["app.jwt"]
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
name: "roles",
|
|
207
|
+
returns: "text",
|
|
208
|
+
reads: ["app.user_roles"]
|
|
209
|
+
}
|
|
210
|
+
];
|
|
211
|
+
/**
|
|
212
|
+
* `pg_proc p` has a Rebase helper's name, arity and result type: what
|
|
213
|
+
* `CREATE OR REPLACE` would have left, whatever the body.
|
|
214
|
+
*
|
|
215
|
+
* Two things that share that shape are excluded outright: a body reading
|
|
216
|
+
* `request.jwt` (Supabase's helpers and anything modelled on them) and a
|
|
217
|
+
* function an extension installed (`pg_session_jwt` puts an `auth.jwt()
|
|
218
|
+
* RETURNS jsonb` in the same schema).
|
|
219
|
+
*/
|
|
220
|
+
var isLegacyHelperShaped = (helper) => `(
|
|
221
|
+
p.proname = '${helper.name}' AND p.pronargs = 0
|
|
222
|
+
AND pg_get_function_result(p.oid) = '${helper.returns}'
|
|
223
|
+
AND strpos(p.prosrc, 'request.jwt') = 0
|
|
224
|
+
AND NOT EXISTS (
|
|
225
|
+
SELECT 1 FROM pg_depend e
|
|
226
|
+
WHERE e.classid = 'pg_proc'::regclass AND e.objid = p.oid AND e.deptype = 'e'
|
|
227
|
+
))`;
|
|
228
|
+
/** `pg_proc p` is a helper Rebase wrote: its shape, and a body reading one of its GUCs. */
|
|
229
|
+
var isLegacyHelper = (helper) => `${isLegacyHelperShaped(helper)}
|
|
230
|
+
AND (${helper.reads.map((guc) => `strpos(p.prosrc, '${guc}') > 0`).join(" OR ")})`;
|
|
231
|
+
/**
|
|
232
|
+
* Removes the pre-1.0 `auth` schema, but only when Rebase is what put it there.
|
|
233
|
+
*
|
|
234
|
+
* ## Why this is safe against a Supabase database
|
|
235
|
+
*
|
|
236
|
+
* Two independent guards, and both have to pass:
|
|
237
|
+
*
|
|
238
|
+
* 1. **Each function is identified before it is dropped.** Ours returns `text`
|
|
239
|
+
* and reads the `app.uid` or `app.user_id` GUC; Supabase's returns `uuid`
|
|
240
|
+
* and reads `request.jwt.claims`. Nothing is dropped on a signature we did
|
|
241
|
+
* not write, so a Supabase database — where our `CREATE OR REPLACE` could
|
|
242
|
+
* never have succeeded in the first place, Postgres refusing to change a
|
|
243
|
+
* return type — matches nothing and this is a no-op. See
|
|
244
|
+
* {@link LEGACY_AUTH_HELPERS} for exactly what is matched.
|
|
245
|
+
* 2. **`DROP SCHEMA … RESTRICT`**, never CASCADE. If anything else at all still
|
|
246
|
+
* lives in `auth` (Supabase's `users` table, its other helpers), the drop
|
|
247
|
+
* fails and the schema stays. CASCADE here would be unrecoverable.
|
|
248
|
+
*
|
|
249
|
+
* ## Why it cannot run too early
|
|
250
|
+
*
|
|
251
|
+
* Postgres records a dependency from every RLS policy to the functions its body
|
|
252
|
+
* calls, so `DROP FUNCTION auth.uid()` fails for as long as a single policy
|
|
253
|
+
* still references it. That is the interlock, and it is load-bearing: the drop
|
|
254
|
+
* can only succeed once every policy has been recompiled to \`rebase.uid()\`.
|
|
255
|
+
* Callers therefore run this *after* applying policies, and treat a failure as
|
|
256
|
+
* "not yet — try again next boot" rather than as an error.
|
|
257
|
+
*/
|
|
258
|
+
var DROP_LEGACY_AUTH_SCHEMA_SQL = `
|
|
259
|
+
DO $rebase_drop_legacy$
|
|
260
|
+
DECLARE
|
|
261
|
+
dropped_any boolean := false;
|
|
262
|
+
BEGIN
|
|
263
|
+
-- Each function is matched on its own result type and body, so a schema
|
|
264
|
+
-- that merely shares the name keeps everything it has.
|
|
265
|
+
${LEGACY_AUTH_HELPERS.map((helper) => ` IF EXISTS (
|
|
266
|
+
SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
267
|
+
WHERE n.nspname = '${LEGACY_RLS_SCHEMA}' AND ${isLegacyHelper(helper)}
|
|
268
|
+
) THEN
|
|
269
|
+
DROP FUNCTION ${LEGACY_RLS_SCHEMA}.${helper.name}();
|
|
270
|
+
dropped_any := true;
|
|
271
|
+
END IF;`).join("\n\n")}
|
|
272
|
+
|
|
273
|
+
-- RESTRICT: only an empty schema goes. Anything else in there — including a
|
|
274
|
+
-- Supabase installation left untouched above — keeps it. Swallowed so the
|
|
275
|
+
-- helpers dropped above stay dropped; dropLegacyAuthSchema looks afterwards
|
|
276
|
+
-- and says what is left.
|
|
277
|
+
IF dropped_any THEN
|
|
278
|
+
BEGIN
|
|
279
|
+
EXECUTE 'DROP SCHEMA ${LEGACY_RLS_SCHEMA} RESTRICT';
|
|
280
|
+
EXCEPTION WHEN OTHERS THEN
|
|
281
|
+
NULL;
|
|
282
|
+
END;
|
|
283
|
+
END IF;
|
|
284
|
+
END
|
|
285
|
+
$rebase_drop_legacy$;
|
|
286
|
+
`;
|
|
287
|
+
/**
|
|
288
|
+
* What the `auth` schema holds, one row per object keeping it alive.
|
|
289
|
+
*
|
|
290
|
+
* No rows: the schema does not exist. A single row with a `null` object: it
|
|
291
|
+
* exists and is empty. Read from the namespace entries in `pg_depend`, which
|
|
292
|
+
* are what `DROP SCHEMA … RESTRICT` itself consults — minus whatever goes with
|
|
293
|
+
* its owner (a serial's sequence, an identity column's), which Postgres does not
|
|
294
|
+
* name either.
|
|
295
|
+
*/
|
|
296
|
+
var LEGACY_AUTH_SCHEMA_CONTENTS_SQL = `
|
|
297
|
+
SELECT pg_describe_object(d.classid, d.objid, d.objsubid) AS object,
|
|
298
|
+
CASE
|
|
299
|
+
WHEN d.classid <> 'pg_proc'::regclass THEN NULL
|
|
300
|
+
WHEN EXISTS (
|
|
301
|
+
SELECT 1 FROM pg_proc p
|
|
302
|
+
WHERE p.oid = d.objid
|
|
303
|
+
AND (${LEGACY_AUTH_HELPERS.map((helper) => `(${isLegacyHelper(helper)})`).join(" OR ")})
|
|
304
|
+
) THEN 'ours'
|
|
305
|
+
WHEN EXISTS (
|
|
306
|
+
SELECT 1 FROM pg_proc p
|
|
307
|
+
WHERE p.oid = d.objid
|
|
308
|
+
AND (${LEGACY_AUTH_HELPERS.map(isLegacyHelperShaped).join(" OR ")})
|
|
309
|
+
) THEN 'lookalike'
|
|
310
|
+
END AS helper
|
|
311
|
+
FROM pg_namespace n
|
|
312
|
+
LEFT JOIN pg_depend d
|
|
313
|
+
ON d.refclassid = 'pg_namespace'::regclass AND d.refobjid = n.oid AND d.deptype = 'n'
|
|
314
|
+
AND NOT EXISTS (
|
|
315
|
+
SELECT 1 FROM pg_depend o
|
|
316
|
+
WHERE o.classid = d.classid AND o.objid = d.objid AND o.deptype IN ('a', 'i')
|
|
317
|
+
)
|
|
318
|
+
WHERE n.nspname = '${LEGACY_RLS_SCHEMA}'
|
|
319
|
+
ORDER BY helper NULLS LAST, object
|
|
320
|
+
`;
|
|
321
|
+
/**
|
|
322
|
+
* Policies whose body still calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.
|
|
323
|
+
*
|
|
324
|
+
* Postgres will not drop a function a policy depends on, so this is exactly the
|
|
325
|
+
* set standing between a database and losing the legacy schema. Rebase's own
|
|
326
|
+
* policies leave the list on the next push or boot, when they are recompiled —
|
|
327
|
+
* anything still here afterwards is hand-written, will never be recompiled by
|
|
328
|
+
* anybody, and is the reason the drop keeps being skipped. Silence there would
|
|
329
|
+
* leave an operator staring at a schema the release notes said would go.
|
|
330
|
+
*/
|
|
331
|
+
var LEGACY_RLS_DEPENDENTS_SQL = `
|
|
332
|
+
SELECT n.nspname AS schema, c.relname AS "table", p.polname AS policy
|
|
333
|
+
FROM pg_policy p
|
|
334
|
+
JOIN pg_class c ON c.oid = p.polrelid
|
|
335
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
336
|
+
WHERE pg_get_expr(p.polqual, p.polrelid) ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
|
|
337
|
+
OR pg_get_expr(p.polwithcheck, p.polrelid) ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
|
|
338
|
+
ORDER BY 1, 2, 3
|
|
339
|
+
`;
|
|
340
|
+
/**
|
|
341
|
+
* Functions whose body calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.
|
|
342
|
+
*
|
|
343
|
+
* This is the half `DROP FUNCTION ... RESTRICT` cannot see, and the reason it
|
|
344
|
+
* needs its own query. Postgres records a dependency for a *policy* that calls a
|
|
345
|
+
* function, which is why the drop is safe against the policies above — but a
|
|
346
|
+
* `LANGUAGE sql` function whose body is a **string literal** is not parsed when
|
|
347
|
+
* it is created, so nothing is recorded and `RESTRICT` has nothing to refuse on.
|
|
348
|
+
* The drop succeeds and the caller is left pointing at a function that no longer
|
|
349
|
+
* exists, which fails at *query* time rather than at boot.
|
|
350
|
+
*
|
|
351
|
+
* A downstream project building on these helpers is not hypothetical: the Rebase
|
|
352
|
+
* control plane defined `auth.is_org_member(uuid)` and `auth.is_org_admin(uuid)`
|
|
353
|
+
* in this very schema, each calling `auth.uid()` in a string body, and eleven of
|
|
354
|
+
* its row-level-security policies went through them. Every one of those would
|
|
355
|
+
* have started failing the first time a recompile left no policy referencing
|
|
356
|
+
* `auth.uid()` directly — the drop's own precondition. (Its migration 0065 has
|
|
357
|
+
* since moved both to `public`, calling `rebase.uid()`.)
|
|
358
|
+
*
|
|
359
|
+
* Matching on the body text is the only option available, and it is deliberately
|
|
360
|
+
* broad: a false positive costs a schema that stays one release longer and says
|
|
361
|
+
* why, while a false negative costs somebody their policies.
|
|
362
|
+
*/
|
|
363
|
+
var LEGACY_RLS_FUNCTION_DEPENDENTS_SQL = `
|
|
364
|
+
SELECT n.nspname AS schema, p.proname AS function
|
|
365
|
+
FROM pg_proc p
|
|
366
|
+
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
367
|
+
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
368
|
+
AND NOT (n.nspname = '${LEGACY_RLS_SCHEMA}' AND p.proname IN ('uid', 'jwt', 'roles'))
|
|
369
|
+
AND p.prosrc ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
|
|
370
|
+
ORDER BY 1, 2
|
|
371
|
+
`;
|
|
372
|
+
/**
|
|
373
|
+
* Retire the pre-1.0 `auth` schema, reporting what is holding it back.
|
|
374
|
+
*
|
|
375
|
+
* The shared implementation behind the CLI's post-push step and the runtime's
|
|
376
|
+
* post-policy step. Both used to just fire {@link DROP_LEGACY_AUTH_SCHEMA_SQL}
|
|
377
|
+
* and swallow whatever came back, which is right for the ordinary case — a
|
|
378
|
+
* table not recompiled *yet* — and wrong for the one that never resolves: a
|
|
379
|
+
* hand-written policy nothing will ever rewrite. Then the schema stays forever
|
|
380
|
+
* and nothing ever says why.
|
|
381
|
+
*
|
|
382
|
+
* The drop itself had the same blind spot. A helper it did not recognise as
|
|
383
|
+
* Rebase's stayed, and so did anything else in the schema, behind a
|
|
384
|
+
* `DROP SCHEMA … RESTRICT` whose failure is swallowed so the helpers it did
|
|
385
|
+
* drop stay dropped. The control plane's `auth.uid()` was one such: it read
|
|
386
|
+
* `app.user_id` alone, the drop looked for `app.uid`, and the schema stayed
|
|
387
|
+
* with no word said. So the schema is read twice. Before, so that one with no
|
|
388
|
+
* Rebase helper in it is left alone: one already gone, as on every boot after
|
|
389
|
+
* the drop, or one that was never Rebase's, like Supabase's — whose own
|
|
390
|
+
* policies the checks below would otherwise report as blockers. After, to name
|
|
391
|
+
* whatever is still there.
|
|
392
|
+
*/
|
|
393
|
+
async function dropLegacyAuthSchema(run, report) {
|
|
394
|
+
let before;
|
|
395
|
+
try {
|
|
396
|
+
before = sqlRows(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));
|
|
397
|
+
} catch {
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (!before.some((o) => o.helper !== null)) return;
|
|
401
|
+
if (!before.some((o) => o.helper === "ours")) {
|
|
402
|
+
report.warn(describeLegacyAuthLeftovers(before, void 0));
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
let blockers;
|
|
406
|
+
try {
|
|
407
|
+
blockers = sqlRows(await run(LEGACY_RLS_DEPENDENTS_SQL));
|
|
408
|
+
} catch {
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (blockers.length > 0) {
|
|
412
|
+
report.warn(`The pre-1.0 \`${LEGACY_RLS_SCHEMA}\` schema cannot be removed yet: ${blockers.length} ${blockers.length === 1 ? "policy still calls" : "policies still call"} \`${LEGACY_RLS_SCHEMA}.uid()\` and friends, and Postgres will not drop a function a policy depends on. Rebase's own policies are rewritten automatically — anything listed here is hand-written SQL that has to be updated to \`${REBASE_SCHEMA}.uid()\` by hand, after which the schema goes on its own:\n` + blockers.map((b) => ` • ${b.schema}.${b.table} → "${b.policy}"`).join("\n"));
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
let borrowers;
|
|
416
|
+
try {
|
|
417
|
+
borrowers = sqlRows(await run(LEGACY_RLS_FUNCTION_DEPENDENTS_SQL));
|
|
418
|
+
} catch {
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
if (borrowers.length > 0) {
|
|
422
|
+
report.warn(`The pre-1.0 \`${LEGACY_RLS_SCHEMA}\` schema cannot be removed yet: ${borrowers.length} ${borrowers.length === 1 ? "function calls" : "functions call"} \`${LEGACY_RLS_SCHEMA}.uid()\` and friends from its own body. Postgres records no dependency for that — a SQL body written as a string literal is never parsed — so dropping the helpers would leave these pointing at nothing, and they would fail when a query reached them rather than now. Repoint them at \`${REBASE_SCHEMA}.uid()\`, after which the schema goes on its own:\n` + borrowers.map((b) => ` • ${b.schema}.${b.function}()`).join("\n"));
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
let failure;
|
|
426
|
+
try {
|
|
427
|
+
await run(DROP_LEGACY_AUTH_SCHEMA_SQL);
|
|
428
|
+
} catch (err) {
|
|
429
|
+
const detail = err instanceof Error && "detail" in err && typeof err.detail === "string" ? err.detail : "";
|
|
430
|
+
failure = (err instanceof Error ? err.message : String(err)) + (detail ? ` (${detail.replace(/\n/g, "; ")})` : "");
|
|
431
|
+
}
|
|
432
|
+
let left;
|
|
433
|
+
try {
|
|
434
|
+
left = sqlRows(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));
|
|
435
|
+
} catch {
|
|
436
|
+
if (failure) report.info(`Left the \`${LEGACY_RLS_SCHEMA}\` schema in place: ${failure}`);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (left.length === 0) return;
|
|
440
|
+
report.warn(describeLegacyAuthLeftovers(left, failure));
|
|
441
|
+
}
|
|
442
|
+
/** At most this many objects are named; a schema this full is plainly in use. */
|
|
443
|
+
var MAX_LEFTOVERS_NAMED = 20;
|
|
444
|
+
/**
|
|
445
|
+
* The warning for an `auth` schema the drop left standing.
|
|
446
|
+
*
|
|
447
|
+
* Said once for objects that are not Rebase's: on the next boot the schema holds
|
|
448
|
+
* no helper, so {@link dropLegacyAuthSchema} leaves it alone — it is somebody
|
|
449
|
+
* else's schema by then. A helper that is still there, Rebase's or a lookalike,
|
|
450
|
+
* keeps it said on every boot until it goes.
|
|
451
|
+
*/
|
|
452
|
+
function describeLegacyAuthLeftovers(left, failure) {
|
|
453
|
+
const schema = LEGACY_RLS_SCHEMA;
|
|
454
|
+
const objects = left.filter((o) => o.object !== null);
|
|
455
|
+
if (objects.length === 0) return `The pre-1.0 \`${schema}\` schema is empty, but this connection could not drop it — most likely because it does not own the schema. Run \`DROP SCHEMA ${schema};\` as its owner.`;
|
|
456
|
+
const why = failure ? `dropping Rebase's old helpers from it failed: ${failure}.` : "`DROP SCHEMA … RESTRICT` refuses a schema that is not empty, and Rebase drops only the helpers it can tell are its own.";
|
|
457
|
+
const lines = objects.slice(0, MAX_LEFTOVERS_NAMED).map((o) => o.helper === "ours" ? ` • ${o.object} — Rebase's old helper, which could not be dropped` : o.helper === "lookalike" ? ` • ${o.object} — named and typed like Rebase's old helper, but no release wrote this body, so it was left alone; drop it by hand if nothing of yours calls it` : ` • ${o.object}`);
|
|
458
|
+
if (objects.length > MAX_LEFTOVERS_NAMED) lines.push(` • …and ${objects.length - MAX_LEFTOVERS_NAMED} more`);
|
|
459
|
+
return `The pre-1.0 \`${schema}\` schema is still here: ${why} Still in it:\n` + lines.join("\n") + `
|
|
460
|
+
Anything of yours can stay where it is — Rebase no longer uses this schema — or move out with \`ALTER … SET SCHEMA\`. Once the schema is empty, \`DROP SCHEMA ${schema};\` removes it.`;
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* `rebase.is_request_role(role)` — is `role` one of the roles this database's
|
|
464
|
+
* requests run as? The predicate `rls.policyTarget: "requestRole"` ANDs into
|
|
465
|
+
* every permissive policy (`RLS_IS_REQUEST_ROLE_SQL`), called with
|
|
466
|
+
* `current_user`.
|
|
467
|
+
*
|
|
468
|
+
* SECURITY DEFINER because the recorded roles live in `rebase.schema_meta`,
|
|
469
|
+
* which the request roles cannot read. That is also why the caller's role is
|
|
470
|
+
* an argument: inside the function `current_user` is its owner. The body is
|
|
471
|
+
* dynamic SQL so the function can be created before the table exists — in
|
|
472
|
+
* Atlas's replay of the migrations, for one. With nothing recorded the answer
|
|
473
|
+
* is `rebase_user`, as everywhere else. Each recorded role's admin counterpart
|
|
474
|
+
* (`<role>_admin`, what an admin request switches to) answers `true` as well.
|
|
475
|
+
*
|
|
476
|
+
* Created only for a project that asks for `policyTarget: "requestRole"`, so
|
|
477
|
+
* every other project's migrations and boot are exactly what they were.
|
|
478
|
+
*/
|
|
479
|
+
var REQUEST_ROLE_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_request_role(role_name text) RETURNS boolean AS $$
|
|
480
|
+
DECLARE
|
|
481
|
+
request_roles text[];
|
|
482
|
+
BEGIN
|
|
483
|
+
IF to_regclass('"${REBASE_SCHEMA}"."schema_meta"') IS NOT NULL THEN
|
|
484
|
+
EXECUTE 'SELECT string_to_array(value, '','') FROM "${REBASE_SCHEMA}"."schema_meta" WHERE key = ''request_roles'''
|
|
485
|
+
INTO request_roles;
|
|
486
|
+
END IF;
|
|
487
|
+
request_roles := COALESCE(request_roles, ARRAY['rebase_user']);
|
|
488
|
+
-- An admin request runs as the request role's admin counterpart
|
|
489
|
+
-- (adminRequestRoleFor), which is a request role here too.
|
|
490
|
+
RETURN role_name = ANY(request_roles) OR role_name = ANY(ARRAY(SELECT r || '_admin' FROM unnest(request_roles) AS r));
|
|
491
|
+
END
|
|
492
|
+
$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog`;
|
|
493
|
+
/**
|
|
494
|
+
* Create {@link REQUEST_ROLE_FUNCTION_SQL} when it is missing or its body
|
|
495
|
+
* differs — replacing an unchanged function would still invalidate every
|
|
496
|
+
* cached plan of every policy that calls it.
|
|
497
|
+
*/
|
|
498
|
+
async function ensureRequestRoleFunction(run) {
|
|
499
|
+
const body = /AS \$\$([\s\S]*)\$\$ LANGUAGE/.exec(REQUEST_ROLE_FUNCTION_SQL)?.[1];
|
|
500
|
+
const [live] = await run(`SELECT p.prosrc AS body FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
501
|
+
WHERE n.nspname = '${REBASE_SCHEMA}' AND p.proname = 'is_request_role'`);
|
|
502
|
+
if (live && String(live.body) === body) return;
|
|
503
|
+
const [schema] = await run(`SELECT to_regnamespace('${REBASE_SCHEMA}') IS NOT NULL AS present`);
|
|
504
|
+
if (schema?.present !== true) await run(`CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`);
|
|
505
|
+
await run(REQUEST_ROLE_FUNCTION_SQL);
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* The statement that creates {@link REBASE_ADMIN_ROLE} when it is missing — a
|
|
509
|
+
* role with no privilege that cannot log in, whose only job is to be what the
|
|
510
|
+
* server-or-admin policies are written `TO`. Guarded in the statement, and a
|
|
511
|
+
* concurrent creator's win taken as success, because a role belongs to the
|
|
512
|
+
* cluster and two databases' boots can race for it.
|
|
513
|
+
*/
|
|
514
|
+
var ADMIN_POLICY_ROLE_SQL = `DO $rebase_admin_role$
|
|
515
|
+
BEGIN
|
|
516
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') THEN
|
|
517
|
+
CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;
|
|
518
|
+
END IF;
|
|
519
|
+
EXCEPTION
|
|
520
|
+
WHEN duplicate_object OR unique_violation THEN NULL;
|
|
521
|
+
WHEN insufficient_privilege THEN
|
|
522
|
+
RAISE EXCEPTION 'Rebase writes its server-or-admin policies TO ${REBASE_ADMIN_ROLE}, which does not exist, and % may not create it.', current_user
|
|
523
|
+
USING HINT = 'Run CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN; as an administrator, or declare database({ rls: { adminPolicies: "public" } }) (REBASE_RLS_ADMIN_POLICIES=public) to write them TO public.';
|
|
524
|
+
END
|
|
525
|
+
$rebase_admin_role$`;
|
|
526
|
+
/** Create {@link REBASE_ADMIN_ROLE} unless it exists — one read when it does. */
|
|
527
|
+
async function ensureAdminPolicyRole(run) {
|
|
528
|
+
const [row] = await run(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') AS present`);
|
|
529
|
+
if (row?.present !== true) await run(ADMIN_POLICY_ROLE_SQL);
|
|
530
|
+
}
|
|
531
|
+
//#endregion
|
|
532
|
+
export { dropLegacyAuthSchema as a, rls_bootstrap_sql_exports as c, RLS_BOOTSTRAP_STATEMENTS as i, REQUEST_ROLE_FUNCTION_SQL as n, ensureAdminPolicyRole as o, RLS_BOOTSTRAP_SQL as r, rlsRuntimeIsCurrent as s, ADMIN_POLICY_ROLE_SQL as t };
|
|
533
|
+
|
|
534
|
+
//# sourceMappingURL=rls-bootstrap-sql-CxszeSc7.js.map
|