@rebasepro/server-postgres 0.29.0 → 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-JiYJ_n9E.js → BranchService-X9R505mP.js} +3 -3
- package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-X9R505mP.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +90 -12
- package/dist/PostgresBootstrapper.d.ts +34 -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-D_aKXPyX.js → backup-cli-CwiJEp_J.js} +3 -3
- package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-CwiJEp_J.js.map} +1 -1
- package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-CbZj9ovZ.js} +2 -2
- package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-CbZj9ovZ.js.map} +1 -1
- package/dist/{cli-console-DPdZCWTi.js → cli-console-DDkNetCz.js} +6 -6
- package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DDkNetCz.js.map} +1 -1
- package/dist/{cli-errors-D8s4z_3g.js → cli-errors-C73Qy7WJ.js} +49 -6
- package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-C73Qy7WJ.js.map} +1 -1
- package/dist/cli.js +209 -53
- 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-DIauc8i5.js +184 -0
- 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/db-subcommands.d.ts +1 -1
- package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-DDdnjaOW.js} +25 -9
- package/dist/deferred-index-build-DDdnjaOW.js.map +1 -0
- package/dist/{doctor-_g2tHRtG.js → doctor-DwMXljiq.js} +11 -11
- package/dist/doctor-DwMXljiq.js.map +1 -0
- package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-DJsOMpaI.js} +23 -13
- package/dist/ensure-collection-policies-DJsOMpaI.js.map +1 -0
- package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-h1mUO7Uu.js} +18 -10
- package/dist/ensure-collection-tables-h1mUO7Uu.js.map +1 -0
- package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-CUqYgMvo.js} +4 -4
- package/dist/ensure-tables-CUqYgMvo.js.map +1 -0
- package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-z7ustOl_.js} +3 -3
- package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-z7ustOl_.js.map} +1 -1
- package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-BIUqhSzh.js} +2 -2
- package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-BIUqhSzh.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-BBXjxm5z.js} +3 -3
- package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-BBXjxm5z.js.map} +1 -1
- package/dist/{generate-files-DbwU8Btx.js → generate-files-BkiRFoV1.js} +3 -3
- package/dist/{generate-files-DbwU8Btx.js.map → generate-files-BkiRFoV1.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-G9PvjHrr.js} +10 -5
- package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-G9PvjHrr.js.map} +1 -1
- package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-D2soazQU.js} +18 -7
- 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.d.ts +2 -1
- package/dist/index.es.js +22 -14
- package/dist/index.es.js.map +1 -1
- 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-BeepEphh.js → migrate-baseline-CveNQli3.js} +166 -460
- package/dist/migrate-baseline-CveNQli3.js.map +1 -0
- package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-C4qbQ0jK.js} +42 -13
- package/dist/migrate-policy-stamps-C4qbQ0jK.js.map +1 -0
- package/dist/{open-rebase-CTNBmmH8.js → open-rebase-Cvid3iwR.js} +1813 -689
- package/dist/open-rebase-Cvid3iwR.js.map +1 -0
- package/dist/open-rebase.d.ts +7 -2
- package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-80uTIHQs.js} +2 -2
- package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-80uTIHQs.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +24 -37
- package/dist/{plan-schema-CMNWvqIa.js → plan-schema-CMhNYEYF.js} +109 -14
- package/dist/plan-schema-CMhNYEYF.js.map +1 -0
- package/dist/{policy-drift-IjD2AUD-.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-CIvajIrL.js → push-index-prebuild-xbpgZEJK.js} +4 -4
- package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-xbpgZEJK.js.map} +1 -1
- package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-D-JEv0Gn.js} +2 -2
- package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-D-JEv0Gn.js.map} +1 -1
- package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-7UKspspl.js} +4 -4
- package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-7UKspspl.js.map} +1 -1
- package/dist/{push-policy-plan--oRXOj4X.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-CzVcbbR1.js → render-ddl-Di-fTGti.js} +40 -10
- package/dist/render-ddl-Di-fTGti.js.map +1 -0
- package/dist/request-role-cli-Bxxskru9.js +260 -0
- package/dist/request-role-cli-Bxxskru9.js.map +1 -0
- package/dist/request-role-cli.d.ts +86 -0
- package/dist/request-role-migration-BCW4v0rq.js +150 -0
- package/dist/request-role-migration-BCW4v0rq.js.map +1 -0
- package/dist/rls-bootstrap-sql-CxszeSc7.js +534 -0
- package/dist/rls-bootstrap-sql-CxszeSc7.js.map +1 -0
- package/dist/rls-enforcement-CyUCPDH8.js +1195 -0
- package/dist/rls-enforcement-CyUCPDH8.js.map +1 -0
- package/dist/rls-settings-BCGMIig3.js +231 -0
- package/dist/rls-settings-BCGMIig3.js.map +1 -0
- package/dist/schema/doctor-cli.js +145 -7
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/doctor-database.d.ts +27 -0
- 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 +14 -2
- package/dist/schema/plan/render-ddl.d.ts +17 -3
- package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
- package/dist/schema/plan/types.d.ts +17 -0
- package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
- package/dist/schema/plan/view-names.d.ts +6 -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 +34 -0
- package/dist/schema/search-column.d.ts +2 -2
- package/dist/search-column-BM-GV6vH.js.map +1 -1
- package/dist/security/caller-sql-columns.d.ts +60 -0
- package/dist/security/caller-sql.d.ts +8 -0
- package/dist/security/database-preflight.d.ts +24 -0
- package/dist/security/policy-drift.d.ts +19 -1
- package/dist/security/request-role-migration.d.ts +36 -0
- package/dist/security/rls-enforcement.d.ts +277 -21
- package/dist/security/rls-settings.d.ts +210 -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 +8 -2
- package/dist/services/realtimeService.d.ts +21 -5
- package/dist/services/socket-liveness.d.ts +6 -1
- package/dist/services/view-access.d.ts +2 -2
- 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/view-names-Dscp6--B.js +24 -0
- package/dist/view-names-Dscp6--B.js.map +1 -0
- package/dist/{websocket-D2y88dOa.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/deferred-index-build-F2GWu009.js.map +0 -1
- package/dist/doctor-_g2tHRtG.js.map +0 -1
- package/dist/ensure-collection-policies-DUpWJb5D.js.map +0 -1
- package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
- package/dist/ensure-tables-Bx1DYarz.js.map +0 -1
- package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
- package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
- package/dist/migrate-baseline-BeepEphh.js.map +0 -1
- package/dist/migrate-policy-stamps-cYMJ_9Ha.js.map +0 -1
- package/dist/open-rebase-CTNBmmH8.js.map +0 -1
- package/dist/plan-schema-CMNWvqIa.js.map +0 -1
- package/dist/policy-drift-IjD2AUD-.js.map +0 -1
- package/dist/push-policy-plan--oRXOj4X.js.map +0 -1
- package/dist/render-ddl-CzVcbbR1.js.map +0 -1
- package/dist/rls-enforcement-jZTv1yci.js +0 -534
- package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
- package/dist/websocket-D2y88dOa.js.map +0 -1
|
@@ -0,0 +1,1195 @@
|
|
|
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 { n as VIEW_ROWS_COMMENT_PREFIX } from "./view-names-Dscp6--B.js";
|
|
5
|
+
import { ot as extractCauseMessage } from "./cli-errors-C73Qy7WJ.js";
|
|
6
|
+
import { t as cliRlsSettings } from "./rls-settings-BCGMIig3.js";
|
|
7
|
+
import { t as ADMIN_POLICY_ROLE_SQL } from "./rls-bootstrap-sql-CxszeSc7.js";
|
|
8
|
+
import { logger } from "@rebasepro/server";
|
|
9
|
+
import { sql } from "drizzle-orm";
|
|
10
|
+
import { ANONYMOUS_USER_ID, REBASE_ADMIN_ROLE, REBASE_SCHEMA, holdsAdminRole, usesLegacyRlsFunctions } from "@rebasepro/types";
|
|
11
|
+
import { AUTH_USERS_TABLE, LOAD_REQUEST_ROLES_PLPGSQL, REBASE_INTERNAL_TABLES, REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, revokeInternalTableSql, securityRuleToConditions } from "@rebasepro/common";
|
|
12
|
+
//#region src/security/rls-enforcement.ts
|
|
13
|
+
var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
|
|
14
|
+
AppRoleSetupError: () => AppRoleSetupError,
|
|
15
|
+
REBASE_USER_ROLE: () => REBASE_USER_ROLE$1,
|
|
16
|
+
REQUEST_ROLES_KEY: () => REQUEST_ROLES_KEY,
|
|
17
|
+
adminPoliciesLiveForCli: () => adminPoliciesLiveForCli,
|
|
18
|
+
adminSwitchLive: () => adminSwitchLive,
|
|
19
|
+
appRoleSetupInstructions: () => appRoleSetupInstructions,
|
|
20
|
+
applyAuthContext: () => applyAuthContext,
|
|
21
|
+
assertAppRoleRestricted: () => assertAppRoleRestricted,
|
|
22
|
+
assertRecordedRequestRoles: () => assertRecordedRequestRoles,
|
|
23
|
+
authContextStatement: () => authContextStatement,
|
|
24
|
+
detectConnectionPosture: () => detectConnectionPosture,
|
|
25
|
+
ensureAdminRequestRole: () => ensureAdminRequestRole,
|
|
26
|
+
ensureAppRole: () => ensureAppRole,
|
|
27
|
+
ensureAppRoleGrants: () => ensureAppRoleGrants,
|
|
28
|
+
ensureConnectionInheritsAdminRole: () => ensureConnectionInheritsAdminRole,
|
|
29
|
+
ensureInheritedRoles: () => ensureInheritedRoles,
|
|
30
|
+
findExposedInternalTables: () => findExposedInternalTables,
|
|
31
|
+
findOtherRoleMembers: () => findOtherRoleMembers,
|
|
32
|
+
findUngrantableTables: () => findUngrantableTables,
|
|
33
|
+
internalTablesGrantedToUserRole: () => internalTablesGrantedToUserRole,
|
|
34
|
+
proveRoleSwitch: () => proveRoleSwitch,
|
|
35
|
+
readRecordedRequestRoles: () => readRecordedRequestRoles,
|
|
36
|
+
recordRequestRoles: () => recordRequestRoles,
|
|
37
|
+
revokeUserRoleSql: () => revokeUserRoleSql,
|
|
38
|
+
roleHoldsTableGrants: () => roleHoldsTableGrants,
|
|
39
|
+
settleAdminRequestRoles: () => settleAdminRequestRoles,
|
|
40
|
+
settleAdminSwitch: () => settleAdminSwitch,
|
|
41
|
+
validatePolicyPgRoles: () => validatePolicyPgRoles,
|
|
42
|
+
warnOnAnonymousGrants: () => warnOnAnonymousGrants,
|
|
43
|
+
warnOnLegacyRlsFunctions: () => warnOnLegacyRlsFunctions,
|
|
44
|
+
warnOnRoleSchemaCollision: () => warnOnRoleSchemaCollision
|
|
45
|
+
});
|
|
46
|
+
var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
47
|
+
/** A string literal for a catalogue read. Names come from config and constants, never from a request. */
|
|
48
|
+
var sqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
49
|
+
var textArray = (values) => values.length === 0 ? "ARRAY[]::text[]" : `ARRAY[${values.map(sqlLiteral).join(", ")}]::text[]`;
|
|
50
|
+
/** A `text[]` column as read back — an array, or `{a,b}` from a driver that hands arrays back as text. */
|
|
51
|
+
var textArrayValue = (value) => Array.isArray(value) ? value.map(String) : String(value ?? "").replace(/^\{|\}$/g, "").split(",").filter(Boolean);
|
|
52
|
+
/** DML the user role holds on managed tables (RLS still filters per row). */
|
|
53
|
+
var USER_TABLE_PRIVILEGES = "SELECT, INSERT, UPDATE, DELETE";
|
|
54
|
+
/**
|
|
55
|
+
* Take every privilege the request roles hold on one table back — what a
|
|
56
|
+
* table gets when RLS cannot be switched on for it, so it is unreachable
|
|
57
|
+
* rather than unprotected. Quoted exactly: a mixed-case adopted table
|
|
58
|
+
* (`"User"`) folded to lower case names a table that does not exist.
|
|
59
|
+
*
|
|
60
|
+
* Every request role, as this database recorded them (`rls.requestRole`), and
|
|
61
|
+
* each only if it exists: one statement, for the boot's policies step and its
|
|
62
|
+
* final posture check alike, without either being handed the roles.
|
|
63
|
+
*/
|
|
64
|
+
var revokeUserRoleSql = (schema, table) => `
|
|
65
|
+
DO $rebase_withhold$
|
|
66
|
+
DECLARE
|
|
67
|
+
request_roles text[];
|
|
68
|
+
request_role text;
|
|
69
|
+
BEGIN
|
|
70
|
+
${LOAD_REQUEST_ROLES_PLPGSQL}
|
|
71
|
+
FOREACH request_role IN ARRAY request_roles LOOP
|
|
72
|
+
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = request_role) THEN
|
|
73
|
+
EXECUTE format('REVOKE ALL PRIVILEGES ON %I.%I FROM %I', ${sqlLiteral(schema)}, ${sqlLiteral(table)}, request_role);
|
|
74
|
+
END IF;
|
|
75
|
+
END LOOP;
|
|
76
|
+
END
|
|
77
|
+
$rebase_withhold$
|
|
78
|
+
`.trim();
|
|
79
|
+
/**
|
|
80
|
+
* Warn when the connection role shares its name with an existing schema.
|
|
81
|
+
*
|
|
82
|
+
* Postgres resolves unqualified names through `search_path`, which defaults to
|
|
83
|
+
* `"$user", public` — and `$user` is the connection ROLE. When a schema of that
|
|
84
|
+
* name exists it sits ahead of `public`, so every unqualified statement
|
|
85
|
+
* silently operates on it instead:
|
|
86
|
+
*
|
|
87
|
+
* CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts
|
|
88
|
+
*
|
|
89
|
+
* Nothing errors. You get a second table of the same name in the wrong schema,
|
|
90
|
+
* and reads that pin `public` cannot see it — which reads as "missing table" and
|
|
91
|
+
* sends people to re-run a push that creates a *third* copy. The bootstrapper
|
|
92
|
+
* has a whole branch dedicated to recognising the symptom after the fact.
|
|
93
|
+
*
|
|
94
|
+
* Rebase shipped straight into this: it creates a schema named `rebase` while
|
|
95
|
+
* every template named the database role `rebase` too. The scaffold uses
|
|
96
|
+
* `rebase_app` now, and every pool Rebase opens pins `search_path=public`
|
|
97
|
+
* (`pinSearchPath`), which covers the paths the framework controls. This covers
|
|
98
|
+
* the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,
|
|
99
|
+
* a hand-written migration — because the hazard is a property of the two NAMES,
|
|
100
|
+
* not of any one connection.
|
|
101
|
+
*
|
|
102
|
+
* A warning rather than a boot failure: the database works, the framework's own
|
|
103
|
+
* traffic is pinned, and refusing to start over a naming choice a user may have
|
|
104
|
+
* inherited would be worse than the risk.
|
|
105
|
+
*/
|
|
106
|
+
async function warnOnRoleSchemaCollision(run) {
|
|
107
|
+
try {
|
|
108
|
+
const rows = await run(`
|
|
109
|
+
SELECT current_user AS role,
|
|
110
|
+
EXISTS (
|
|
111
|
+
SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user
|
|
112
|
+
) AS collides
|
|
113
|
+
`);
|
|
114
|
+
if (rows[0]?.collides !== true) return;
|
|
115
|
+
const role = String(rows[0]?.role ?? "the connection role");
|
|
116
|
+
logger.warn(`⚠️ The database role "${role}" has the same name as a schema. Postgres resolves unqualified names through \`search_path\`, which defaults to \`"$user", public\` — so "${role}" is searched BEFORE public, and any unqualified \`CREATE TABLE\`/\`SELECT\` from a tool that does not pin the path (psql, pg_dump, drizzle-kit, a hand-written migration) silently lands in "${role}" instead. Rebase's own connections pin \`search_path=public\`, so the server is unaffected. To remove the hazard entirely, connect as a role whose name is not also a schema — the scaffold uses "rebase_app".`);
|
|
117
|
+
} catch {}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Would RLS actually constrain this connection?
|
|
121
|
+
*
|
|
122
|
+
* Four ways the answer is no, and only two of them are obvious. Superuser and
|
|
123
|
+
* BYPASSRLS announce themselves in `pg_roles`. The other two are about
|
|
124
|
+
* ownership, and both used to read as "no bypass here":
|
|
125
|
+
*
|
|
126
|
+
* - **Ownership through membership.** The old query compared
|
|
127
|
+
* `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a
|
|
128
|
+
* role that INHERITs the owner passes every ownership test the planner makes,
|
|
129
|
+
* including the one that decides whether a policy applies. So a perfectly
|
|
130
|
+
* ordinary "app role that is a member of the owner role" setup reported
|
|
131
|
+
* unprivileged and bypassed every policy — permanently, since no restart
|
|
132
|
+
* changes a string comparison's answer.
|
|
133
|
+
*
|
|
134
|
+
* - **Ownership that has not happened yet.** The posture is decided once, at
|
|
135
|
+
* boot, and on a fresh database there is nothing in the catalogue to find. The
|
|
136
|
+
* same process then creates every table and owns all of them. The first boot
|
|
137
|
+
* of a new deployment therefore served every request unconstrained, the log
|
|
138
|
+
* said RLS was fine, and the SECOND boot silently fixed it — which is the
|
|
139
|
+
* worst possible shape for a security check, because the state that reproduces
|
|
140
|
+
* it is gone by the time anyone looks. Asking "may this role create tables
|
|
141
|
+
* where the server provisions?" answers about the process's whole life rather
|
|
142
|
+
* than about one instant of it.
|
|
143
|
+
*
|
|
144
|
+
* `schemas` narrows the CREATE question to where the server actually writes.
|
|
145
|
+
* Omitted, it asks about every schema the role can see, which is the safe
|
|
146
|
+
* direction: over-reporting costs a role switch that was not strictly needed,
|
|
147
|
+
* under-reporting costs the entire authorization model.
|
|
148
|
+
*/
|
|
149
|
+
async function detectConnectionPosture(run, schemas) {
|
|
150
|
+
const row = (await run(`
|
|
151
|
+
SELECT current_user AS role,
|
|
152
|
+
r.rolsuper AS superuser,
|
|
153
|
+
r.rolbypassrls AS bypassrls,
|
|
154
|
+
EXISTS (
|
|
155
|
+
SELECT 1 FROM pg_tables t
|
|
156
|
+
WHERE pg_has_role(current_user, t.tableowner, 'USAGE')
|
|
157
|
+
AND t.schemaname NOT IN ('pg_catalog', 'information_schema')
|
|
158
|
+
) AS owns_tables,
|
|
159
|
+
EXISTS (
|
|
160
|
+
SELECT 1 FROM pg_namespace n
|
|
161
|
+
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
162
|
+
AND n.nspname NOT LIKE 'pg\\_toast%'
|
|
163
|
+
AND n.nspname NOT LIKE 'pg\\_temp%'
|
|
164
|
+
${schemas?.length ? `AND n.nspname IN (${Array.from(new Set(schemas)).map((s) => `'${s.replace(/'/g, "''")}'`).join(", ")})` : ""}
|
|
165
|
+
AND has_schema_privilege(current_user, n.oid, 'CREATE')
|
|
166
|
+
) AS can_create
|
|
167
|
+
FROM pg_roles r
|
|
168
|
+
WHERE r.rolname = current_user
|
|
169
|
+
`))[0] ?? {};
|
|
170
|
+
const superuser = row.superuser === true;
|
|
171
|
+
const bypassRLS = row.bypassrls === true;
|
|
172
|
+
const ownsTables = row.owns_tables === true;
|
|
173
|
+
const canCreateTables = row.can_create === true;
|
|
174
|
+
return {
|
|
175
|
+
role: String(row.role ?? "unknown"),
|
|
176
|
+
superuser,
|
|
177
|
+
bypassRLS,
|
|
178
|
+
ownsTables,
|
|
179
|
+
canCreateTables,
|
|
180
|
+
privileged: superuser || bypassRLS || ownsTables || canCreateTables
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* The Postgres major from which a role membership carries a separate SET
|
|
185
|
+
* option, as `server_version_num` spells it.
|
|
186
|
+
*
|
|
187
|
+
* From 16, `pg_has_role(…, 'MEMBER')` no longer answers "may this connection
|
|
188
|
+
* `SET ROLE` to it": a membership can be held with `SET FALSE`. That is exactly
|
|
189
|
+
* what a non-superuser with CREATEROLE gets for a role it creates — Postgres
|
|
190
|
+
* records the creator as a member `WITH ADMIN TRUE, SET FALSE, INHERIT FALSE`
|
|
191
|
+
* (unless `createrole_self_grant` says otherwise). RDS's master user, Cloud
|
|
192
|
+
* SQL's `postgres`, Neon's owner and most managed "admin" users are that kind
|
|
193
|
+
* of role. Asking MEMBER said yes, the grant was skipped, boot logged RLS as
|
|
194
|
+
* active, and every signed-in request then failed with 42501 "permission
|
|
195
|
+
* denied to set role". A plain `GRANT` on top changes nothing — Postgres reports
|
|
196
|
+
* the membership as already granted — so the grant has to name the option.
|
|
197
|
+
*/
|
|
198
|
+
var SET_OPTION_SINCE = 16e4;
|
|
199
|
+
/**
|
|
200
|
+
* Raised when `rebase_user` cannot be provisioned, adopted or switched to —
|
|
201
|
+
* with the SQL that fixes it in {@link instructions}.
|
|
202
|
+
*
|
|
203
|
+
* Its own class so a caller that prints the instructions itself (the CLI) can
|
|
204
|
+
* tell they are already in the message.
|
|
205
|
+
*/
|
|
206
|
+
var AppRoleSetupError = class extends Error {
|
|
207
|
+
instructions;
|
|
208
|
+
constructor(problem, instructions) {
|
|
209
|
+
super(`${problem}\n\n${instructions}`);
|
|
210
|
+
this.name = "AppRoleSetupError";
|
|
211
|
+
this.instructions = instructions;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
/**
|
|
215
|
+
* What a failed statement said, without the statement.
|
|
216
|
+
*
|
|
217
|
+
* A Drizzle runner throws `Failed query: <sql>\nparams: <values>` and keeps
|
|
218
|
+
* Postgres's own sentence in `.cause`. The logger redacts from that marker to
|
|
219
|
+
* the next stack frame — the params have no terminator — so any text appended
|
|
220
|
+
* after a Drizzle message is redacted with it. That is how the setup SQL below
|
|
221
|
+
* used to vanish from a production log. Postgres's messages carry no statement
|
|
222
|
+
* and no row values, and they are the part that says what is wrong.
|
|
223
|
+
*/
|
|
224
|
+
function failureReason(err) {
|
|
225
|
+
return extractCauseMessage(err) ?? (err instanceof Error ? err.message : String(err));
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The statement that lets `connectionRole` switch to the user role, as one
|
|
229
|
+
* statement that works on any Postgres the driver supports.
|
|
230
|
+
*
|
|
231
|
+
* Version-adaptive rather than two alternatives for the reader to choose
|
|
232
|
+
* between: `WITH SET TRUE` is a syntax error before 16, and a plain `GRANT`
|
|
233
|
+
* from 16 on is a no-op on a membership that exists without SET.
|
|
234
|
+
* `INHERIT FALSE` keeps the connection from picking up the user role's
|
|
235
|
+
* privileges as its own; the switch is all it needs.
|
|
236
|
+
*/
|
|
237
|
+
function membershipGrantSql(connectionRole, role = REBASE_USER_ROLE$1) {
|
|
238
|
+
const member = sqlLiteral(connectionRole);
|
|
239
|
+
const target = sqlLiteral(role);
|
|
240
|
+
return `DO \$rebase_grant\$
|
|
241
|
+
BEGIN
|
|
242
|
+
IF current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} THEN\n EXECUTE format('GRANT %I TO %I WITH SET TRUE, INHERIT FALSE', ${target}, ${member});\n ELSE\n EXECUTE format('GRANT %I TO %I', ${target}, ${member});\n END IF;\nEND\n$rebase_grant$;`;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Human-actionable instructions for when the connection cannot provision the
|
|
246
|
+
* user role itself (no CREATEROLE and role not pre-created by the platform),
|
|
247
|
+
* or holds it without the right to switch to it.
|
|
248
|
+
*
|
|
249
|
+
* Every statement is safe to re-run and the same text works on Postgres 15 and
|
|
250
|
+
* 16+, so it can be pasted whole whatever state the database is in.
|
|
251
|
+
* `connectionRole` is the role the server connects as; without one, a
|
|
252
|
+
* placeholder Postgres will refuse until it is replaced.
|
|
253
|
+
*/
|
|
254
|
+
function appRoleSetupInstructions(connectionRole, schemas, role = REBASE_USER_ROLE$1, mode = "schema") {
|
|
255
|
+
const member = connectionRole ?? "<your database user>";
|
|
256
|
+
const grants = mode !== "schema" ? "" : schemas.map((s) => `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${role};\nGRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${role};\nGRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${role};`).join("\n");
|
|
257
|
+
return `Rebase enforces row-level security by running authenticated requests as the restricted role "${role}", but the connection role "${member}" bypasses RLS and cannot set that role up itself.\nRun the following as a database administrator (a superuser, or the role that created "${role}"), then restart:\n\nDO $rebase_role$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${sqlLiteral(role)}) THEN\n CREATE ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\n END IF;\nEND\n$rebase_role$;\n${membershipGrantSql(member, role)}\n` + grants;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Refuse a `rebase_user` that would not restrict anything.
|
|
261
|
+
*
|
|
262
|
+
* The role is cluster-wide and found by name, so the one a boot adopts may
|
|
263
|
+
* have been made by anybody — an earlier tool, a hand-written script, another
|
|
264
|
+
* application on the same cluster. Every authenticated request runs as it, so
|
|
265
|
+
* an attribute or a membership that lifts RLS lifts it from all of them, and
|
|
266
|
+
* nothing would say so: requests succeed, with every row.
|
|
267
|
+
*
|
|
268
|
+
* - LOGIN: anyone holding its password connects as the request role directly.
|
|
269
|
+
* - SUPERUSER, BYPASSRLS: RLS does not apply to it at all.
|
|
270
|
+
* - A membership in a role that owns tables here, or is itself a login,
|
|
271
|
+
* superuser or BYPASSRLS role: a member inheriting an owner is the owner for
|
|
272
|
+
* every policy check, and one that may `SET ROLE` to a privileged role is a
|
|
273
|
+
* statement away from it. (`GRANT app TO rebase_user` for `GRANT rebase_user
|
|
274
|
+
* TO app` is the easy way to get here.)
|
|
275
|
+
*
|
|
276
|
+
* A plain NOLOGIN group role is left alone: `validatePolicyPgRoles` sends a
|
|
277
|
+
* project with `pgRoles` to exactly that grant.
|
|
278
|
+
*/
|
|
279
|
+
async function assertAppRoleRestricted(run, role = REBASE_USER_ROLE$1) {
|
|
280
|
+
const row = (await run(`
|
|
281
|
+
SELECT r.rolcanlogin AS can_login,
|
|
282
|
+
r.rolsuper AS superuser,
|
|
283
|
+
r.rolbypassrls AS bypassrls,
|
|
284
|
+
ARRAY(
|
|
285
|
+
SELECT g.rolname::text FROM pg_roles g
|
|
286
|
+
WHERE g.oid <> r.oid
|
|
287
|
+
AND pg_has_role(r.oid, g.oid, 'MEMBER')
|
|
288
|
+
AND (g.rolsuper OR g.rolbypassrls OR g.rolcanlogin
|
|
289
|
+
OR EXISTS (SELECT 1 FROM pg_class c
|
|
290
|
+
WHERE c.relowner = g.oid AND c.relkind IN ('r', 'p', 'v', 'm', 'f')))
|
|
291
|
+
ORDER BY 1
|
|
292
|
+
) AS privileged_memberships
|
|
293
|
+
FROM pg_roles r
|
|
294
|
+
WHERE r.rolname = ${sqlLiteral(role)}
|
|
295
|
+
`))[0];
|
|
296
|
+
if (!row) return;
|
|
297
|
+
const memberships = textArrayValue(row.privileged_memberships);
|
|
298
|
+
const problems = [];
|
|
299
|
+
const fixes = [];
|
|
300
|
+
const attributes = [];
|
|
301
|
+
if (row.can_login === true) {
|
|
302
|
+
problems.push("it can log in (LOGIN)");
|
|
303
|
+
attributes.push("NOLOGIN");
|
|
304
|
+
}
|
|
305
|
+
if (row.superuser === true) {
|
|
306
|
+
problems.push("it is a superuser, so RLS does not apply to it");
|
|
307
|
+
attributes.push("NOSUPERUSER");
|
|
308
|
+
}
|
|
309
|
+
if (row.bypassrls === true) {
|
|
310
|
+
problems.push("it has BYPASSRLS, so RLS does not apply to it");
|
|
311
|
+
attributes.push("NOBYPASSRLS");
|
|
312
|
+
}
|
|
313
|
+
if (attributes.length > 0) fixes.push(`ALTER ROLE ${role} ${attributes.join(" ")};`);
|
|
314
|
+
if (memberships.length > 0) {
|
|
315
|
+
problems.push(`it is a member of ${memberships.map((m) => `"${m}"`).join(", ")} — a role that owns tables or logs in, or is a superuser or BYPASSRLS — so requests can act as that role`);
|
|
316
|
+
for (const m of memberships) fixes.push(`REVOKE ${quoteIdent(m)} FROM ${role};`);
|
|
317
|
+
}
|
|
318
|
+
if (problems.length === 0) return;
|
|
319
|
+
throw new AppRoleSetupError(`Refusing to use the existing "${role}" role: every authenticated request runs as it, and ${problems.join("; ")}. Row-level security would not restrict those requests.`, `Run the following as a database administrator, then restart. If another application on this cluster relies on "${role}" being this way, the two cannot share it.\n\n` + fixes.join("\n"));
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Prove the connection can switch to the user role, the way every request
|
|
323
|
+
* will, and leave nothing behind.
|
|
324
|
+
*
|
|
325
|
+
* Catalogue answers are only a model of what Postgres will allow. This is the
|
|
326
|
+
* switch itself — `set_config('role', …, true)` is what `applyAuthContext`
|
|
327
|
+
* sends — followed, in the same statement, by switching back to the role the
|
|
328
|
+
* session had, so nothing outlives the probe even when the runner is inside a
|
|
329
|
+
* transaction of its own. A refusal escapes as Postgres's own 42501.
|
|
330
|
+
*
|
|
331
|
+
* Each step is its own subquery level, so the order is the plan's, not the
|
|
332
|
+
* order of a target list: the innermost reads the role the session has, the
|
|
333
|
+
* middle switches, the outer switches back. `OFFSET 0` keeps the levels from
|
|
334
|
+
* being flattened, and a volatile column is never pruned as unused.
|
|
335
|
+
*
|
|
336
|
+
* A `SELECT`, not a `DO` block with a rolled-back subtransaction: the
|
|
337
|
+
* provisioning recorder and the provisioning-off guard both read a leading
|
|
338
|
+
* `DO` as a schema change, and this changes nothing.
|
|
339
|
+
*/
|
|
340
|
+
var roleSwitchProbe = (role) => `
|
|
341
|
+
SELECT set_config('role', switched.previous, true) AS restored
|
|
342
|
+
FROM (
|
|
343
|
+
SELECT session.previous, set_config('role', ${sqlLiteral(role)}, true) AS probe
|
|
344
|
+
FROM (SELECT current_setting('role') AS previous OFFSET 0) session
|
|
345
|
+
OFFSET 0
|
|
346
|
+
) switched
|
|
347
|
+
`;
|
|
348
|
+
/**
|
|
349
|
+
* Run {@link roleSwitchProbe}, and on a refusal throw an
|
|
350
|
+
* {@link AppRoleSetupError} carrying the SQL that grants the switch.
|
|
351
|
+
*
|
|
352
|
+
* For a boot that adopts the role without provisioning it as much as for one
|
|
353
|
+
* that just did: either way the next thing that happens is a request running
|
|
354
|
+
* as it.
|
|
355
|
+
*/
|
|
356
|
+
async function proveRoleSwitch(run, schemas, connectionRole, role = REBASE_USER_ROLE$1) {
|
|
357
|
+
try {
|
|
358
|
+
await run(roleSwitchProbe(role));
|
|
359
|
+
} catch (err) {
|
|
360
|
+
const member = connectionRole ?? String((await run("SELECT current_user AS role").catch(() => []))[0]?.role ?? "");
|
|
361
|
+
throw new AppRoleSetupError(`The connection role "${member}" cannot switch to "${role}", so every authenticated request would fail: ${failureReason(err)}`, appRoleSetupInstructions(member || void 0, Array.from(new Set(schemas.filter(Boolean))), role));
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/** The `rebase.schema_meta` key that records which roles requests run as. */
|
|
365
|
+
var REQUEST_ROLES_KEY = "request_roles";
|
|
366
|
+
/**
|
|
367
|
+
* The request roles this database recorded on an earlier provisioning boot, or
|
|
368
|
+
* `undefined` when none has — every database provisioned before the setting
|
|
369
|
+
* existed, which ran as `rebase_user`.
|
|
370
|
+
*
|
|
371
|
+
* Recorded in the database rather than only configured because a role belongs
|
|
372
|
+
* to the cluster and holds grants here: a later boot configured with another
|
|
373
|
+
* name would provision a second role and leave the first one holding every
|
|
374
|
+
* grant. Reading the record is how that boot notices.
|
|
375
|
+
*/
|
|
376
|
+
async function readRecordedRequestRoles(run) {
|
|
377
|
+
const [present] = await run(`SELECT to_regclass('"${REBASE_SCHEMA}"."schema_meta"') IS NOT NULL AS present`);
|
|
378
|
+
if (present?.present !== true) return void 0;
|
|
379
|
+
const [row] = await run(`SELECT value FROM "${REBASE_SCHEMA}"."schema_meta" WHERE key = ${sqlLiteral(REQUEST_ROLES_KEY)}`);
|
|
380
|
+
const value = row?.value === void 0 ? "" : String(row.value).trim();
|
|
381
|
+
return value === "" ? void 0 : value.split(",").map((r) => r.trim()).filter(Boolean);
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Record `roles` as this database's request roles, creating `rebase.schema_meta`
|
|
385
|
+
* if nothing has yet. The table is one of Rebase's internal tables, so it is
|
|
386
|
+
* taken back from the request roles here, as its every creator does.
|
|
387
|
+
*/
|
|
388
|
+
async function recordRequestRoles(run, roles) {
|
|
389
|
+
const [schema] = await run(`SELECT to_regnamespace('${REBASE_SCHEMA}') IS NOT NULL AS present`);
|
|
390
|
+
if (schema?.present !== true) await run(`CREATE SCHEMA IF NOT EXISTS "${REBASE_SCHEMA}"`);
|
|
391
|
+
await run(`
|
|
392
|
+
CREATE TABLE IF NOT EXISTS "${REBASE_SCHEMA}"."schema_meta" (
|
|
393
|
+
key TEXT PRIMARY KEY,
|
|
394
|
+
value TEXT NOT NULL,
|
|
395
|
+
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL
|
|
396
|
+
)
|
|
397
|
+
`);
|
|
398
|
+
await run(`
|
|
399
|
+
INSERT INTO "${REBASE_SCHEMA}"."schema_meta" (key, value)
|
|
400
|
+
VALUES (${sqlLiteral(REQUEST_ROLES_KEY)}, ${sqlLiteral(roles.join(","))})
|
|
401
|
+
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
|
|
402
|
+
WHERE "schema_meta".value IS DISTINCT FROM EXCLUDED.value
|
|
403
|
+
`);
|
|
404
|
+
await run(revokeInternalTableSql(REBASE_SCHEMA, "schema_meta"));
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Refuse a boot configured with request roles other than the ones this
|
|
408
|
+
* database recorded. The same set in any order is the same.
|
|
409
|
+
*
|
|
410
|
+
* Nothing recorded means `rebase_user`, as every database from before the
|
|
411
|
+
* setting ran — but only where `rebase_user` actually holds grants here. A
|
|
412
|
+
* database it has never been granted on (a fresh one) has nothing to strand,
|
|
413
|
+
* and a new role is simply recorded.
|
|
414
|
+
*/
|
|
415
|
+
function assertRecordedRequestRoles(configured, recorded, defaultRoleHoldsGrants) {
|
|
416
|
+
if (!recorded && !defaultRoleHoldsGrants) return;
|
|
417
|
+
const effective = recorded ?? [REBASE_USER_ROLE$1];
|
|
418
|
+
if (configured.length === effective.length && configured.every((r) => effective.includes(r))) return;
|
|
419
|
+
throw new AppRoleSetupError(`This database's requests run as ${effective.map((r) => `"${r}"`).join(", ")}${recorded ? "" : " (the default, which holds grants here)"}, but this server is configured for ${configured.map((r) => `"${r}"`).join(", ")} (rls.requestRole / REBASE_RLS_REQUEST_ROLE). Booting would provision new roles and leave the old ones holding every grant.`, `Move this database to the new role(s) — it re-creates each grant in this database only and records them:
|
|
420
|
+
|
|
421
|
+
rebase db request-role migrate --to ${configured.join(",")}\n\nOr set the setting back to ${effective.join(",")}.`);
|
|
422
|
+
}
|
|
423
|
+
/** Whether `role` holds any table privilege in `schemas` — something a new role would strand. */
|
|
424
|
+
async function roleHoldsTableGrants(run, schemas, role = REBASE_USER_ROLE$1) {
|
|
425
|
+
const [row] = await run(`
|
|
426
|
+
SELECT to_regrole(${sqlLiteral(role)}) IS NOT NULL AND EXISTS (
|
|
427
|
+
SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
428
|
+
WHERE n.nspname = ANY(${textArray(schemas)}) AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
|
|
429
|
+
AND EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = to_regrole(${sqlLiteral(role)}))
|
|
430
|
+
) AS holds
|
|
431
|
+
`);
|
|
432
|
+
return row?.holds === true;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Login roles other than this connection that can switch into `role`, and so
|
|
436
|
+
* can pass this database's policies as whichever user they like: the settings the
|
|
437
|
+
* policies read can be set by any session.
|
|
438
|
+
*
|
|
439
|
+
* Roles belong to the cluster, so this is how two projects on one cluster
|
|
440
|
+
* sharing `rebase_user` shows up from inside either database. Superusers are
|
|
441
|
+
* left out — they can become any role, and nothing here changes that.
|
|
442
|
+
*/
|
|
443
|
+
async function findOtherRoleMembers(run, role) {
|
|
444
|
+
return (await run(`
|
|
445
|
+
SELECT r.rolname AS name
|
|
446
|
+
FROM pg_roles r
|
|
447
|
+
WHERE r.rolcanlogin AND NOT r.rolsuper AND r.rolname <> current_user
|
|
448
|
+
AND to_regrole(${sqlLiteral(role)}) IS NOT NULL
|
|
449
|
+
AND pg_has_role(r.oid, to_regrole(${sqlLiteral(role)}),
|
|
450
|
+
CASE WHEN current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} THEN 'SET' ELSE 'MEMBER' END)
|
|
451
|
+
ORDER BY 1
|
|
452
|
+
`)).map((row) => String(row.name));
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Idempotently provision the `rebase_user` role, membership for the current
|
|
456
|
+
* connection role, and DML grants (+ default privileges for future tables)
|
|
457
|
+
* on every existing schema in `schemas`.
|
|
458
|
+
*
|
|
459
|
+
* Split into privilege tiers so it works both when the connection is a
|
|
460
|
+
* superuser (creates everything) and when the platform pre-created the role
|
|
461
|
+
* and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is
|
|
462
|
+
* merely the table owner — owners can always run the grant tier themselves.
|
|
463
|
+
*
|
|
464
|
+
* RLS still filters every row: these grants only make the tables *reachable*
|
|
465
|
+
* by the role; the policies decide which rows/commands actually pass.
|
|
466
|
+
*
|
|
467
|
+
* Throws {@link AppRoleSetupError}, with precise setup instructions, when the
|
|
468
|
+
* role is missing and the connection cannot create it, when an existing role
|
|
469
|
+
* would not restrict anything, and when the connection cannot switch to it.
|
|
470
|
+
* Boot fails then, rather than serving an API whose every signed-in request is
|
|
471
|
+
* refused — or, worse, allowed.
|
|
472
|
+
*/
|
|
473
|
+
async function ensureAppRole(run, schemas, options = {}) {
|
|
474
|
+
const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
|
|
475
|
+
const role = options.role ?? REBASE_USER_ROLE$1;
|
|
476
|
+
const provision = options.provisionRole !== "never";
|
|
477
|
+
const [who] = await run(`
|
|
478
|
+
SELECT current_user AS role,
|
|
479
|
+
(SELECT rolsuper FROM pg_roles WHERE rolname = current_user) AS superuser,
|
|
480
|
+
current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS set_option,
|
|
481
|
+
EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${sqlLiteral(role)}) AS role_exists
|
|
482
|
+
`);
|
|
483
|
+
const connectionRole = String(who?.role ?? "");
|
|
484
|
+
const superuser = who?.superuser === true;
|
|
485
|
+
const setOption = who?.set_option === true;
|
|
486
|
+
const instructions = () => appRoleSetupInstructions(connectionRole || void 0, uniqueSchemas, role, options.grants);
|
|
487
|
+
if (who?.role_exists !== true && !provision) throw new AppRoleSetupError(`The request role "${role}" does not exist, and rls.provisionRole is "never", so Rebase does not create it.`, instructions());
|
|
488
|
+
if (who?.role_exists !== true) try {
|
|
489
|
+
await run(`
|
|
490
|
+
DO $rebase_role$
|
|
491
|
+
BEGIN
|
|
492
|
+
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${role}') THEN
|
|
493
|
+
CREATE ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;
|
|
494
|
+
END IF;
|
|
495
|
+
END
|
|
496
|
+
$rebase_role$
|
|
497
|
+
`);
|
|
498
|
+
} catch (err) {
|
|
499
|
+
throw new AppRoleSetupError(`Failed to create the "${role}" role: ${failureReason(err)}`, instructions());
|
|
500
|
+
}
|
|
501
|
+
else await assertAppRoleRestricted(run, role);
|
|
502
|
+
if (!superuser) {
|
|
503
|
+
const [membership] = await run(`SELECT pg_has_role(current_user, ${sqlLiteral(role)}, '${setOption ? "SET" : "MEMBER"}') AS can_set`);
|
|
504
|
+
if (membership?.can_set !== true && !provision) throw new AppRoleSetupError(`The connection role "${connectionRole}" may not switch to "${role}", and rls.provisionRole is "never", so Rebase does not grant itself that.`, instructions());
|
|
505
|
+
if (membership?.can_set !== true) try {
|
|
506
|
+
await run(setOption ? `GRANT ${role} TO CURRENT_USER WITH SET TRUE, INHERIT FALSE` : `GRANT ${role} TO CURRENT_USER`);
|
|
507
|
+
} catch (err) {
|
|
508
|
+
throw new AppRoleSetupError(`The connection role "${connectionRole}" may not switch to "${role}" ${setOption ? "(no membership WITH SET TRUE)" : "(not a member)"} and cannot grant that to itself: ${failureReason(err)}`, instructions());
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
await proveRoleSwitch(run, uniqueSchemas, connectionRole || void 0, role);
|
|
512
|
+
if (options.inheritRoles?.length) await ensureInheritedRoles(run, role, options.inheritRoles);
|
|
513
|
+
await ensureAppRoleGrants(run, uniqueSchemas, {
|
|
514
|
+
role,
|
|
515
|
+
mode: options.grants,
|
|
516
|
+
managedTables: options.managedTables
|
|
517
|
+
});
|
|
518
|
+
logger.debug(`🔐 [rls] User role "${role}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* SQL: whether `c` (in namespace `n`) is a table the request roles are kept
|
|
522
|
+
* off when RLS is off on it — see `withheldTablesIn`.
|
|
523
|
+
*/
|
|
524
|
+
var isWithheldTable = (c, n) => `(${c}.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)}) OR (${n}.nspname = ${sqlLiteral(AUTH_USERS_TABLE.schema)} AND ${c}.relname = ${sqlLiteral(AUTH_USERS_TABLE.table)}))`;
|
|
525
|
+
/**
|
|
526
|
+
* The framework's internal tables in `schemas` that the request role can
|
|
527
|
+
* reach — `schema.table`, sorted — when nothing is left to take it back off.
|
|
528
|
+
*
|
|
529
|
+
* Every provisioning boot repairs this: each store revokes on its own table
|
|
530
|
+
* and {@link ensureAppRole}'s sweep revokes on the rest, because the grant
|
|
531
|
+
* tier hands the request role DML on whole schemas. A backend that changes
|
|
532
|
+
* nothing in its database runs neither, so a database whose `rebase_user` can
|
|
533
|
+
* read `refresh_tokens` or `api_keys` would stay that way for as long as it
|
|
534
|
+
* served. This is the question the sweep would have answered, asked instead.
|
|
535
|
+
*
|
|
536
|
+
* "Can reach" is what the role can actually do — through a grant to it, to a
|
|
537
|
+
* role it inherits, or to PUBLIC, on the table or on any of its columns —
|
|
538
|
+
* because that, not how the ACL is spelled, is what a request running as it
|
|
539
|
+
* gets. A table with RLS on is somebody's collection by that same rule as the
|
|
540
|
+
* sweep's, and is left out.
|
|
541
|
+
*/
|
|
542
|
+
async function findExposedInternalTables(run, schemas, role = REBASE_USER_ROLE$1) {
|
|
543
|
+
return (await run(`
|
|
544
|
+
SELECT n.nspname || '.' || c.relname AS name
|
|
545
|
+
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
546
|
+
WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})
|
|
547
|
+
AND ${isWithheldTable("c", "n")}
|
|
548
|
+
AND c.relkind IN ('r', 'p')
|
|
549
|
+
AND NOT c.relrowsecurity
|
|
550
|
+
AND (has_table_privilege(${sqlLiteral(role)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')
|
|
551
|
+
OR has_any_column_privilege(${sqlLiteral(role)}, c.oid, 'SELECT, INSERT, UPDATE'))
|
|
552
|
+
ORDER BY 1
|
|
553
|
+
`)).map((row) => String(row.name));
|
|
554
|
+
}
|
|
555
|
+
/** The connection role's oid, for a catalogue read. */
|
|
556
|
+
var CURRENT_ROLE_OID = "(SELECT oid FROM pg_roles WHERE rolname = current_user)";
|
|
557
|
+
/**
|
|
558
|
+
* SQL: may this connection grant every one of `privileges` on an object?
|
|
559
|
+
*
|
|
560
|
+
* Its owner, a role that inherits the owner, or a superuser — `pg_has_role`
|
|
561
|
+
* answers yes for all three — or a role holding each privilege `WITH GRANT
|
|
562
|
+
* OPTION`. Every one, because a grant short of one only warns and leaves the
|
|
563
|
+
* object reading as missing, which is the boot-after-boot re-grant this exists
|
|
564
|
+
* to stop.
|
|
565
|
+
*/
|
|
566
|
+
function mayGrant(kind, oid, owner, privileges) {
|
|
567
|
+
return `(pg_has_role(current_user, ${owner}, 'USAGE') OR (${privileges.map((p) => `has_${kind}_privilege(current_user, ${oid}, ${sqlLiteral(`${p} WITH GRANT OPTION`)})`).join(" AND ")}))`;
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Tables collections are served from that the user role holds no privilege on
|
|
571
|
+
* and this connection cannot grant it, because another role owns them.
|
|
572
|
+
*
|
|
573
|
+
* The grant tier passes these over — it could only fail on them — so on a
|
|
574
|
+
* database another application shares, a collection over that application's
|
|
575
|
+
* table boots and then refuses every request with "permission denied". This
|
|
576
|
+
* names them, with the owner who can run the grant. Refusing rather than
|
|
577
|
+
* widening, so the boot warns instead of stopping: the rest of the project
|
|
578
|
+
* works, and an introspected project serves every table in the schema,
|
|
579
|
+
* whoever owns it.
|
|
580
|
+
*/
|
|
581
|
+
async function findUngrantableTables(run, tables, role = REBASE_USER_ROLE$1) {
|
|
582
|
+
if (tables.length === 0) return [];
|
|
583
|
+
return (await run(`
|
|
584
|
+
SELECT n.nspname AS schema, c.relname AS table, pg_get_userbyid(c.relowner) AS owner
|
|
585
|
+
FROM unnest(${textArray(tables.map((t) => t.schema))}, ${textArray(tables.map((t) => t.table))}) AS w(s, t)
|
|
586
|
+
JOIN pg_namespace n ON n.nspname = w.s
|
|
587
|
+
JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = w.t
|
|
588
|
+
WHERE NOT ${mayGrant("table", "c.oid", "c.relowner", USER_TABLE_PRIVILEGES.split(", "))}
|
|
589
|
+
AND NOT has_table_privilege(to_regrole(${sqlLiteral(role)}), c.oid, 'SELECT, INSERT, UPDATE, DELETE')
|
|
590
|
+
ORDER BY 1, 2
|
|
591
|
+
`)).map((row) => {
|
|
592
|
+
const name = `${quoteIdent(String(row.schema))}.${quoteIdent(String(row.table))}`;
|
|
593
|
+
return {
|
|
594
|
+
name,
|
|
595
|
+
owner: String(row.owner),
|
|
596
|
+
grant: `GRANT ${USER_TABLE_PRIVILEGES} ON ${name} TO ${role};`
|
|
597
|
+
};
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* The grant tier's state for every existing schema in `schemas`, in one read.
|
|
602
|
+
*
|
|
603
|
+
* A grant counts as present only as the statement this tier runs would record
|
|
604
|
+
* it — grantor the object's owner, which is what a GRANT by the owner, a member
|
|
605
|
+
* of the owning role or a superuser records, or this connection itself, which
|
|
606
|
+
* is what a GRANT on its grant option records — so skipping it leaves the ACL
|
|
607
|
+
* exactly as running it would. Anything else reads as missing, and the
|
|
608
|
+
* statement runs as it always did.
|
|
609
|
+
*/
|
|
610
|
+
async function readSchemaGrants(run, schemas, role = REBASE_USER_ROLE$1, managedTables) {
|
|
611
|
+
const managed = managedTables ? `(SELECT * FROM unnest(${textArray(managedTables.map((t) => t.schema))}, ${textArray(managedTables.map((t) => t.table))}))` : void 0;
|
|
612
|
+
const onlyManagedTables = managed ? `AND (n.nspname, c.relname::text) IN ${managed}` : "";
|
|
613
|
+
const onlyManagedSequences = managed ? `AND EXISTS (SELECT 1 FROM pg_depend d JOIN pg_class t ON t.oid = d.refobjid
|
|
614
|
+
WHERE d.objid = c.oid AND d.deptype IN ('a', 'i')
|
|
615
|
+
AND (n.nspname, t.relname::text) IN ${managed})` : "";
|
|
616
|
+
const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(role)})`;
|
|
617
|
+
/** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */
|
|
618
|
+
const held = (acl, privileges, grantor) => `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}${grantor ? ` AND a.grantor IN (${grantor}, ${CURRENT_ROLE_OID})` : ""} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(", ")}))`;
|
|
619
|
+
const DML = [
|
|
620
|
+
"SELECT",
|
|
621
|
+
"INSERT",
|
|
622
|
+
"UPDATE",
|
|
623
|
+
"DELETE"
|
|
624
|
+
];
|
|
625
|
+
const SEQ = ["USAGE", "SELECT"];
|
|
626
|
+
const viewRows = (alias) => `(${alias}.relkind = 'm' AND COALESCE(obj_description(${alias}.oid, 'pg_class'), '') LIKE '${VIEW_ROWS_COMMENT_PREFIX}%')`;
|
|
627
|
+
const rows = await run(`
|
|
628
|
+
SELECT n.nspname AS schema,
|
|
629
|
+
-- Settled as well when this connection cannot grant it: a schema
|
|
630
|
+
-- another role owns (a shared database's \`public\`) only warned,
|
|
631
|
+
-- and was re-granted on every boot. PUBLIC's own USAGE covers it there.
|
|
632
|
+
(${held("n.nspacl", ["USAGE"], "n.nspowner")} = 1
|
|
633
|
+
OR NOT ${mayGrant("schema", "n.oid", "n.nspowner", ["USAGE"])}) AS usage,
|
|
634
|
+
ARRAY(
|
|
635
|
+
SELECT c.relname::text FROM pg_class c
|
|
636
|
+
WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
|
|
637
|
+
AND NOT (${isWithheldTable("c", "n")} AND NOT c.relrowsecurity)
|
|
638
|
+
AND ${mayGrant("table", "c.oid", "c.relowner", DML)}
|
|
639
|
+
${onlyManagedTables}
|
|
640
|
+
AND NOT ${viewRows("c")}
|
|
641
|
+
AND ${held("c.relacl", DML, "c.relowner")} < ${DML.length}
|
|
642
|
+
ORDER BY 1
|
|
643
|
+
) AS tables,
|
|
644
|
+
ARRAY(
|
|
645
|
+
SELECT c.relname::text FROM pg_class c
|
|
646
|
+
WHERE c.relnamespace = n.oid AND c.relkind = 'S'
|
|
647
|
+
AND ${mayGrant("sequence", "c.oid", "c.relowner", SEQ)}
|
|
648
|
+
${onlyManagedSequences}
|
|
649
|
+
AND ${held("c.relacl", SEQ, "c.relowner")} < ${SEQ.length}
|
|
650
|
+
ORDER BY 1
|
|
651
|
+
) AS sequences,
|
|
652
|
+
EXISTS (
|
|
653
|
+
SELECT 1 FROM pg_default_acl d
|
|
654
|
+
WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
|
|
655
|
+
AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'
|
|
656
|
+
AND ${held("d.defaclacl", DML)} = ${DML.length}
|
|
657
|
+
) AS default_tables,
|
|
658
|
+
EXISTS (
|
|
659
|
+
SELECT 1 FROM pg_default_acl d
|
|
660
|
+
WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
|
|
661
|
+
AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'
|
|
662
|
+
AND ${held("d.defaclacl", SEQ)} = ${SEQ.length}
|
|
663
|
+
) AS default_sequences,
|
|
664
|
+
ARRAY(
|
|
665
|
+
SELECT c.relname::text FROM pg_class c
|
|
666
|
+
WHERE c.relnamespace = n.oid AND ${isWithheldTable("c", "n")} AND NOT c.relrowsecurity
|
|
667
|
+
AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))
|
|
668
|
+
ORDER BY 1
|
|
669
|
+
) AS internal_granted,
|
|
670
|
+
ARRAY(
|
|
671
|
+
SELECT c.relname::text FROM pg_class c
|
|
672
|
+
WHERE c.relnamespace = n.oid AND ${viewRows("c")}
|
|
673
|
+
AND EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target})
|
|
674
|
+
ORDER BY 1
|
|
675
|
+
) AS view_rows_granted
|
|
676
|
+
FROM pg_namespace n
|
|
677
|
+
WHERE n.nspname = ANY(${textArray(schemas)})
|
|
678
|
+
`);
|
|
679
|
+
const grants = /* @__PURE__ */ new Map();
|
|
680
|
+
for (const row of rows) {
|
|
681
|
+
const internalGranted = row.internal_granted;
|
|
682
|
+
const viewRowsGranted = row.view_rows_granted;
|
|
683
|
+
grants.set(String(row.schema), {
|
|
684
|
+
usage: row.usage === true,
|
|
685
|
+
tables: textArrayValue(row.tables),
|
|
686
|
+
sequences: textArrayValue(row.sequences),
|
|
687
|
+
defaultTables: row.default_tables === true,
|
|
688
|
+
defaultSequences: row.default_sequences === true,
|
|
689
|
+
internalGranted: textArrayValue(internalGranted),
|
|
690
|
+
viewRowsGranted: textArrayValue(viewRowsGranted)
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
return grants;
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Grant each of `inheritRoles` to the request role `WITH INHERIT TRUE`, so a
|
|
697
|
+
* policy written `TO` one of them — Supabase's `authenticated`, say — applies
|
|
698
|
+
* to requests.
|
|
699
|
+
*
|
|
700
|
+
* PostgreSQL 16 and newer only. From 16 inheritance is an option of each
|
|
701
|
+
* grant, so the request role takes on these roles' privileges and stays
|
|
702
|
+
* NOINHERIT towards every other membership. Before 16 the only lever is the
|
|
703
|
+
* role's own INHERIT attribute, which would hand it every role it belongs to;
|
|
704
|
+
* that is refused rather than done.
|
|
705
|
+
*/
|
|
706
|
+
async function ensureInheritedRoles(run, role, inheritRoles) {
|
|
707
|
+
const [server] = await run(`SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant`);
|
|
708
|
+
if (server?.per_grant !== true) throw new AppRoleSetupError(`rls.inheritRoles (${inheritRoles.join(", ")}) needs PostgreSQL 16 or newer: before 16 the request role "${role}" can only inherit by inheriting from every role it belongs to.`, "Upgrade to PostgreSQL 16+, or drop rls.inheritRoles and express those policies as the collection's securityRules.");
|
|
709
|
+
const rows = await run(`
|
|
710
|
+
SELECT w.name, r.oid IS NOT NULL AS present,
|
|
711
|
+
COALESCE(pg_has_role(to_regrole(${sqlLiteral(role)}), r.oid, 'USAGE'), false) AS inherits
|
|
712
|
+
FROM unnest(${textArray(inheritRoles)}) AS w(name)
|
|
713
|
+
LEFT JOIN pg_roles r ON r.rolname = w.name
|
|
714
|
+
`);
|
|
715
|
+
const missing = rows.filter((row) => row.present !== true).map((row) => String(row.name));
|
|
716
|
+
if (missing.length > 0) throw new AppRoleSetupError(`rls.inheritRoles names ${missing.map((m) => `"${m}"`).join(", ")}, which ${missing.length === 1 ? "does" : "do"} not exist in this cluster.`, "Create the role(s), or remove them from rls.inheritRoles.");
|
|
717
|
+
for (const row of rows) {
|
|
718
|
+
if (row.inherits === true) continue;
|
|
719
|
+
const name = String(row.name);
|
|
720
|
+
const grant = `GRANT ${quoteIdent(name)} TO ${quoteIdent(role)} WITH INHERIT TRUE, SET FALSE`;
|
|
721
|
+
try {
|
|
722
|
+
await run(grant);
|
|
723
|
+
} catch (err) {
|
|
724
|
+
throw new AppRoleSetupError(`Could not grant "${name}" to the request role "${role}" for rls.inheritRoles: ${failureReason(err)}`, `Run as a database administrator, then restart:\n\n${grant};`);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Provision the role admin requests run as for one request role:
|
|
730
|
+
* `<role>_admin`, inheriting `role` — its grants, and every policy written
|
|
731
|
+
* for it — and {@link REBASE_ADMIN_ROLE}, with the connection able to switch
|
|
732
|
+
* to it. The role itself goes through {@link ensureAppRole} (created NOLOGIN
|
|
733
|
+
* NOSUPERUSER NOBYPASSRLS, checked as restricted when found, the switch
|
|
734
|
+
* proved), with no grants of its own: everything it can reach, it reaches as
|
|
735
|
+
* `role` does.
|
|
736
|
+
*
|
|
737
|
+
* Inheriting is per grant from PostgreSQL 16 (`WITH INHERIT TRUE`); before
|
|
738
|
+
* that it is the role's own `INHERIT` attribute, harmless here because this
|
|
739
|
+
* role belongs to exactly the two roles granted below.
|
|
740
|
+
*/
|
|
741
|
+
async function ensureAdminRequestRole(run, schemas, options) {
|
|
742
|
+
const { role, adminRole } = options;
|
|
743
|
+
const provision = options.provisionRole !== "never";
|
|
744
|
+
const [present] = await run(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') AS present`);
|
|
745
|
+
if (present?.present !== true) {
|
|
746
|
+
if (!provision) throw new AppRoleSetupError(`The role "${REBASE_ADMIN_ROLE}" does not exist, and rls.provisionRole is "never", so Rebase does not create it.`, `Run as a database administrator, then restart:\n\nCREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;`);
|
|
747
|
+
await run(ADMIN_POLICY_ROLE_SQL);
|
|
748
|
+
}
|
|
749
|
+
await ensureAppRole(run, schemas, {
|
|
750
|
+
role: adminRole,
|
|
751
|
+
provisionRole: options.provisionRole,
|
|
752
|
+
grants: "none"
|
|
753
|
+
});
|
|
754
|
+
const [state] = await run(`
|
|
755
|
+
SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
756
|
+
r.rolinherit AS inherits_all,
|
|
757
|
+
pg_has_role(r.oid, to_regrole(${sqlLiteral(role)}), 'USAGE') AS has_request_role,
|
|
758
|
+
pg_has_role(r.oid, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE') AS has_admin_role
|
|
759
|
+
FROM pg_roles r WHERE r.rolname = ${sqlLiteral(adminRole)}
|
|
760
|
+
`);
|
|
761
|
+
const perGrant = state?.per_grant === true;
|
|
762
|
+
const missing = [...state?.has_request_role === true ? [] : [role], ...state?.has_admin_role === true ? [] : [REBASE_ADMIN_ROLE]];
|
|
763
|
+
if (missing.length === 0) return;
|
|
764
|
+
const statements = [...!perGrant && state?.inherits_all !== true ? [`ALTER ROLE ${adminRole} INHERIT`] : [], ...missing.map((granted) => perGrant ? `GRANT ${quoteIdent(granted)} TO ${adminRole} WITH INHERIT TRUE, SET FALSE` : `GRANT ${quoteIdent(granted)} TO ${adminRole}`)];
|
|
765
|
+
const instructions = `Run as a database administrator, then restart:\n\n${statements.map((st) => `${st};`).join("\n")}`;
|
|
766
|
+
if (!provision) throw new AppRoleSetupError(`The admin request role "${adminRole}" does not inherit ${missing.map((m) => `"${m}"`).join(" and ")}, and rls.provisionRole is "never", so Rebase does not grant it.`, instructions);
|
|
767
|
+
try {
|
|
768
|
+
for (const statement of statements) await run(statement);
|
|
769
|
+
} catch (err) {
|
|
770
|
+
throw new AppRoleSetupError(`Could not let the admin request role "${adminRole}" inherit ${missing.map((m) => `"${m}"`).join(" and ")}: ${failureReason(err)}`, instructions);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Let the connection role itself pass the server-or-admin policies, by
|
|
775
|
+
* inheriting {@link REBASE_ADMIN_ROLE} — which is what `TO public` gave it.
|
|
776
|
+
*
|
|
777
|
+
* It matters where the connection is subject to RLS: always, when it owns
|
|
778
|
+
* none of the tables (requests then run as the connection itself, so the
|
|
779
|
+
* server context and admins depend on it), and on any table it does not own
|
|
780
|
+
* otherwise. Best effort: a connection that cannot be granted the role is
|
|
781
|
+
* told what to run, and its server-context and admin reads of those tables are
|
|
782
|
+
* refused — closed, never wider — until someone does.
|
|
783
|
+
*/
|
|
784
|
+
async function ensureConnectionInheritsAdminRole(run, options) {
|
|
785
|
+
const [state] = await run(`
|
|
786
|
+
SELECT current_user AS role,
|
|
787
|
+
(SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user) AS exempt,
|
|
788
|
+
current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
789
|
+
to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present,
|
|
790
|
+
COALESCE(pg_has_role(current_user, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS inherits
|
|
791
|
+
`);
|
|
792
|
+
if (state?.exempt === true || state?.inherits === true) return;
|
|
793
|
+
const connection = String(state?.role ?? "");
|
|
794
|
+
const grant = state?.per_grant === true ? `GRANT ${REBASE_ADMIN_ROLE} TO ${quoteIdent(connection)} WITH INHERIT TRUE, SET FALSE` : `GRANT ${REBASE_ADMIN_ROLE} TO ${quoteIdent(connection)}`;
|
|
795
|
+
const warn = (why, roleExists) => (roleExists ? (m) => logger.warn(m) : (m) => logger.debug(m))(`⚠️ RLS enforcement: the connection role "${connection}" does not inherit "${REBASE_ADMIN_ROLE}" (${why}), so on any table it does not own, its server-context and admin requests do not pass the server-or-admin policies and are refused. Run as an administrator: ${roleExists ? "" : `CREATE ROLE ${REBASE_ADMIN_ROLE} NOLOGIN; `}${grant}; — or declare rls.adminPolicies "public".`);
|
|
796
|
+
if (!options.provision) {
|
|
797
|
+
warn("this driver was opened without provisioning", state?.present === true);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
let roleExists = state?.present === true;
|
|
801
|
+
try {
|
|
802
|
+
if (!roleExists) await run(ADMIN_POLICY_ROLE_SQL);
|
|
803
|
+
roleExists = true;
|
|
804
|
+
await run(grant);
|
|
805
|
+
} catch (err) {
|
|
806
|
+
warn(failureReason(err), roleExists);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* The request identity a boot hands the driver and the realtime refetch, with
|
|
811
|
+
* the admin switch on when every admin request role is ready: provisioned
|
|
812
|
+
* here, or — on a boot that provisions nothing — found existing, inheriting
|
|
813
|
+
* what it should and switchable. Otherwise admin requests run as the request
|
|
814
|
+
* role, as before, and the boot says why: under `adminPolicies: "adminRole"`,
|
|
815
|
+
* policies already written `TO rebase_admin` then refuse them.
|
|
816
|
+
*/
|
|
817
|
+
async function settleAdminRequestRoles(run, schemas, settings, options) {
|
|
818
|
+
if (settings.adminRoles.size === 0) return settings.request;
|
|
819
|
+
const failures = [];
|
|
820
|
+
for (const [role, adminRole] of settings.adminRoles) try {
|
|
821
|
+
await ensureAdminRequestRole(run, schemas, {
|
|
822
|
+
role,
|
|
823
|
+
adminRole,
|
|
824
|
+
provisionRole: options.provision ? settings.provisionRole : "never"
|
|
825
|
+
});
|
|
826
|
+
} catch (err) {
|
|
827
|
+
failures.push(`"${adminRole}": ${err instanceof Error ? err.message : String(err)}`);
|
|
828
|
+
}
|
|
829
|
+
if (failures.length > 0) {
|
|
830
|
+
const [marker] = await run(`SELECT to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present`);
|
|
831
|
+
(marker?.present === true ? (m) => logger.warn(m) : (m) => logger.info(m))(`${marker?.present === true ? "⚠️" : "🔐"} RLS enforcement: admin requests keep running as the request role, because ${failures.join("; ")}. The server-or-admin policies are written TO public by this server until that is fixed, so signed-in users' owner-scoped reads cannot use the owner index. Create ${REBASE_ADMIN_ROLE} and the admin request role as above to change that, or declare adminPolicies "public" to say this on purpose.`);
|
|
832
|
+
return settings.request;
|
|
833
|
+
}
|
|
834
|
+
const adminRoles = settings.adminRoles;
|
|
835
|
+
return {
|
|
836
|
+
...settings.request,
|
|
837
|
+
adminRoleFor: (role) => adminRoles.get(role)
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Whether policies written `TO rebase_admin` reach every caller they are for on
|
|
842
|
+
* this connection, read from the catalogue without changing anything: the role
|
|
843
|
+
* exists, the connection passes it (exempt from RLS, or inheriting it — the
|
|
844
|
+
* server context on tables it does not own), and each of `adminRoles` exists,
|
|
845
|
+
* inherits its request role and `rebase_admin`, and the connection can switch
|
|
846
|
+
* into it. The state {@link settleAdminRequestRoles} and
|
|
847
|
+
* {@link ensureConnectionInheritsAdminRole} leave when both succeed.
|
|
848
|
+
*
|
|
849
|
+
* With `existingOnly`, an admin role that does not exist is passed over, but at
|
|
850
|
+
* least one must be ready: for a role list read back from the database, which
|
|
851
|
+
* does not say which role is an anonymous one with no admin counterpart.
|
|
852
|
+
*
|
|
853
|
+
* Anything it cannot read answers `false`, and `false` means `TO public`: the
|
|
854
|
+
* shape every caller passes, as before the admin role existed.
|
|
855
|
+
*/
|
|
856
|
+
async function adminSwitchLive(run, adminRoles, options = {}) {
|
|
857
|
+
if (adminRoles.size === 0) return false;
|
|
858
|
+
const [connection] = await run(`
|
|
859
|
+
SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
860
|
+
to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present,
|
|
861
|
+
COALESCE((SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user), false)
|
|
862
|
+
OR COALESCE(pg_has_role(current_user, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS passes
|
|
863
|
+
`);
|
|
864
|
+
if (connection?.present !== true || connection?.passes !== true) return false;
|
|
865
|
+
const privilege = connection.per_grant === true ? "SET" : "MEMBER";
|
|
866
|
+
let ready = 0;
|
|
867
|
+
for (const [role, adminRole] of adminRoles) {
|
|
868
|
+
const [state] = await run(`
|
|
869
|
+
SELECT to_regrole(${sqlLiteral(adminRole)}) IS NOT NULL AS present,
|
|
870
|
+
COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole(${sqlLiteral(role)}), 'USAGE'), false)
|
|
871
|
+
AND COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false)
|
|
872
|
+
AND COALESCE(pg_has_role(current_user, to_regrole(${sqlLiteral(adminRole)}), '${privilege}'), false) AS ready
|
|
873
|
+
`);
|
|
874
|
+
if (options.existingOnly && state?.present !== true) continue;
|
|
875
|
+
if (state?.ready !== true) return false;
|
|
876
|
+
ready++;
|
|
877
|
+
}
|
|
878
|
+
return ready > 0;
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* The admin switch for a boot whose requests switch roles: settle the admin
|
|
882
|
+
* request roles and the connection's `rebase_admin`, then say whether the
|
|
883
|
+
* switch is live — which is what decides where the policies step writes the
|
|
884
|
+
* server-or-admin policies. `TO rebase_admin` only when it is: written there
|
|
885
|
+
* while admin requests still run as the request role, they refuse every admin
|
|
886
|
+
* caller, `dataAsAdmin` included, as an empty table. Otherwise `TO public`, the
|
|
887
|
+
* documented fallback, which the request role passes.
|
|
888
|
+
*/
|
|
889
|
+
async function settleAdminSwitch(run, schemas, settings, options) {
|
|
890
|
+
const request = await settleAdminRequestRoles(run, schemas, settings, options);
|
|
891
|
+
if (settings.adminPolicies !== "adminRole") return {
|
|
892
|
+
request,
|
|
893
|
+
adminPoliciesLive: false
|
|
894
|
+
};
|
|
895
|
+
await ensureConnectionInheritsAdminRole(run, options);
|
|
896
|
+
return {
|
|
897
|
+
request,
|
|
898
|
+
adminPoliciesLive: request.adminRoleFor !== void 0 && await adminSwitchLive(run, settings.adminRoles)
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Where `db push` and `rebase doctor` expect the server-or-admin policies, for
|
|
903
|
+
* the request roles this database records (or the configured ones): `TO
|
|
904
|
+
* rebase_admin` only when {@link adminSwitchLive} says a server on this
|
|
905
|
+
* connection would have the switch live, `TO public` otherwise — the same
|
|
906
|
+
* answer a boot reaches, without provisioning anything. Settings that do not
|
|
907
|
+
* resolve answer `false`.
|
|
908
|
+
*/
|
|
909
|
+
async function adminPoliciesLiveForCli(run) {
|
|
910
|
+
try {
|
|
911
|
+
const settings = cliRlsSettings(await readRecordedRequestRoles(run));
|
|
912
|
+
if (settings.adminPolicies !== "adminRole") return false;
|
|
913
|
+
return await adminSwitchLive(run, settings.adminRoles, { existingOnly: true });
|
|
914
|
+
} catch {
|
|
915
|
+
return false;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
|
|
920
|
+
* schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
|
|
921
|
+
* sequences, the default privileges that cover what this role creates later,
|
|
922
|
+
* and Rebase's own tables taken back — for a role and membership already
|
|
923
|
+
* provisioned.
|
|
924
|
+
*
|
|
925
|
+
* Every statement is issued only when the catalogue says it would change
|
|
926
|
+
* something. They used to run unconditionally, twice per boot (at connect, and
|
|
927
|
+
* again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every
|
|
928
|
+
* table's `pg_class` row whether or not the ACL changes, which invalidates
|
|
929
|
+
* every table's cached plans on every connection, and the internal-table sweep
|
|
930
|
+
* ran 23 `REVOKE`s per schema. A boot against a database whose grants already
|
|
931
|
+
* hold now reads one catalogue query and writes nothing.
|
|
932
|
+
*
|
|
933
|
+
* Tables and sequences are granted by name, the ones that are missing it and
|
|
934
|
+
* that this connection may grant on — not `ON ALL … IN SCHEMA`, which also
|
|
935
|
+
* tries every relation another role owns. On a schema shared with another
|
|
936
|
+
* application that statement fails for a table this connection holds no
|
|
937
|
+
* privilege on, or only warns for one it holds without grant option, and either
|
|
938
|
+
* way the schema never reads as granted. The ACLs this leaves are the ones the
|
|
939
|
+
* schema-wide statement left on everything it could reach.
|
|
940
|
+
*
|
|
941
|
+
* Table owners (the expected non-superuser posture) can always grant on their
|
|
942
|
+
* own objects, so this needs no extra privilege.
|
|
943
|
+
*/
|
|
944
|
+
async function ensureAppRoleGrants(run, schemas, options = {}) {
|
|
945
|
+
const role = options.role ?? REBASE_USER_ROLE$1;
|
|
946
|
+
const mode = options.mode ?? "schema";
|
|
947
|
+
if (mode === "none") return;
|
|
948
|
+
const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
|
|
949
|
+
const grants = await readSchemaGrants(run, uniqueSchemas, role, mode === "managed" ? options.managedTables ?? [] : void 0);
|
|
950
|
+
for (const schema of uniqueSchemas) {
|
|
951
|
+
const state = grants.get(schema);
|
|
952
|
+
if (!state) continue;
|
|
953
|
+
const s = quoteIdent(schema);
|
|
954
|
+
if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${role}`);
|
|
955
|
+
const named = (relations) => relations.map((r) => `${s}.${quoteIdent(r)}`).join(", ");
|
|
956
|
+
if (state.tables.length > 0) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON TABLE ${named(state.tables)} TO ${role}`);
|
|
957
|
+
if (state.sequences.length > 0) await run(`GRANT USAGE, SELECT ON SEQUENCE ${named(state.sequences)} TO ${role}`);
|
|
958
|
+
for (const rows of state.viewRowsGranted) await run(`REVOKE ALL ON ${s}.${quoteIdent(rows)} FROM ${role}`);
|
|
959
|
+
if (!state.defaultTables && mode === "schema") await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${role}`);
|
|
960
|
+
if (!state.defaultSequences && mode === "schema") await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${role}`);
|
|
961
|
+
if (state.internalGranted.length === 0) continue;
|
|
962
|
+
await revokeInternalTableAccess(async (text) => {
|
|
963
|
+
await run(text);
|
|
964
|
+
}, schema, {
|
|
965
|
+
tables: state.internalGranted,
|
|
966
|
+
onError: (table, error) => logger.warn(`🔐 [rls] Could not revoke "${role}" access to "${schema}"."${table}" — it stays reachable by authenticated requests: ` + (error instanceof Error ? error.message : String(error)))
|
|
967
|
+
});
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`
|
|
972
|
+
* sweep would change — the user role holds a privilege on them, or their ACL
|
|
973
|
+
* has never been written. One read; the sweep it narrows is one `DO` per
|
|
974
|
+
* table name.
|
|
975
|
+
*/
|
|
976
|
+
async function internalTablesGrantedToUserRole(run, schema, role = REBASE_USER_ROLE$1) {
|
|
977
|
+
return (await readSchemaGrants(run, [schema], role)).get(schema)?.internalGranted ?? [];
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* Apply the authenticated context to a transaction: the `app.*` GUCs that RLS
|
|
981
|
+
* policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when
|
|
982
|
+
* `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS
|
|
983
|
+
* binds every statement in this transaction (reads *and* writes).
|
|
984
|
+
*
|
|
985
|
+
* GUCs are set with `is_local = true` and the role switch is `LOCAL`: both
|
|
986
|
+
* reset at commit/rollback, so pooled connections are never polluted.
|
|
987
|
+
*
|
|
988
|
+
* Fails closed by construction: if the role switch errors, the transaction
|
|
989
|
+
* aborts instead of proceeding privileged.
|
|
990
|
+
*
|
|
991
|
+
* SECURITY: this function is only ever called on the **user** path (the server
|
|
992
|
+
* context uses the base/owner driver and never calls it). The default policies
|
|
993
|
+
* treat `rebase.uid() IS NULL` as the trusted server context, and `rebase.uid()`
|
|
994
|
+
* is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
|
|
995
|
+
* be read as NULL and silently escalate a user request to server privileges.
|
|
996
|
+
* Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
|
|
997
|
+
* rather than trusting every caller (e.g. realtime subscription auth) to do it.
|
|
998
|
+
* That sentinel is exported from `@rebasepro/types` because it leaks into rule
|
|
999
|
+
* semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.
|
|
1000
|
+
*/
|
|
1001
|
+
async function applyAuthContext(tx, auth, userRole) {
|
|
1002
|
+
const settings = authContextSettings(auth, userRole);
|
|
1003
|
+
await tx.execute(sql`SELECT ${sql.join(settings.map(([name, value]) => sql`${sql.raw(`set_config(${settingNameLiteral(name)}, `)}${value}, true)`), sql`, `)}`);
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* {@link applyAuthContext} as one statement and its values, for a transaction
|
|
1007
|
+
* that sends it in the same batch as its first query
|
|
1008
|
+
* (`pipelined-transaction.ts`). `before` are settings of the transaction's own
|
|
1009
|
+
* — what a pooled connection could not carry at connect — set ahead of the
|
|
1010
|
+
* caller's, in the same statement.
|
|
1011
|
+
*/
|
|
1012
|
+
function authContextStatement(auth, userRole, before = []) {
|
|
1013
|
+
const settings = [...before, ...authContextSettings(auth, userRole)];
|
|
1014
|
+
return {
|
|
1015
|
+
text: `SELECT ${settings.map(([name], i) => `set_config(${settingNameLiteral(name)}, $${i + 1}, true)`).join(", ")}`,
|
|
1016
|
+
values: settings.map(([, value]) => value)
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* A setting's name as a SQL literal. Names are this module's constants (and
|
|
1021
|
+
* the pooled settings' two), never a caller's value, which is a bound
|
|
1022
|
+
* parameter; written into the text so a statement log reads as the settings
|
|
1023
|
+
* it sets.
|
|
1024
|
+
*/
|
|
1025
|
+
function settingNameLiteral(name) {
|
|
1026
|
+
return `'${name.replace(/'/g, "''")}'`;
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* The transaction-local settings that make a transaction the caller's, in the
|
|
1030
|
+
* order they are set: the `app.*` GUCs, then the role.
|
|
1031
|
+
*
|
|
1032
|
+
* `userRole` is the role to switch to — or, for a project whose requests do not
|
|
1033
|
+
* all run as one role or carry their identity in more than `app.*`, the
|
|
1034
|
+
* resolved `rls` settings ({@link RequestIdentity}), which choose the role for
|
|
1035
|
+
* this caller and add their own settings ahead of the switch.
|
|
1036
|
+
*/
|
|
1037
|
+
function authContextSettings(auth, userRole) {
|
|
1038
|
+
const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
|
|
1039
|
+
const normalizedRoles = auth.roles.map((r) => typeof r === "string" ? r : r?.id ?? String(r));
|
|
1040
|
+
const isAnonymous = auth.isAnonymous === true ? "true" : "false";
|
|
1041
|
+
const settings = [
|
|
1042
|
+
["app.uid", uid],
|
|
1043
|
+
["app.user_id", uid],
|
|
1044
|
+
["app.user_roles", normalizedRoles.join(",")],
|
|
1045
|
+
["app.is_anonymous", isAnonymous],
|
|
1046
|
+
["app.jwt", JSON.stringify({
|
|
1047
|
+
...auth.claims ?? {},
|
|
1048
|
+
sub: uid,
|
|
1049
|
+
roles: auth.roles,
|
|
1050
|
+
is_anonymous: auth.isAnonymous === true
|
|
1051
|
+
})]
|
|
1052
|
+
];
|
|
1053
|
+
const role = typeof userRole === "object" ? userRole.roleFor(auth) : userRole;
|
|
1054
|
+
if (typeof userRole === "object" && role) for (const [name, value] of userRole.settingsFor(auth, role)) settings.push([name, value]);
|
|
1055
|
+
const admin = role && typeof userRole === "object" && holdsAdminRole(normalizedRoles.map(String)) ? userRole.adminRoleFor?.(role) : void 0;
|
|
1056
|
+
if (role) settings.push(["role", admin ?? role]);
|
|
1057
|
+
return settings;
|
|
1058
|
+
}
|
|
1059
|
+
/** Role names from other BaaS platforms that people reach for out of habit. */
|
|
1060
|
+
var FOREIGN_CONVENTION_ROLES = {
|
|
1061
|
+
authenticated: "Supabase",
|
|
1062
|
+
anon: "Supabase",
|
|
1063
|
+
service_role: "Supabase"
|
|
1064
|
+
};
|
|
1065
|
+
/**
|
|
1066
|
+
* Warn about rules that read as "signed-in users only" but admit anonymous
|
|
1067
|
+
* callers — `rebase.uid() IS NOT NULL`, or a comparison against another
|
|
1068
|
+
* platform's magic user id such as `'anon'`.
|
|
1069
|
+
*
|
|
1070
|
+
* The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
|
|
1071
|
+
* of the same habit. A foreign `pgRoles` value makes a policy unreachable and
|
|
1072
|
+
* the table reads empty — loud, and that guard throws. These do the opposite:
|
|
1073
|
+
* the rule compiles to a grant, and nothing looks wrong until the data is
|
|
1074
|
+
* already public.
|
|
1075
|
+
*
|
|
1076
|
+
* Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
|
|
1077
|
+
* serving traffic today: refusing to boot would take an app offline to report a
|
|
1078
|
+
* problem it already has, and on the read path it would take it offline
|
|
1079
|
+
* *because* its data was exposed. Rewriting the author's SQL is not an option
|
|
1080
|
+
* either — this is the escape hatch whose whole promise is that it means what it
|
|
1081
|
+
* says. So: say so, loudly, and leave the rule alone.
|
|
1082
|
+
*/
|
|
1083
|
+
function warnOnAnonymousGrants(collections) {
|
|
1084
|
+
const byRisk = /* @__PURE__ */ new Map();
|
|
1085
|
+
for (const collection of collections) for (const rule of collection.securityRules ?? []) {
|
|
1086
|
+
const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
|
|
1087
|
+
const risks = [usingExpr, withCheckExpr].filter((e) => e !== null).flatMap(findAnonymousGrants);
|
|
1088
|
+
for (const risk of risks) {
|
|
1089
|
+
const key = `${risk.pattern}:${risk.detail}`;
|
|
1090
|
+
const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
|
|
1091
|
+
const entry = byRisk.get(key) ?? {
|
|
1092
|
+
risk,
|
|
1093
|
+
sites: []
|
|
1094
|
+
};
|
|
1095
|
+
if (!entry.sites.includes(site)) entry.sites.push(site);
|
|
1096
|
+
byRisk.set(key, entry);
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
if (byRisk.size === 0) return;
|
|
1100
|
+
const problems = [...byRisk.values()].map(({ risk, sites }) => ` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`);
|
|
1101
|
+
logger.warn(`Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are true for everyone:\n\n` + problems.join("\n\n") + "\n");
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Name the collections whose raw policy SQL still calls the pre-1.0 helpers.
|
|
1105
|
+
*
|
|
1106
|
+
* The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the
|
|
1107
|
+
* database, so nothing is broken and no policy is wrong — which is exactly why
|
|
1108
|
+
* this has to be said out loud. A silent rewrite that works forever is not a
|
|
1109
|
+
* migration, it is a second supported spelling nobody wrote down, and the next
|
|
1110
|
+
* person to read those rules will copy the old one.
|
|
1111
|
+
*
|
|
1112
|
+
* Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,
|
|
1113
|
+
* `policy.rolesOverlap(...)`) compile from the model and were never affected.
|
|
1114
|
+
*/
|
|
1115
|
+
function warnOnLegacyRlsFunctions(collections) {
|
|
1116
|
+
const sites = [];
|
|
1117
|
+
for (const collection of collections) for (const rule of collection.securityRules ?? []) {
|
|
1118
|
+
const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
|
|
1119
|
+
if (![usingExpr, withCheckExpr].filter((e) => e !== null).some(containsLegacyRlsCall)) continue;
|
|
1120
|
+
const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
|
|
1121
|
+
if (!sites.includes(site)) sites.push(site);
|
|
1122
|
+
}
|
|
1123
|
+
if (sites.length === 0) return;
|
|
1124
|
+
logger.warn(`These security rules call the pre-1.0 RLS helpers (\`auth.uid()\`, \`auth.roles()\`, \`auth.jwt()\`). They still work — the compiler rewrites them — but the functions now live in the \`rebase\` schema, and the \`auth\` one is Supabase's. Update the raw SQL in these rules to \`${REBASE_SCHEMA}.uid()\` and friends, or switch them to the structured helpers (\`policy.authUid()\`, \`policy.rolesOverlap()\`), which never had to be spelled by hand:\n\n` + sites.map((s) => ` • ${s}`).join("\n") + "\n");
|
|
1125
|
+
}
|
|
1126
|
+
/** Whether any `raw` expression in the tree calls a pre-1.0 helper. */
|
|
1127
|
+
function containsLegacyRlsCall(expr) {
|
|
1128
|
+
switch (expr.kind) {
|
|
1129
|
+
case "raw": return usesLegacyRlsFunctions(expr.sql);
|
|
1130
|
+
case "and":
|
|
1131
|
+
case "or": return expr.operands.some(containsLegacyRlsCall);
|
|
1132
|
+
case "not": return containsLegacyRlsCall(expr.operand);
|
|
1133
|
+
case "existsIn": return containsLegacyRlsCall(expr.where);
|
|
1134
|
+
default: return false;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Reject `pgRoles` that this server can never satisfy.
|
|
1139
|
+
*
|
|
1140
|
+
* `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a
|
|
1141
|
+
* role the request never runs as simply never applies — and RLS then filters
|
|
1142
|
+
* every row. The table reads as empty, which is indistinguishable from having
|
|
1143
|
+
* no data, so the mistake survives review and ships.
|
|
1144
|
+
*
|
|
1145
|
+
* Requests run as `rebase_user`, so a policy is only reachable if it targets
|
|
1146
|
+
* `public` or a role whose privileges `rebase_user` has. Anything else is a
|
|
1147
|
+
* configuration error worth failing the boot for.
|
|
1148
|
+
*
|
|
1149
|
+
* Privileges, not membership: Postgres applies a policy `TO r` to a role that
|
|
1150
|
+
* has `r`'s privileges, which a member only gets by inheriting them, and
|
|
1151
|
+
* `rebase_user` is `NOINHERIT`. This used to ask `pg_has_role(…, 'MEMBER')`, so
|
|
1152
|
+
* `GRANT authenticated TO rebase_user` — the grant its own hint suggested —
|
|
1153
|
+
* passed here and still read every collection as empty.
|
|
1154
|
+
*/
|
|
1155
|
+
async function validatePolicyPgRoles(run, collections, requestRoles = REBASE_USER_ROLE$1) {
|
|
1156
|
+
const candidates = typeof requestRoles === "string" ? [requestRoles] : [...requestRoles];
|
|
1157
|
+
const requestRole = candidates[0] ?? REBASE_USER_ROLE$1;
|
|
1158
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
1159
|
+
for (const collection of collections) for (const rule of collection.securityRules ?? []) for (const role of rule.pgRoles ?? []) {
|
|
1160
|
+
if (role === "public" || candidates.includes(role)) continue;
|
|
1161
|
+
wanted.set(role, [...wanted.get(role) ?? [], collection.slug ?? "(unnamed)"]);
|
|
1162
|
+
}
|
|
1163
|
+
if (wanted.size === 0) return;
|
|
1164
|
+
const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, "''")}'`).join(",");
|
|
1165
|
+
const escapedRequestRole = requestRole.replace(/'/g, "''");
|
|
1166
|
+
const rows = await run(`
|
|
1167
|
+
SELECT r.rolname AS role,
|
|
1168
|
+
COALESCE(bool_or(pg_has_role(to_regrole(req.name), r.oid, 'USAGE')), false) AS reachable,
|
|
1169
|
+
COALESCE(bool_or(pg_has_role(to_regrole(req.name), r.oid, 'MEMBER')), false) AS member
|
|
1170
|
+
FROM pg_roles r CROSS JOIN unnest(${textArray(candidates)}) AS req(name)
|
|
1171
|
+
WHERE r.rolname IN (${names})
|
|
1172
|
+
GROUP BY r.rolname
|
|
1173
|
+
`);
|
|
1174
|
+
const [server] = await run(`
|
|
1175
|
+
SELECT current_setting('server_version_num')::int >= 160000 AS per_grant_inherit,
|
|
1176
|
+
(SELECT rolinherit FROM pg_roles WHERE oid = to_regrole('${escapedRequestRole}')) AS inherits
|
|
1177
|
+
`);
|
|
1178
|
+
const grantThatWorks = (role) => server?.per_grant_inherit === true ? `GRANT ${role} TO ${requestRole} WITH INHERIT TRUE` : server?.inherits === true ? `GRANT ${role} TO ${requestRole}` : void 0;
|
|
1179
|
+
const found = new Map(rows.map((row) => [String(row.role), row]));
|
|
1180
|
+
const problems = [];
|
|
1181
|
+
for (const [role, slugs] of wanted) {
|
|
1182
|
+
const row = found.get(role);
|
|
1183
|
+
if (row?.reachable === true) continue;
|
|
1184
|
+
const why = !row ? "no such role exists in this database" : row.member === true ? `"${requestRole}" is a member of it but does not inherit its privileges, so its policies do not apply` : `"${requestRole}" is not a member of it`;
|
|
1185
|
+
const platform = FOREIGN_CONVENTION_ROLES[role];
|
|
1186
|
+
const grant = grantThatWorks(role);
|
|
1187
|
+
const hint = platform && !row ? `"${role}" is a ${platform} convention, not a PostgreSQL role. Application roles belong in \`roles: ["${role === "service_role" ? "admin" : role}"]\`, which is checked inside the policy via rebase.roles().` : grant ? `Either grant it (${grant}) or drop \`pgRoles\` so the policy targets \`public\`.` : `"${requestRole}" is NOINHERIT, and before PostgreSQL 16 a NOINHERIT role takes on no other role's policies. Drop \`pgRoles\` so the policy targets \`public\`.`;
|
|
1188
|
+
problems.push(` • pgRoles: ["${role}"] on ${slugs.join(", ")} — ${why}.\n ${hint}`);
|
|
1189
|
+
}
|
|
1190
|
+
if (problems.length > 0) throw new Error(`Security rules target PostgreSQL roles this server cannot use. Requests run as "${requestRole}", so these policies would never apply and every row would be filtered out — the collections would look empty rather than error.\n\n` + problems.join("\n\n") + "\n");
|
|
1191
|
+
}
|
|
1192
|
+
//#endregion
|
|
1193
|
+
export { warnOnAnonymousGrants as C, validatePolicyPgRoles as S, warnOnRoleSchemaCollision as T, recordRequestRoles as _, assertRecordedRequestRoles as a, roleHoldsTableGrants as b, ensureAppRole as c, findExposedInternalTables as d, findOtherRoleMembers as f, readRecordedRequestRoles as g, proveRoleSwitch as h, assertAppRoleRestricted as i, ensureAppRoleGrants as l, internalTablesGrantedToUserRole as m, appRoleSetupInstructions as n, authContextStatement as o, findUngrantableTables as p, applyAuthContext as r, detectConnectionPosture as s, REBASE_USER_ROLE$1 as t, ensureConnectionInheritsAdminRole as u, revokeUserRoleSql as v, warnOnLegacyRlsFunctions as w, settleAdminSwitch as x, rls_enforcement_exports as y };
|
|
1194
|
+
|
|
1195
|
+
//# sourceMappingURL=rls-enforcement-CyUCPDH8.js.map
|