@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
|
@@ -1,534 +0,0 @@
|
|
|
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 { logger } from "@rebasepro/server";
|
|
5
|
-
import { sql } from "drizzle-orm";
|
|
6
|
-
import { ANONYMOUS_USER_ID, REBASE_SCHEMA, usesLegacyRlsFunctions } from "@rebasepro/types";
|
|
7
|
-
import { REBASE_INTERNAL_TABLES, REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, securityRuleToConditions } from "@rebasepro/common";
|
|
8
|
-
//#region src/security/rls-enforcement.ts
|
|
9
|
-
var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
|
|
10
|
-
REBASE_USER_ROLE: () => REBASE_USER_ROLE$1,
|
|
11
|
-
appRoleSetupInstructions: () => appRoleSetupInstructions,
|
|
12
|
-
applyAuthContext: () => applyAuthContext,
|
|
13
|
-
authContextStatement: () => authContextStatement,
|
|
14
|
-
detectConnectionPosture: () => detectConnectionPosture,
|
|
15
|
-
ensureAppRole: () => ensureAppRole,
|
|
16
|
-
ensureAppRoleGrants: () => ensureAppRoleGrants,
|
|
17
|
-
findExposedInternalTables: () => findExposedInternalTables,
|
|
18
|
-
internalTablesGrantedToUserRole: () => internalTablesGrantedToUserRole,
|
|
19
|
-
revokeUserRoleSql: () => revokeUserRoleSql,
|
|
20
|
-
validatePolicyPgRoles: () => validatePolicyPgRoles,
|
|
21
|
-
warnOnAnonymousGrants: () => warnOnAnonymousGrants,
|
|
22
|
-
warnOnLegacyRlsFunctions: () => warnOnLegacyRlsFunctions,
|
|
23
|
-
warnOnRoleSchemaCollision: () => warnOnRoleSchemaCollision
|
|
24
|
-
});
|
|
25
|
-
var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
26
|
-
/** DML the user role holds on managed tables (RLS still filters per row). */
|
|
27
|
-
var USER_TABLE_PRIVILEGES = "SELECT, INSERT, UPDATE, DELETE";
|
|
28
|
-
/**
|
|
29
|
-
* Take every privilege the user role holds on one table back — what a table
|
|
30
|
-
* gets when RLS cannot be switched on for it, so it is unreachable rather than
|
|
31
|
-
* unprotected. Quoted exactly: a mixed-case adopted table (`"User"`) folded to
|
|
32
|
-
* lower case names a table that does not exist.
|
|
33
|
-
*/
|
|
34
|
-
var revokeUserRoleSql = (schema, table) => `REVOKE ALL PRIVILEGES ON ${quoteIdent(schema)}.${quoteIdent(table)} FROM ${quoteIdent(REBASE_USER_ROLE$1)}`;
|
|
35
|
-
/**
|
|
36
|
-
* Warn when the connection role shares its name with an existing schema.
|
|
37
|
-
*
|
|
38
|
-
* Postgres resolves unqualified names through `search_path`, which defaults to
|
|
39
|
-
* `"$user", public` — and `$user` is the connection ROLE. When a schema of that
|
|
40
|
-
* name exists it sits ahead of `public`, so every unqualified statement
|
|
41
|
-
* silently operates on it instead:
|
|
42
|
-
*
|
|
43
|
-
* CREATE TABLE posts (...); -- you meant public.posts; you got <role>.posts
|
|
44
|
-
*
|
|
45
|
-
* Nothing errors. You get a second table of the same name in the wrong schema,
|
|
46
|
-
* and reads that pin `public` cannot see it — which reads as "missing table" and
|
|
47
|
-
* sends people to re-run a push that creates a *third* copy. The bootstrapper
|
|
48
|
-
* has a whole branch dedicated to recognising the symptom after the fact.
|
|
49
|
-
*
|
|
50
|
-
* Rebase shipped straight into this: it creates a schema named `rebase` while
|
|
51
|
-
* every template named the database role `rebase` too. The scaffold uses
|
|
52
|
-
* `rebase_app` now, and every pool Rebase opens pins `search_path=public`
|
|
53
|
-
* (`pinSearchPath`), which covers the paths the framework controls. This covers
|
|
54
|
-
* the ones it does not — `psql`, `pg_dump`, drizzle-kit, a colleague's script,
|
|
55
|
-
* a hand-written migration — because the hazard is a property of the two NAMES,
|
|
56
|
-
* not of any one connection.
|
|
57
|
-
*
|
|
58
|
-
* A warning rather than a boot failure: the database works, the framework's own
|
|
59
|
-
* traffic is pinned, and refusing to start over a naming choice a user may have
|
|
60
|
-
* inherited would be worse than the risk.
|
|
61
|
-
*/
|
|
62
|
-
async function warnOnRoleSchemaCollision(run) {
|
|
63
|
-
try {
|
|
64
|
-
const rows = await run(`
|
|
65
|
-
SELECT current_user AS role,
|
|
66
|
-
EXISTS (
|
|
67
|
-
SELECT 1 FROM pg_namespace n WHERE n.nspname = current_user
|
|
68
|
-
) AS collides
|
|
69
|
-
`);
|
|
70
|
-
if (rows[0]?.collides !== true) return;
|
|
71
|
-
const role = String(rows[0]?.role ?? "the connection role");
|
|
72
|
-
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".`);
|
|
73
|
-
} catch {}
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Would RLS actually constrain this connection?
|
|
77
|
-
*
|
|
78
|
-
* Four ways the answer is no, and only two of them are obvious. Superuser and
|
|
79
|
-
* BYPASSRLS announce themselves in `pg_roles`. The other two are about
|
|
80
|
-
* ownership, and both used to read as "no bypass here":
|
|
81
|
-
*
|
|
82
|
-
* - **Ownership through membership.** The old query compared
|
|
83
|
-
* `pg_tables.tableowner` to `current_user` as a string. Postgres does not: a
|
|
84
|
-
* role that INHERITs the owner passes every ownership test the planner makes,
|
|
85
|
-
* including the one that decides whether a policy applies. So a perfectly
|
|
86
|
-
* ordinary "app role that is a member of the owner role" setup reported
|
|
87
|
-
* unprivileged and bypassed every policy — permanently, since no restart
|
|
88
|
-
* changes a string comparison's answer.
|
|
89
|
-
*
|
|
90
|
-
* - **Ownership that has not happened yet.** The posture is decided once, at
|
|
91
|
-
* boot, and on a fresh database there is nothing in the catalogue to find. The
|
|
92
|
-
* same process then creates every table and owns all of them. The first boot
|
|
93
|
-
* of a new deployment therefore served every request unconstrained, the log
|
|
94
|
-
* said RLS was fine, and the SECOND boot silently fixed it — which is the
|
|
95
|
-
* worst possible shape for a security check, because the state that reproduces
|
|
96
|
-
* it is gone by the time anyone looks. Asking "may this role create tables
|
|
97
|
-
* where the server provisions?" answers about the process's whole life rather
|
|
98
|
-
* than about one instant of it.
|
|
99
|
-
*
|
|
100
|
-
* `schemas` narrows the CREATE question to where the server actually writes.
|
|
101
|
-
* Omitted, it asks about every schema the role can see, which is the safe
|
|
102
|
-
* direction: over-reporting costs a role switch that was not strictly needed,
|
|
103
|
-
* under-reporting costs the entire authorization model.
|
|
104
|
-
*/
|
|
105
|
-
async function detectConnectionPosture(run, schemas) {
|
|
106
|
-
const row = (await run(`
|
|
107
|
-
SELECT current_user AS role,
|
|
108
|
-
r.rolsuper AS superuser,
|
|
109
|
-
r.rolbypassrls AS bypassrls,
|
|
110
|
-
EXISTS (
|
|
111
|
-
SELECT 1 FROM pg_tables t
|
|
112
|
-
WHERE pg_has_role(current_user, t.tableowner, 'USAGE')
|
|
113
|
-
AND t.schemaname NOT IN ('pg_catalog', 'information_schema')
|
|
114
|
-
) AS owns_tables,
|
|
115
|
-
EXISTS (
|
|
116
|
-
SELECT 1 FROM pg_namespace n
|
|
117
|
-
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
118
|
-
AND n.nspname NOT LIKE 'pg\\_toast%'
|
|
119
|
-
AND n.nspname NOT LIKE 'pg\\_temp%'
|
|
120
|
-
${schemas?.length ? `AND n.nspname IN (${Array.from(new Set(schemas)).map((s) => `'${s.replace(/'/g, "''")}'`).join(", ")})` : ""}
|
|
121
|
-
AND has_schema_privilege(current_user, n.oid, 'CREATE')
|
|
122
|
-
) AS can_create
|
|
123
|
-
FROM pg_roles r
|
|
124
|
-
WHERE r.rolname = current_user
|
|
125
|
-
`))[0] ?? {};
|
|
126
|
-
const superuser = row.superuser === true;
|
|
127
|
-
const bypassRLS = row.bypassrls === true;
|
|
128
|
-
const ownsTables = row.owns_tables === true;
|
|
129
|
-
const canCreateTables = row.can_create === true;
|
|
130
|
-
return {
|
|
131
|
-
role: String(row.role ?? "unknown"),
|
|
132
|
-
superuser,
|
|
133
|
-
bypassRLS,
|
|
134
|
-
ownsTables,
|
|
135
|
-
canCreateTables,
|
|
136
|
-
privileged: superuser || bypassRLS || ownsTables || canCreateTables
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
/**
|
|
140
|
-
* Human-actionable instructions for when the connection cannot provision the
|
|
141
|
-
* user role itself (no CREATEROLE and role not pre-created by the platform).
|
|
142
|
-
*/
|
|
143
|
-
function appRoleSetupInstructions(connectionRole, schemas) {
|
|
144
|
-
const grants = schemas.map((s) => `GRANT USAGE ON SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE$1};\nGRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE$1};\nGRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${quoteIdent(s)} TO ${REBASE_USER_ROLE$1};`).join("\n");
|
|
145
|
-
return `Rebase enforces row-level security by running authenticated requests as the restricted role "${REBASE_USER_ROLE$1}", but the connection role "${connectionRole}" bypasses RLS and cannot create that role itself.\nRun the following as a database administrator, then restart:\n\nCREATE ROLE ${REBASE_USER_ROLE$1} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;\nGRANT ${REBASE_USER_ROLE$1} TO ${quoteIdent(connectionRole)};\n` + grants;
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* Idempotently provision the `rebase_user` role, membership for the current
|
|
149
|
-
* connection role, and DML grants (+ default privileges for future tables)
|
|
150
|
-
* on every existing schema in `schemas`.
|
|
151
|
-
*
|
|
152
|
-
* Split into privilege tiers so it works both when the connection is a
|
|
153
|
-
* superuser (creates everything) and when the platform pre-created the role
|
|
154
|
-
* and membership (e.g. CNPG `postInitApplicationSQL`) and the connection is
|
|
155
|
-
* merely the table owner — owners can always run the grant tier themselves.
|
|
156
|
-
*
|
|
157
|
-
* RLS still filters every row: these grants only make the tables *reachable*
|
|
158
|
-
* by the role; the policies decide which rows/commands actually pass.
|
|
159
|
-
*
|
|
160
|
-
* Throws with precise setup instructions when the role is missing and the
|
|
161
|
-
* connection cannot create it.
|
|
162
|
-
*/
|
|
163
|
-
async function ensureAppRole(run, schemas) {
|
|
164
|
-
const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
|
|
165
|
-
if ((await run(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE$1}'`)).length === 0) try {
|
|
166
|
-
await run(`
|
|
167
|
-
DO $rebase_role$
|
|
168
|
-
BEGIN
|
|
169
|
-
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE$1}') THEN
|
|
170
|
-
CREATE ROLE ${REBASE_USER_ROLE$1} NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT;
|
|
171
|
-
END IF;
|
|
172
|
-
END
|
|
173
|
-
$rebase_role$
|
|
174
|
-
`);
|
|
175
|
-
} catch (err) {
|
|
176
|
-
throw new Error(`Failed to create the "${REBASE_USER_ROLE$1}" role: ${err instanceof Error ? err.message : String(err)}\n\n` + appRoleSetupInstructions("current connection role", uniqueSchemas));
|
|
177
|
-
}
|
|
178
|
-
const memberRows = await run(`
|
|
179
|
-
SELECT (pg_has_role(current_user, '${REBASE_USER_ROLE$1}', 'MEMBER')
|
|
180
|
-
OR (SELECT rolsuper FROM pg_roles WHERE rolname = current_user)) AS can_set,
|
|
181
|
-
current_user AS role
|
|
182
|
-
`);
|
|
183
|
-
if (memberRows[0]?.can_set !== true) try {
|
|
184
|
-
await run(`GRANT ${REBASE_USER_ROLE$1} TO CURRENT_USER`);
|
|
185
|
-
} catch (err) {
|
|
186
|
-
throw new Error(`The connection role is not a member of "${REBASE_USER_ROLE$1}" and cannot grant itself membership: ${err instanceof Error ? err.message : String(err)}\n\n` + appRoleSetupInstructions(String(memberRows[0]?.role ?? "current connection role"), uniqueSchemas));
|
|
187
|
-
}
|
|
188
|
-
await ensureAppRoleGrants(run, uniqueSchemas);
|
|
189
|
-
logger.debug(`🔐 [rls] User role "${REBASE_USER_ROLE$1}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
|
|
190
|
-
}
|
|
191
|
-
/** A string literal for a catalogue read. Names come from config and constants, never from a request. */
|
|
192
|
-
var sqlLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
193
|
-
var textArray = (values) => values.length === 0 ? "ARRAY[]::text[]" : `ARRAY[${values.map(sqlLiteral).join(", ")}]::text[]`;
|
|
194
|
-
/**
|
|
195
|
-
* The framework's internal tables in `schemas` that the request role can
|
|
196
|
-
* reach — `schema.table`, sorted — when nothing is left to take it back off.
|
|
197
|
-
*
|
|
198
|
-
* Every provisioning boot repairs this: each store revokes on its own table
|
|
199
|
-
* and {@link ensureAppRole}'s sweep revokes on the rest, because the grant
|
|
200
|
-
* tier hands the request role DML on whole schemas. A backend that changes
|
|
201
|
-
* nothing in its database runs neither, so a database whose `rebase_user` can
|
|
202
|
-
* read `refresh_tokens` or `api_keys` would stay that way for as long as it
|
|
203
|
-
* served. This is the question the sweep would have answered, asked instead.
|
|
204
|
-
*
|
|
205
|
-
* "Can reach" is what the role can actually do — through a grant to it, to a
|
|
206
|
-
* role it inherits, or to PUBLIC, on the table or on any of its columns —
|
|
207
|
-
* because that, not how the ACL is spelled, is what a request running as it
|
|
208
|
-
* gets. A table with RLS on is somebody's collection by that same rule as the
|
|
209
|
-
* sweep's, and is left out.
|
|
210
|
-
*/
|
|
211
|
-
async function findExposedInternalTables(run, schemas) {
|
|
212
|
-
return (await run(`
|
|
213
|
-
SELECT n.nspname || '.' || c.relname AS name
|
|
214
|
-
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
215
|
-
WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})
|
|
216
|
-
AND c.relname = ANY(${textArray(REBASE_INTERNAL_TABLES)})
|
|
217
|
-
AND c.relkind IN ('r', 'p')
|
|
218
|
-
AND NOT c.relrowsecurity
|
|
219
|
-
AND (has_table_privilege(${sqlLiteral(REBASE_USER_ROLE$1)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')
|
|
220
|
-
OR has_any_column_privilege(${sqlLiteral(REBASE_USER_ROLE$1)}, c.oid, 'SELECT, INSERT, UPDATE'))
|
|
221
|
-
ORDER BY 1
|
|
222
|
-
`)).map((row) => String(row.name));
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* The grant tier's state for every existing schema in `schemas`, in one read.
|
|
226
|
-
*
|
|
227
|
-
* A grant counts as present only as the statement this tier runs would record
|
|
228
|
-
* it — grantor the object's owner, which is what a GRANT by the owner, a member
|
|
229
|
-
* of the owning role or a superuser records — so skipping it leaves the ACL
|
|
230
|
-
* exactly as running it would. Anything else reads as missing, and the
|
|
231
|
-
* statement runs as it always did.
|
|
232
|
-
*/
|
|
233
|
-
async function readSchemaGrants(run, schemas) {
|
|
234
|
-
const internal = textArray(REBASE_INTERNAL_TABLES);
|
|
235
|
-
const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(REBASE_USER_ROLE$1)})`;
|
|
236
|
-
/** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */
|
|
237
|
-
const held = (acl, privileges, grantor) => `(SELECT count(DISTINCT a.privilege_type) FROM aclexplode(${acl}) a WHERE a.grantee = ${target}${grantor ? ` AND a.grantor = ${grantor}` : ""} AND a.privilege_type IN (${privileges.map(sqlLiteral).join(", ")}))`;
|
|
238
|
-
const DML = [
|
|
239
|
-
"SELECT",
|
|
240
|
-
"INSERT",
|
|
241
|
-
"UPDATE",
|
|
242
|
-
"DELETE"
|
|
243
|
-
];
|
|
244
|
-
const SEQ = ["USAGE", "SELECT"];
|
|
245
|
-
const rows = await run(`
|
|
246
|
-
SELECT n.nspname AS schema,
|
|
247
|
-
${held("n.nspacl", ["USAGE"], "n.nspowner")} = 1 AS usage,
|
|
248
|
-
NOT EXISTS (
|
|
249
|
-
SELECT 1 FROM pg_class c
|
|
250
|
-
WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
|
|
251
|
-
AND NOT (c.relname = ANY(${internal}) AND NOT c.relrowsecurity)
|
|
252
|
-
AND ${held("c.relacl", DML, "c.relowner")} < ${DML.length}
|
|
253
|
-
) AS tables,
|
|
254
|
-
NOT EXISTS (
|
|
255
|
-
SELECT 1 FROM pg_class c
|
|
256
|
-
WHERE c.relnamespace = n.oid AND c.relkind = 'S'
|
|
257
|
-
AND ${held("c.relacl", SEQ, "c.relowner")} < ${SEQ.length}
|
|
258
|
-
) AS sequences,
|
|
259
|
-
EXISTS (
|
|
260
|
-
SELECT 1 FROM pg_default_acl d
|
|
261
|
-
WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
|
|
262
|
-
AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'r'
|
|
263
|
-
AND ${held("d.defaclacl", DML)} = ${DML.length}
|
|
264
|
-
) AS default_tables,
|
|
265
|
-
EXISTS (
|
|
266
|
-
SELECT 1 FROM pg_default_acl d
|
|
267
|
-
WHERE d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
|
|
268
|
-
AND d.defaclnamespace = n.oid AND d.defaclobjtype = 'S'
|
|
269
|
-
AND ${held("d.defaclacl", SEQ)} = ${SEQ.length}
|
|
270
|
-
) AS default_sequences,
|
|
271
|
-
ARRAY(
|
|
272
|
-
SELECT c.relname::text FROM pg_class c
|
|
273
|
-
WHERE c.relnamespace = n.oid AND c.relname = ANY(${internal}) AND NOT c.relrowsecurity
|
|
274
|
-
AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))
|
|
275
|
-
ORDER BY 1
|
|
276
|
-
) AS internal_granted
|
|
277
|
-
FROM pg_namespace n
|
|
278
|
-
WHERE n.nspname = ANY(${textArray(schemas)})
|
|
279
|
-
`);
|
|
280
|
-
const grants = /* @__PURE__ */ new Map();
|
|
281
|
-
for (const row of rows) {
|
|
282
|
-
const internalGranted = row.internal_granted;
|
|
283
|
-
grants.set(String(row.schema), {
|
|
284
|
-
usage: row.usage === true,
|
|
285
|
-
tables: row.tables === true,
|
|
286
|
-
sequences: row.sequences === true,
|
|
287
|
-
defaultTables: row.default_tables === true,
|
|
288
|
-
defaultSequences: row.default_sequences === true,
|
|
289
|
-
internalGranted: Array.isArray(internalGranted) ? internalGranted.map(String) : String(internalGranted ?? "").replace(/^\{|\}$/g, "").split(",").filter(Boolean)
|
|
290
|
-
});
|
|
291
|
-
}
|
|
292
|
-
return grants;
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
|
|
296
|
-
* schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
|
|
297
|
-
* sequences, the default privileges that cover what this role creates later,
|
|
298
|
-
* and Rebase's own tables taken back — for a role and membership already
|
|
299
|
-
* provisioned.
|
|
300
|
-
*
|
|
301
|
-
* Every statement is issued only when the catalogue says it would change
|
|
302
|
-
* something. They used to run unconditionally, twice per boot (at connect, and
|
|
303
|
-
* again in the final posture check): a `GRANT … ON ALL TABLES` rewrites every
|
|
304
|
-
* table's `pg_class` row whether or not the ACL changes, which invalidates
|
|
305
|
-
* every table's cached plans on every connection, and the internal-table sweep
|
|
306
|
-
* ran 23 `REVOKE`s per schema. A boot against a database whose grants already
|
|
307
|
-
* hold now reads one catalogue query and writes nothing; one that is missing
|
|
308
|
-
* any of them runs exactly the statements it always ran.
|
|
309
|
-
*
|
|
310
|
-
* Table owners (the expected non-superuser posture) can always grant on their
|
|
311
|
-
* own objects, so this needs no extra privilege.
|
|
312
|
-
*/
|
|
313
|
-
async function ensureAppRoleGrants(run, schemas) {
|
|
314
|
-
const uniqueSchemas = Array.from(new Set(schemas.filter(Boolean)));
|
|
315
|
-
const grants = await readSchemaGrants(run, uniqueSchemas);
|
|
316
|
-
for (const schema of uniqueSchemas) {
|
|
317
|
-
const state = grants.get(schema);
|
|
318
|
-
if (!state) continue;
|
|
319
|
-
const s = quoteIdent(schema);
|
|
320
|
-
if (!state.usage) await run(`GRANT USAGE ON SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
|
|
321
|
-
if (!state.tables) await run(`GRANT ${USER_TABLE_PRIVILEGES} ON ALL TABLES IN SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
|
|
322
|
-
if (!state.sequences) await run(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${s} TO ${REBASE_USER_ROLE$1}`);
|
|
323
|
-
if (!state.defaultTables) await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT ${USER_TABLE_PRIVILEGES} ON TABLES TO ${REBASE_USER_ROLE$1}`);
|
|
324
|
-
if (!state.defaultSequences) await run(`ALTER DEFAULT PRIVILEGES IN SCHEMA ${s} GRANT USAGE, SELECT ON SEQUENCES TO ${REBASE_USER_ROLE$1}`);
|
|
325
|
-
const tables = state.tables ? state.internalGranted : void 0;
|
|
326
|
-
if (tables && tables.length === 0) continue;
|
|
327
|
-
await revokeInternalTableAccess(async (text) => {
|
|
328
|
-
await run(text);
|
|
329
|
-
}, schema, {
|
|
330
|
-
tables,
|
|
331
|
-
onError: (table, error) => logger.warn(`🔐 [rls] Could not revoke "${REBASE_USER_ROLE$1}" access to "${schema}"."${table}" — it stays reachable by authenticated requests: ` + (error instanceof Error ? error.message : String(error)))
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
/**
|
|
336
|
-
* Rebase's own RLS-off tables in `schema` that a `revokeInternalTableAccess`
|
|
337
|
-
* sweep would change — the user role holds a privilege on them, or their ACL
|
|
338
|
-
* has never been written. One read; the sweep it narrows is one `DO` per
|
|
339
|
-
* table name.
|
|
340
|
-
*/
|
|
341
|
-
async function internalTablesGrantedToUserRole(run, schema) {
|
|
342
|
-
return (await readSchemaGrants(run, [schema])).get(schema)?.internalGranted ?? [];
|
|
343
|
-
}
|
|
344
|
-
/**
|
|
345
|
-
* Apply the authenticated context to a transaction: the `app.*` GUCs that RLS
|
|
346
|
-
* policies read via `rebase.uid()` / `rebase.roles()` / `rebase.jwt()`, and — when
|
|
347
|
-
* `userRole` is set — the `LOCAL` role switch, in the same statement, so RLS
|
|
348
|
-
* binds every statement in this transaction (reads *and* writes).
|
|
349
|
-
*
|
|
350
|
-
* GUCs are set with `is_local = true` and the role switch is `LOCAL`: both
|
|
351
|
-
* reset at commit/rollback, so pooled connections are never polluted.
|
|
352
|
-
*
|
|
353
|
-
* Fails closed by construction: if the role switch errors, the transaction
|
|
354
|
-
* aborts instead of proceeding privileged.
|
|
355
|
-
*
|
|
356
|
-
* SECURITY: this function is only ever called on the **user** path (the server
|
|
357
|
-
* context uses the base/owner driver and never calls it). The default policies
|
|
358
|
-
* treat `rebase.uid() IS NULL` as the trusted server context, and `rebase.uid()`
|
|
359
|
-
* is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
|
|
360
|
-
* be read as NULL and silently escalate a user request to server privileges.
|
|
361
|
-
* Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
|
|
362
|
-
* rather than trusting every caller (e.g. realtime subscription auth) to do it.
|
|
363
|
-
* That sentinel is exported from `@rebasepro/types` because it leaks into rule
|
|
364
|
-
* semantics: it is why `rebase.uid() IS NOT NULL` is true for anonymous requests.
|
|
365
|
-
*/
|
|
366
|
-
async function applyAuthContext(tx, auth, userRole) {
|
|
367
|
-
const settings = authContextSettings(auth, userRole);
|
|
368
|
-
await tx.execute(sql`SELECT ${sql.join(settings.map(([name, value]) => sql`${sql.raw(`set_config(${settingNameLiteral(name)}, `)}${value}, true)`), sql`, `)}`);
|
|
369
|
-
}
|
|
370
|
-
/**
|
|
371
|
-
* {@link applyAuthContext} as one statement and its values, for a transaction
|
|
372
|
-
* that sends it in the same batch as its first query
|
|
373
|
-
* (`pipelined-transaction.ts`). `before` are settings of the transaction's own
|
|
374
|
-
* — what a pooled connection could not carry at connect — set ahead of the
|
|
375
|
-
* caller's, in the same statement.
|
|
376
|
-
*/
|
|
377
|
-
function authContextStatement(auth, userRole, before = []) {
|
|
378
|
-
const settings = [...before, ...authContextSettings(auth, userRole)];
|
|
379
|
-
return {
|
|
380
|
-
text: `SELECT ${settings.map(([name], i) => `set_config(${settingNameLiteral(name)}, $${i + 1}, true)`).join(", ")}`,
|
|
381
|
-
values: settings.map(([, value]) => value)
|
|
382
|
-
};
|
|
383
|
-
}
|
|
384
|
-
/**
|
|
385
|
-
* A setting's name as a SQL literal. Names are this module's constants (and
|
|
386
|
-
* the pooled settings' two), never a caller's value, which is a bound
|
|
387
|
-
* parameter; written into the text so a statement log reads as the settings
|
|
388
|
-
* it sets.
|
|
389
|
-
*/
|
|
390
|
-
function settingNameLiteral(name) {
|
|
391
|
-
return `'${name.replace(/'/g, "''")}'`;
|
|
392
|
-
}
|
|
393
|
-
/**
|
|
394
|
-
* The transaction-local settings that make a transaction the caller's, in the
|
|
395
|
-
* order they are set: the `app.*` GUCs, then the role.
|
|
396
|
-
*/
|
|
397
|
-
function authContextSettings(auth, userRole) {
|
|
398
|
-
const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
|
|
399
|
-
const normalizedRoles = auth.roles.map((r) => typeof r === "string" ? r : r?.id ?? String(r));
|
|
400
|
-
const isAnonymous = auth.isAnonymous === true ? "true" : "false";
|
|
401
|
-
const settings = [
|
|
402
|
-
["app.uid", uid],
|
|
403
|
-
["app.user_id", uid],
|
|
404
|
-
["app.user_roles", normalizedRoles.join(",")],
|
|
405
|
-
["app.is_anonymous", isAnonymous],
|
|
406
|
-
["app.jwt", JSON.stringify({
|
|
407
|
-
...auth.claims ?? {},
|
|
408
|
-
sub: uid,
|
|
409
|
-
roles: auth.roles,
|
|
410
|
-
is_anonymous: auth.isAnonymous === true
|
|
411
|
-
})]
|
|
412
|
-
];
|
|
413
|
-
if (userRole) settings.push(["role", userRole]);
|
|
414
|
-
return settings;
|
|
415
|
-
}
|
|
416
|
-
/** Role names from other BaaS platforms that people reach for out of habit. */
|
|
417
|
-
var FOREIGN_CONVENTION_ROLES = {
|
|
418
|
-
authenticated: "Supabase",
|
|
419
|
-
anon: "Supabase",
|
|
420
|
-
service_role: "Supabase"
|
|
421
|
-
};
|
|
422
|
-
/**
|
|
423
|
-
* Warn about rules that read as "signed-in users only" but admit anonymous
|
|
424
|
-
* callers — `rebase.uid() IS NOT NULL`, or a comparison against another
|
|
425
|
-
* platform's magic user id such as `'anon'`.
|
|
426
|
-
*
|
|
427
|
-
* The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
|
|
428
|
-
* of the same habit. A foreign `pgRoles` value makes a policy unreachable and
|
|
429
|
-
* the table reads empty — loud, and that guard throws. These do the opposite:
|
|
430
|
-
* the rule compiles to a grant, and nothing looks wrong until the data is
|
|
431
|
-
* already public.
|
|
432
|
-
*
|
|
433
|
-
* Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
|
|
434
|
-
* serving traffic today: refusing to boot would take an app offline to report a
|
|
435
|
-
* problem it already has, and on the read path it would take it offline
|
|
436
|
-
* *because* its data was exposed. Rewriting the author's SQL is not an option
|
|
437
|
-
* either — this is the escape hatch whose whole promise is that it means what it
|
|
438
|
-
* says. So: say so, loudly, and leave the rule alone.
|
|
439
|
-
*/
|
|
440
|
-
function warnOnAnonymousGrants(collections) {
|
|
441
|
-
const byRisk = /* @__PURE__ */ new Map();
|
|
442
|
-
for (const collection of collections) for (const rule of collection.securityRules ?? []) {
|
|
443
|
-
const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
|
|
444
|
-
const risks = [usingExpr, withCheckExpr].filter((e) => e !== null).flatMap(findAnonymousGrants);
|
|
445
|
-
for (const risk of risks) {
|
|
446
|
-
const key = `${risk.pattern}:${risk.detail}`;
|
|
447
|
-
const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
|
|
448
|
-
const entry = byRisk.get(key) ?? {
|
|
449
|
-
risk,
|
|
450
|
-
sites: []
|
|
451
|
-
};
|
|
452
|
-
if (!entry.sites.includes(site)) entry.sites.push(site);
|
|
453
|
-
byRisk.set(key, entry);
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
if (byRisk.size === 0) return;
|
|
457
|
-
const problems = [...byRisk.values()].map(({ risk, sites }) => ` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`);
|
|
458
|
-
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");
|
|
459
|
-
}
|
|
460
|
-
/**
|
|
461
|
-
* Name the collections whose raw policy SQL still calls the pre-1.0 helpers.
|
|
462
|
-
*
|
|
463
|
-
* The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the
|
|
464
|
-
* database, so nothing is broken and no policy is wrong — which is exactly why
|
|
465
|
-
* this has to be said out loud. A silent rewrite that works forever is not a
|
|
466
|
-
* migration, it is a second supported spelling nobody wrote down, and the next
|
|
467
|
-
* person to read those rules will copy the old one.
|
|
468
|
-
*
|
|
469
|
-
* Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,
|
|
470
|
-
* `policy.rolesOverlap(...)`) compile from the model and were never affected.
|
|
471
|
-
*/
|
|
472
|
-
function warnOnLegacyRlsFunctions(collections) {
|
|
473
|
-
const sites = [];
|
|
474
|
-
for (const collection of collections) for (const rule of collection.securityRules ?? []) {
|
|
475
|
-
const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
|
|
476
|
-
if (![usingExpr, withCheckExpr].filter((e) => e !== null).some(containsLegacyRlsCall)) continue;
|
|
477
|
-
const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
|
|
478
|
-
if (!sites.includes(site)) sites.push(site);
|
|
479
|
-
}
|
|
480
|
-
if (sites.length === 0) return;
|
|
481
|
-
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");
|
|
482
|
-
}
|
|
483
|
-
/** Whether any `raw` expression in the tree calls a pre-1.0 helper. */
|
|
484
|
-
function containsLegacyRlsCall(expr) {
|
|
485
|
-
switch (expr.kind) {
|
|
486
|
-
case "raw": return usesLegacyRlsFunctions(expr.sql);
|
|
487
|
-
case "and":
|
|
488
|
-
case "or": return expr.operands.some(containsLegacyRlsCall);
|
|
489
|
-
case "not": return containsLegacyRlsCall(expr.operand);
|
|
490
|
-
case "existsIn": return containsLegacyRlsCall(expr.where);
|
|
491
|
-
default: return false;
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
/**
|
|
495
|
-
* Reject `pgRoles` that this server can never satisfy.
|
|
496
|
-
*
|
|
497
|
-
* `pgRoles` sets the `TO` clause of a generated policy, so a policy naming a
|
|
498
|
-
* role the request never runs as simply never applies — and RLS then filters
|
|
499
|
-
* every row. The table reads as empty, which is indistinguishable from having
|
|
500
|
-
* no data, so the mistake survives review and ships.
|
|
501
|
-
*
|
|
502
|
-
* Requests run as `rebase_user`, so a policy is only reachable if it targets
|
|
503
|
-
* `public` or a role `rebase_user` holds. Anything else is a configuration
|
|
504
|
-
* error worth failing the boot for.
|
|
505
|
-
*/
|
|
506
|
-
async function validatePolicyPgRoles(run, collections, requestRole = REBASE_USER_ROLE$1) {
|
|
507
|
-
const wanted = /* @__PURE__ */ new Map();
|
|
508
|
-
for (const collection of collections) for (const rule of collection.securityRules ?? []) for (const role of rule.pgRoles ?? []) {
|
|
509
|
-
if (role === "public") continue;
|
|
510
|
-
wanted.set(role, [...wanted.get(role) ?? [], collection.slug ?? "(unnamed)"]);
|
|
511
|
-
}
|
|
512
|
-
if (wanted.size === 0) return;
|
|
513
|
-
const names = [...wanted.keys()].map((r) => `'${r.replace(/'/g, "''")}'`).join(",");
|
|
514
|
-
const rows = await run(`
|
|
515
|
-
SELECT r.rolname AS role,
|
|
516
|
-
COALESCE(pg_has_role(to_regrole('${requestRole.replace(/'/g, "''")}'), r.oid, 'MEMBER'), false) AS reachable
|
|
517
|
-
FROM pg_roles r
|
|
518
|
-
WHERE r.rolname IN (${names})
|
|
519
|
-
`);
|
|
520
|
-
const reachable = new Map(rows.map((row) => [String(row.role), row.reachable === true]));
|
|
521
|
-
const problems = [];
|
|
522
|
-
for (const [role, slugs] of wanted) {
|
|
523
|
-
if (reachable.get(role) === true) continue;
|
|
524
|
-
const why = reachable.has(role) ? `"${requestRole}" is not a member of it` : "no such role exists in this database";
|
|
525
|
-
const platform = FOREIGN_CONVENTION_ROLES[role];
|
|
526
|
-
const hint = platform ? `"${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().` : `Either grant it (GRANT ${role} TO ${requestRole}) or drop \`pgRoles\` so the policy targets \`public\`.`;
|
|
527
|
-
problems.push(` • pgRoles: ["${role}"] on ${slugs.join(", ")} — ${why}.\n ${hint}`);
|
|
528
|
-
}
|
|
529
|
-
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");
|
|
530
|
-
}
|
|
531
|
-
//#endregion
|
|
532
|
-
export { ensureAppRole as a, internalTablesGrantedToUserRole as c, validatePolicyPgRoles as d, warnOnAnonymousGrants as f, detectConnectionPosture as i, revokeUserRoleSql as l, warnOnRoleSchemaCollision as m, applyAuthContext as n, ensureAppRoleGrants as o, warnOnLegacyRlsFunctions as p, authContextStatement as r, findExposedInternalTables as s, REBASE_USER_ROLE$1 as t, rls_enforcement_exports as u };
|
|
533
|
-
|
|
534
|
-
//# sourceMappingURL=rls-enforcement-jZTv1yci.js.map
|