@rebasepro/server-postgres 0.29.1 → 0.29.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchService-BIIBF5ZL.js → BranchService-CrXvcES2.js} +3 -3
- package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-CrXvcES2.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +64 -4
- package/dist/PostgresBootstrapper.d.ts +27 -0
- package/dist/auth/ensure-tables.d.ts +2 -2
- package/dist/auth/schema-version.d.ts +5 -5
- package/dist/auth/services.d.ts +9 -9
- package/dist/{backup-cli-QcOpmRpQ.js → backup-cli-CTKCOLpX.js} +3 -3
- package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CTKCOLpX.js.map} +1 -1
- package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CqGIwSYx.js} +2 -2
- package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CqGIwSYx.js.map} +1 -1
- package/dist/{cli-console-DTsm96lW.js → cli-console-DBPw-oAz.js} +6 -6
- package/dist/{cli-console-DTsm96lW.js.map → cli-console-DBPw-oAz.js.map} +1 -1
- package/dist/{cli-errors-DwqFRIWz.js → cli-errors-DYTxnLbW.js} +5 -5
- package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-DYTxnLbW.js.map} +1 -1
- package/dist/cli.js +185 -49
- package/dist/cli.js.map +1 -1
- package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
- package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
- package/dist/data-transformer.d.ts +2 -2
- package/dist/database-health.d.ts +2 -1
- package/dist/{database-preflight-D5JtPt8i.js → database-preflight-iBpT7-vv.js} +36 -3
- package/dist/database-preflight-iBpT7-vv.js.map +1 -0
- package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
- package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
- package/dist/{deferred-index-build-B8feKnUj.js → deferred-index-build-BCU9RoHK.js} +18 -6
- package/dist/deferred-index-build-BCU9RoHK.js.map +1 -0
- package/dist/{doctor-BaR11xUe.js → doctor-Kg1oUK0Q.js} +11 -11
- package/dist/doctor-Kg1oUK0Q.js.map +1 -0
- package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-Bo-_fDAy.js} +25 -15
- package/dist/ensure-collection-policies-Bo-_fDAy.js.map +1 -0
- package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-DCJINkT_.js} +11 -8
- package/dist/ensure-collection-tables-DCJINkT_.js.map +1 -0
- package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-BPGaGh0y.js} +4 -4
- package/dist/ensure-tables-BPGaGh0y.js.map +1 -0
- package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-YAgOZS4I.js} +3 -3
- package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-YAgOZS4I.js.map} +1 -1
- package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-DcrFr7YX.js} +2 -2
- package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-DcrFr7YX.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-LTLZvt6r.js} +3 -3
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-LTLZvt6r.js.map} +1 -1
- package/dist/{generate-files-Bl3_D_oP.js → generate-files-CsaVzatS.js} +3 -3
- package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-CsaVzatS.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-Dg0bcENZ.js} +45 -7
- package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +1 -0
- package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-By4dxyTH.js} +8 -5
- package/dist/generated-schema-diff-By4dxyTH.js.map +1 -0
- package/dist/history/HistoryService.d.ts +2 -3
- package/dist/history/ensure-history-table.d.ts +8 -3
- package/dist/index.es.js +15 -15
- package/dist/interfaces.d.ts +24 -2
- package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
- package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
- package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CmWXL7qx.js} +163 -502
- package/dist/migrate-baseline-CmWXL7qx.js.map +1 -0
- package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-BN_Qad6c.js} +42 -13
- package/dist/migrate-policy-stamps-BN_Qad6c.js.map +1 -0
- package/dist/{open-rebase-CiO_sjMT.js → open-rebase-40paQfVW.js} +1401 -655
- package/dist/open-rebase-40paQfVW.js.map +1 -0
- package/dist/open-rebase.d.ts +1 -1
- package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-DJHjCF7-.js} +2 -2
- package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-DJHjCF7-.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +24 -37
- package/dist/{plan-schema-BYxOzflz.js → plan-schema-vJd3UEmT.js} +41 -11
- package/dist/plan-schema-vJd3UEmT.js.map +1 -0
- package/dist/{policy-drift-DKuTJHfc.js → policy-drift-C-m0uWHH.js} +78 -10
- package/dist/policy-drift-C-m0uWHH.js.map +1 -0
- package/dist/push-index-adoption-Cp7oZxSl.js +22 -0
- package/dist/push-index-adoption-Cp7oZxSl.js.map +1 -0
- package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-DbwKGtQT.js} +4 -4
- package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-DbwKGtQT.js.map} +1 -1
- package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-CLcgsEPt.js} +2 -2
- package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-CLcgsEPt.js.map} +1 -1
- package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-BthD0E9W.js} +4 -4
- package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-BthD0E9W.js.map} +1 -1
- package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BgcrroxQ.js} +14 -8
- package/dist/push-policy-plan-BgcrroxQ.js.map +1 -0
- package/dist/read-routing.d.ts +10 -30
- package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Ci3S_SoI.js} +34 -3
- package/dist/render-ddl-Ci3S_SoI.js.map +1 -0
- package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Dy1EgJU9.js} +10 -10
- package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Dy1EgJU9.js.map} +1 -1
- package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-GHTJnPMV.js} +2 -2
- package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-GHTJnPMV.js.map} +1 -1
- package/dist/rls-bootstrap-sql-kPX4-MB1.js +549 -0
- package/dist/rls-bootstrap-sql-kPX4-MB1.js.map +1 -0
- package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-Cc_UhOxb.js} +316 -10
- package/dist/rls-enforcement-Cc_UhOxb.js.map +1 -0
- package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
- package/dist/rls-settings-BCGMIig3.js.map +1 -0
- package/dist/schema/doctor-cli.js +9 -9
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/drizzle-ddl.d.ts +2 -2
- package/dist/schema/ensure-collection-policies.d.ts +23 -3
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +14 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/index-adoption.d.ts +99 -0
- package/dist/schema/introspect-db-logic.d.ts +2 -1
- package/dist/schema/introspect-db.js +3 -3
- package/dist/schema/migrate-policy-stamps.d.ts +19 -1
- package/dist/schema/plan/diff-plan.d.ts +8 -1
- package/dist/schema/plan/render-ddl.d.ts +7 -0
- package/dist/schema/plan/types.d.ts +15 -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 +19 -2
- package/dist/schema/search-column.d.ts +2 -2
- package/dist/search-column-BM-GV6vH.js.map +1 -1
- package/dist/security/policy-drift.d.ts +31 -1
- package/dist/security/rls-enforcement.d.ts +118 -1
- package/dist/security/rls-settings.d.ts +33 -0
- package/dist/services/FetchService.d.ts +33 -8
- package/dist/services/PersistService.d.ts +75 -4
- package/dist/services/RelationService.d.ts +1 -1
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
- package/dist/services/channel-bus/index.d.ts +2 -2
- package/dist/services/channel-history.d.ts +2 -2
- package/dist/services/channel-presence.d.ts +3 -3
- package/dist/services/dataService.d.ts +6 -2
- package/dist/services/realtimeService.d.ts +18 -5
- package/dist/services/socket-liveness.d.ts +6 -1
- package/dist/types.d.ts +1 -1
- package/dist/utils/drizzle-conditions.d.ts +12 -0
- package/dist/utils/positional-params.d.ts +40 -0
- package/dist/{websocket-B33YjKhs.js → websocket-B7ex6AQM.js} +3 -3
- package/dist/websocket-B7ex6AQM.js.map +1 -0
- package/dist/websocket.d.ts +14 -3
- package/package.json +7 -7
- package/dist/database-preflight-D5JtPt8i.js.map +0 -1
- package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
- package/dist/doctor-BaR11xUe.js.map +0 -1
- package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
- package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
- package/dist/generate-postgres-ddl-logic-BC3JA93M.js.map +0 -1
- package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
- package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
- package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
- package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
- package/dist/open-rebase-CiO_sjMT.js.map +0 -1
- package/dist/plan-schema-BYxOzflz.js.map +0 -1
- package/dist/policy-drift-DKuTJHfc.js.map +0 -1
- package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
- package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
- package/dist/rls-enforcement-BO618rnr.js.map +0 -1
- package/dist/rls-settings-De5NoHHy.js.map +0 -1
- package/dist/websocket-B33YjKhs.js.map +0 -1
|
@@ -2,24 +2,31 @@ import { createRequire as __createRequire } from "module";
|
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
|
|
4
4
|
import { n as VIEW_ROWS_COMMENT_PREFIX } from "./view-names-Dscp6--B.js";
|
|
5
|
-
import { ot as extractCauseMessage } from "./cli-errors-
|
|
5
|
+
import { ot as extractCauseMessage } from "./cli-errors-DYTxnLbW.js";
|
|
6
|
+
import { t as cliRlsSettings } from "./rls-settings-BCGMIig3.js";
|
|
7
|
+
import { n as ADMIN_REQUEST_ROLE_SQL, t as ADMIN_POLICY_ROLE_SQL } from "./rls-bootstrap-sql-kPX4-MB1.js";
|
|
6
8
|
import { logger } from "@rebasepro/server";
|
|
7
9
|
import { sql } from "drizzle-orm";
|
|
8
|
-
import { ANONYMOUS_USER_ID, REBASE_SCHEMA, usesLegacyRlsFunctions } from "@rebasepro/types";
|
|
9
|
-
import { LOAD_REQUEST_ROLES_PLPGSQL, REBASE_INTERNAL_TABLES, REBASE_USER_ROLE as REBASE_USER_ROLE$1, findAnonymousGrants, revokeInternalTableAccess, revokeInternalTableSql, securityRuleToConditions } from "@rebasepro/common";
|
|
10
|
+
import { ANONYMOUS_USER_ID, REBASE_ADMIN_REQUEST_ROLE, 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";
|
|
10
12
|
//#region src/security/rls-enforcement.ts
|
|
11
13
|
var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
|
|
12
14
|
AppRoleSetupError: () => AppRoleSetupError,
|
|
13
15
|
REBASE_USER_ROLE: () => REBASE_USER_ROLE$1,
|
|
14
16
|
REQUEST_ROLES_KEY: () => REQUEST_ROLES_KEY,
|
|
17
|
+
adminPoliciesLiveForCli: () => adminPoliciesLiveForCli,
|
|
18
|
+
adminRequestCompanionsSafeForCli: () => adminRequestCompanionsSafeForCli,
|
|
19
|
+
adminSwitchLive: () => adminSwitchLive,
|
|
15
20
|
appRoleSetupInstructions: () => appRoleSetupInstructions,
|
|
16
21
|
applyAuthContext: () => applyAuthContext,
|
|
17
22
|
assertAppRoleRestricted: () => assertAppRoleRestricted,
|
|
18
23
|
assertRecordedRequestRoles: () => assertRecordedRequestRoles,
|
|
19
24
|
authContextStatement: () => authContextStatement,
|
|
20
25
|
detectConnectionPosture: () => detectConnectionPosture,
|
|
26
|
+
ensureAdminRequestRole: () => ensureAdminRequestRole,
|
|
21
27
|
ensureAppRole: () => ensureAppRole,
|
|
22
28
|
ensureAppRoleGrants: () => ensureAppRoleGrants,
|
|
29
|
+
ensureConnectionInheritsAdminRole: () => ensureConnectionInheritsAdminRole,
|
|
23
30
|
ensureInheritedRoles: () => ensureInheritedRoles,
|
|
24
31
|
findExposedInternalTables: () => findExposedInternalTables,
|
|
25
32
|
findOtherRoleMembers: () => findOtherRoleMembers,
|
|
@@ -30,6 +37,9 @@ var rls_enforcement_exports = /* @__PURE__ */ __exportAll({
|
|
|
30
37
|
recordRequestRoles: () => recordRequestRoles,
|
|
31
38
|
revokeUserRoleSql: () => revokeUserRoleSql,
|
|
32
39
|
roleHoldsTableGrants: () => roleHoldsTableGrants,
|
|
40
|
+
settleAdminRequestGroup: () => settleAdminRequestGroup,
|
|
41
|
+
settleAdminRequestRoles: () => settleAdminRequestRoles,
|
|
42
|
+
settleAdminSwitch: () => settleAdminSwitch,
|
|
33
43
|
validatePolicyPgRoles: () => validatePolicyPgRoles,
|
|
34
44
|
warnOnAnonymousGrants: () => warnOnAnonymousGrants,
|
|
35
45
|
warnOnLegacyRlsFunctions: () => warnOnLegacyRlsFunctions,
|
|
@@ -510,6 +520,11 @@ async function ensureAppRole(run, schemas, options = {}) {
|
|
|
510
520
|
logger.debug(`🔐 [rls] User role "${role}" provisioned (schemas: ${uniqueSchemas.join(", ")})`);
|
|
511
521
|
}
|
|
512
522
|
/**
|
|
523
|
+
* SQL: whether `c` (in namespace `n`) is a table the request roles are kept
|
|
524
|
+
* off when RLS is off on it — see `withheldTablesIn`.
|
|
525
|
+
*/
|
|
526
|
+
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)}))`;
|
|
527
|
+
/**
|
|
513
528
|
* The framework's internal tables in `schemas` that the request role can
|
|
514
529
|
* reach — `schema.table`, sorted — when nothing is left to take it back off.
|
|
515
530
|
*
|
|
@@ -531,7 +546,7 @@ async function findExposedInternalTables(run, schemas, role = REBASE_USER_ROLE$1
|
|
|
531
546
|
SELECT n.nspname || '.' || c.relname AS name
|
|
532
547
|
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
533
548
|
WHERE n.nspname = ANY(${textArray(Array.from(new Set(schemas)))})
|
|
534
|
-
AND
|
|
549
|
+
AND ${isWithheldTable("c", "n")}
|
|
535
550
|
AND c.relkind IN ('r', 'p')
|
|
536
551
|
AND NOT c.relrowsecurity
|
|
537
552
|
AND (has_table_privilege(${sqlLiteral(role)}, c.oid, 'SELECT, INSERT, UPDATE, DELETE')
|
|
@@ -600,7 +615,6 @@ async function readSchemaGrants(run, schemas, role = REBASE_USER_ROLE$1, managed
|
|
|
600
615
|
const onlyManagedSequences = managed ? `AND EXISTS (SELECT 1 FROM pg_depend d JOIN pg_class t ON t.oid = d.refobjid
|
|
601
616
|
WHERE d.objid = c.oid AND d.deptype IN ('a', 'i')
|
|
602
617
|
AND (n.nspname, t.relname::text) IN ${managed})` : "";
|
|
603
|
-
const internal = textArray(REBASE_INTERNAL_TABLES);
|
|
604
618
|
const target = `(SELECT oid FROM pg_roles WHERE rolname = ${sqlLiteral(role)})`;
|
|
605
619
|
/** Distinct privileges `acl` gives the user role (from `grantor`, when given) out of `privileges`. */
|
|
606
620
|
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(", ")}))`;
|
|
@@ -622,7 +636,7 @@ async function readSchemaGrants(run, schemas, role = REBASE_USER_ROLE$1, managed
|
|
|
622
636
|
ARRAY(
|
|
623
637
|
SELECT c.relname::text FROM pg_class c
|
|
624
638
|
WHERE c.relnamespace = n.oid AND c.relkind IN ('r', 'v', 'm', 'f', 'p')
|
|
625
|
-
AND NOT (c
|
|
639
|
+
AND NOT (${isWithheldTable("c", "n")} AND NOT c.relrowsecurity)
|
|
626
640
|
AND ${mayGrant("table", "c.oid", "c.relowner", DML)}
|
|
627
641
|
${onlyManagedTables}
|
|
628
642
|
AND NOT ${viewRows("c")}
|
|
@@ -651,7 +665,7 @@ async function readSchemaGrants(run, schemas, role = REBASE_USER_ROLE$1, managed
|
|
|
651
665
|
) AS default_sequences,
|
|
652
666
|
ARRAY(
|
|
653
667
|
SELECT c.relname::text FROM pg_class c
|
|
654
|
-
WHERE c.relnamespace = n.oid AND c
|
|
668
|
+
WHERE c.relnamespace = n.oid AND ${isWithheldTable("c", "n")} AND NOT c.relrowsecurity
|
|
655
669
|
AND (c.relacl IS NULL OR EXISTS (SELECT 1 FROM aclexplode(c.relacl) a WHERE a.grantee = ${target}))
|
|
656
670
|
ORDER BY 1
|
|
657
671
|
) AS internal_granted,
|
|
@@ -714,6 +728,297 @@ async function ensureInheritedRoles(run, role, inheritRoles) {
|
|
|
714
728
|
}
|
|
715
729
|
}
|
|
716
730
|
/**
|
|
731
|
+
* Provision the role admin requests run as for one request role:
|
|
732
|
+
* `<role>_admin`, inheriting `role` — its grants, and every policy written
|
|
733
|
+
* for it — and {@link REBASE_ADMIN_ROLE}, with the connection able to switch
|
|
734
|
+
* to it. The role itself goes through {@link ensureAppRole} (created NOLOGIN
|
|
735
|
+
* NOSUPERUSER NOBYPASSRLS, checked as restricted when found, the switch
|
|
736
|
+
* proved), with no grants of its own: everything it can reach, it reaches as
|
|
737
|
+
* `role` does.
|
|
738
|
+
*
|
|
739
|
+
* Inheriting is per grant from PostgreSQL 16 (`WITH INHERIT TRUE`); before
|
|
740
|
+
* that it is the role's own `INHERIT` attribute, harmless here because this
|
|
741
|
+
* role belongs to exactly the two roles granted below.
|
|
742
|
+
*/
|
|
743
|
+
async function ensureAdminRequestRole(run, schemas, options) {
|
|
744
|
+
const { role, adminRole } = options;
|
|
745
|
+
const provision = options.provisionRole !== "never";
|
|
746
|
+
const [present] = await run(`SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_ADMIN_ROLE}') AS present`);
|
|
747
|
+
if (present?.present !== true) {
|
|
748
|
+
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;`);
|
|
749
|
+
await run(ADMIN_POLICY_ROLE_SQL);
|
|
750
|
+
}
|
|
751
|
+
await ensureAppRole(run, schemas, {
|
|
752
|
+
role: adminRole,
|
|
753
|
+
provisionRole: options.provisionRole,
|
|
754
|
+
grants: "none"
|
|
755
|
+
});
|
|
756
|
+
const [state] = await run(`
|
|
757
|
+
SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
758
|
+
r.rolinherit AS inherits_all,
|
|
759
|
+
pg_has_role(r.oid, to_regrole(${sqlLiteral(role)}), 'USAGE') AS has_request_role,
|
|
760
|
+
pg_has_role(r.oid, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE') AS has_admin_role
|
|
761
|
+
FROM pg_roles r WHERE r.rolname = ${sqlLiteral(adminRole)}
|
|
762
|
+
`);
|
|
763
|
+
const perGrant = state?.per_grant === true;
|
|
764
|
+
const missing = [...state?.has_request_role === true ? [] : [role], ...state?.has_admin_role === true ? [] : [REBASE_ADMIN_ROLE]];
|
|
765
|
+
if (missing.length === 0) return;
|
|
766
|
+
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}`)];
|
|
767
|
+
const instructions = `Run as a database administrator, then restart:\n\n${statements.map((st) => `${st};`).join("\n")}`;
|
|
768
|
+
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);
|
|
769
|
+
try {
|
|
770
|
+
for (const statement of statements) await run(statement);
|
|
771
|
+
} catch (err) {
|
|
772
|
+
throw new AppRoleSetupError(`Could not let the admin request role "${adminRole}" inherit ${missing.map((m) => `"${m}"`).join(" and ")}: ${failureReason(err)}`, instructions);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Let the connection role itself pass the server-or-admin policies, by
|
|
777
|
+
* inheriting {@link REBASE_ADMIN_ROLE} — which is what `TO public` gave it.
|
|
778
|
+
*
|
|
779
|
+
* It matters where the connection is subject to RLS: always, when it owns
|
|
780
|
+
* none of the tables (requests then run as the connection itself, so the
|
|
781
|
+
* server context and admins depend on it), and on any table it does not own
|
|
782
|
+
* otherwise. Best effort: a connection that cannot be granted the role is
|
|
783
|
+
* told what to run, and its server-context and admin reads of those tables are
|
|
784
|
+
* refused — closed, never wider — until someone does.
|
|
785
|
+
*/
|
|
786
|
+
async function ensureConnectionInheritsAdminRole(run, options) {
|
|
787
|
+
const [state] = await run(`
|
|
788
|
+
SELECT current_user AS role,
|
|
789
|
+
(SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user) AS exempt,
|
|
790
|
+
current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
791
|
+
to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present,
|
|
792
|
+
COALESCE(pg_has_role(current_user, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS inherits
|
|
793
|
+
`);
|
|
794
|
+
if (state?.exempt === true || state?.inherits === true) return;
|
|
795
|
+
const connection = String(state?.role ?? "");
|
|
796
|
+
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)}`;
|
|
797
|
+
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".`);
|
|
798
|
+
if (!options.provision) {
|
|
799
|
+
warn("this driver was opened without provisioning", state?.present === true);
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
let roleExists = state?.present === true;
|
|
803
|
+
try {
|
|
804
|
+
if (!roleExists) await run(ADMIN_POLICY_ROLE_SQL);
|
|
805
|
+
roleExists = true;
|
|
806
|
+
await run(grant);
|
|
807
|
+
} catch (err) {
|
|
808
|
+
warn(failureReason(err), roleExists);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* The request identity a boot hands the driver and the realtime refetch, with
|
|
813
|
+
* the admin switch on when every admin request role is ready: provisioned
|
|
814
|
+
* here, or — on a boot that provisions nothing — found existing, inheriting
|
|
815
|
+
* what it should and switchable. Otherwise admin requests run as the request
|
|
816
|
+
* role, as before, and the boot says why: under `adminPolicies: "adminRole"`,
|
|
817
|
+
* policies already written `TO rebase_admin` then refuse them.
|
|
818
|
+
*/
|
|
819
|
+
async function settleAdminRequestRoles(run, schemas, settings, options) {
|
|
820
|
+
if (settings.adminRoles.size === 0) return settings.request;
|
|
821
|
+
const failures = [];
|
|
822
|
+
for (const [role, adminRole] of settings.adminRoles) try {
|
|
823
|
+
await ensureAdminRequestRole(run, schemas, {
|
|
824
|
+
role,
|
|
825
|
+
adminRole,
|
|
826
|
+
provisionRole: options.provision ? settings.provisionRole : "never"
|
|
827
|
+
});
|
|
828
|
+
} catch (err) {
|
|
829
|
+
failures.push(`"${adminRole}": ${err instanceof Error ? err.message : String(err)}`);
|
|
830
|
+
}
|
|
831
|
+
if (failures.length > 0) {
|
|
832
|
+
const [marker] = await run(`SELECT to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present`);
|
|
833
|
+
(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.`);
|
|
834
|
+
return settings.request;
|
|
835
|
+
}
|
|
836
|
+
const adminRoles = settings.adminRoles;
|
|
837
|
+
return {
|
|
838
|
+
...settings.request,
|
|
839
|
+
adminRoleFor: (role) => adminRoles.get(role)
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Whether policies written `TO rebase_admin` reach every caller they are for on
|
|
844
|
+
* this connection, read from the catalogue without changing anything: the role
|
|
845
|
+
* exists, the connection passes it (exempt from RLS, or inheriting it — the
|
|
846
|
+
* server context on tables it does not own), and each of `adminRoles` exists,
|
|
847
|
+
* inherits its request role and `rebase_admin`, and the connection can switch
|
|
848
|
+
* into it. The state {@link settleAdminRequestRoles} and
|
|
849
|
+
* {@link ensureConnectionInheritsAdminRole} leave when both succeed.
|
|
850
|
+
*
|
|
851
|
+
* With `existingOnly`, an admin role that does not exist is passed over, but at
|
|
852
|
+
* least one must be ready: for a role list read back from the database, which
|
|
853
|
+
* does not say which role is an anonymous one with no admin counterpart.
|
|
854
|
+
*
|
|
855
|
+
* Anything it cannot read answers `false`, and `false` means `TO public`: the
|
|
856
|
+
* shape every caller passes, as before the admin role existed.
|
|
857
|
+
*/
|
|
858
|
+
async function adminSwitchLive(run, adminRoles, options = {}) {
|
|
859
|
+
if (adminRoles.size === 0) return false;
|
|
860
|
+
const [connection] = await run(`
|
|
861
|
+
SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
862
|
+
to_regrole('${REBASE_ADMIN_ROLE}') IS NOT NULL AS present,
|
|
863
|
+
COALESCE((SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user), false)
|
|
864
|
+
OR COALESCE(pg_has_role(current_user, to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false) AS passes
|
|
865
|
+
`);
|
|
866
|
+
if (connection?.present !== true || connection?.passes !== true) return false;
|
|
867
|
+
const privilege = connection.per_grant === true ? "SET" : "MEMBER";
|
|
868
|
+
let ready = 0;
|
|
869
|
+
for (const [role, adminRole] of adminRoles) {
|
|
870
|
+
const [state] = await run(`
|
|
871
|
+
SELECT to_regrole(${sqlLiteral(adminRole)}) IS NOT NULL AS present,
|
|
872
|
+
COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole(${sqlLiteral(role)}), 'USAGE'), false)
|
|
873
|
+
AND COALESCE(pg_has_role(to_regrole(${sqlLiteral(adminRole)}), to_regrole('${REBASE_ADMIN_ROLE}'), 'USAGE'), false)
|
|
874
|
+
AND COALESCE(pg_has_role(current_user, to_regrole(${sqlLiteral(adminRole)}), '${privilege}'), false) AS ready
|
|
875
|
+
`);
|
|
876
|
+
if (options.existingOnly && state?.present !== true) continue;
|
|
877
|
+
if (state?.ready !== true) return false;
|
|
878
|
+
ready++;
|
|
879
|
+
}
|
|
880
|
+
return ready > 0;
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* The admin switch for a boot whose requests switch roles: settle the admin
|
|
884
|
+
* request roles and the connection's `rebase_admin`, then say whether the
|
|
885
|
+
* switch is live — which is what decides where the policies step writes the
|
|
886
|
+
* server-or-admin policies. `TO rebase_admin` only when it is: written there
|
|
887
|
+
* while admin requests still run as the request role, they refuse every admin
|
|
888
|
+
* caller, `dataAsAdmin` included, as an empty table. Otherwise `TO public`, the
|
|
889
|
+
* documented fallback, which the request role passes.
|
|
890
|
+
*/
|
|
891
|
+
async function settleAdminSwitch(run, schemas, settings, options) {
|
|
892
|
+
const request = await settleAdminRequestRoles(run, schemas, settings, options);
|
|
893
|
+
if (settings.adminPolicies !== "adminRole") return {
|
|
894
|
+
request,
|
|
895
|
+
adminPoliciesLive: false,
|
|
896
|
+
adminRequestPoliciesLive: false
|
|
897
|
+
};
|
|
898
|
+
await ensureConnectionInheritsAdminRole(run, options);
|
|
899
|
+
const adminPoliciesLive = request.adminRoleFor !== void 0 && await adminSwitchLive(run, settings.adminRoles);
|
|
900
|
+
return {
|
|
901
|
+
request,
|
|
902
|
+
adminPoliciesLive,
|
|
903
|
+
adminRequestPoliciesLive: adminPoliciesLive && await settleAdminRequestGroup(run, [...settings.adminRoles.values()], options).catch((err) => {
|
|
904
|
+
logger.warn(`⚠️ RLS enforcement: admin reads keep their policy barrier (${failureReason(err)}).`);
|
|
905
|
+
return false;
|
|
906
|
+
})
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Make {@link REBASE_ADMIN_REQUEST_ROLE} the admin request roles' alone, and
|
|
911
|
+
* say whether it is — which decides whether the admin-only policies get their
|
|
912
|
+
* `USING (true)` companions, and with them an admin request's index plans.
|
|
913
|
+
*
|
|
914
|
+
* The companions admit every member of that role to every row the admin
|
|
915
|
+
* policies grant, so membership is the whole boundary, and it is checked, not
|
|
916
|
+
* assumed. From PostgreSQL 16 each admin request role is granted it `WITH
|
|
917
|
+
* INHERIT TRUE, SET FALSE`; the connection holds those roles `WITH INHERIT
|
|
918
|
+
* FALSE` and so not this one. Before 16 inheritance is a property of the role,
|
|
919
|
+
* the connection would inherit it through them, and nothing is granted. Then
|
|
920
|
+
* the catalogue is asked who holds its privileges: anyone but the admin
|
|
921
|
+
* request roles — the connection by `createrole_self_grant`, a request role, a
|
|
922
|
+
* grant by hand — and the answer is `false`, the companions are not planned,
|
|
923
|
+
* and the policies step drops any it finds. A role that bypasses RLS anyway
|
|
924
|
+
* (a superuser, BYPASSRLS) gains nothing from them and does not count.
|
|
925
|
+
*
|
|
926
|
+
* A boot that provisions nothing creates and grants nothing, and only reads.
|
|
927
|
+
*/
|
|
928
|
+
async function settleAdminRequestGroup(run, adminRoles, options) {
|
|
929
|
+
if (adminRoles.length === 0) return false;
|
|
930
|
+
const group = REBASE_ADMIN_REQUEST_ROLE;
|
|
931
|
+
const [state] = await run(`
|
|
932
|
+
SELECT current_setting('server_version_num')::int >= ${SET_OPTION_SINCE} AS per_grant,
|
|
933
|
+
to_regrole('${group}') IS NOT NULL AS present
|
|
934
|
+
`);
|
|
935
|
+
if (state?.per_grant !== true) return false;
|
|
936
|
+
if (state.present !== true) {
|
|
937
|
+
if (!options.provision) return false;
|
|
938
|
+
try {
|
|
939
|
+
await run(ADMIN_REQUEST_ROLE_SQL);
|
|
940
|
+
} catch (err) {
|
|
941
|
+
logger.info(`🔐 RLS enforcement: "${group}" could not be created (${failureReason(err)}); admin reads keep their policy barrier.`);
|
|
942
|
+
return false;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
if (options.provision) for (const adminRole of adminRoles) {
|
|
946
|
+
const [held] = await run(`SELECT pg_has_role(${sqlLiteral(adminRole)}, '${group}', 'USAGE') AS inherits`);
|
|
947
|
+
if (held?.inherits !== true) await run(`GRANT ${group} TO ${quoteIdent(adminRole)} WITH INHERIT TRUE, SET FALSE`);
|
|
948
|
+
}
|
|
949
|
+
const { others, adminsHold } = await adminRequestGroupHolders(run, adminRoles);
|
|
950
|
+
if (others.length > 0) {
|
|
951
|
+
logger.warn(`⚠️ RLS enforcement: ${others.map((r) => `"${r}"`).join(", ")} ${others.length === 1 ? "holds" : "hold"} the privileges of "${group}", which only the admin request roles may: its policies admit every row the admin policies grant. They are not written, so admin reads keep their policy barrier. Revoke it (REVOKE ${group} FROM …, or REVOKE INHERIT OPTION FOR ${group} FROM …).`);
|
|
952
|
+
return false;
|
|
953
|
+
}
|
|
954
|
+
return adminsHold;
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Who holds the privileges of {@link REBASE_ADMIN_REQUEST_ROLE}: `others`, the
|
|
958
|
+
* roles that may not (anything subject to RLS but the admin request roles),
|
|
959
|
+
* and whether every admin request role does. Read-only — the check
|
|
960
|
+
* {@link settleAdminRequestGroup} makes after granting, and the one `db push`
|
|
961
|
+
* and `rebase doctor` make before trusting a companion they find.
|
|
962
|
+
*/
|
|
963
|
+
async function adminRequestGroupHolders(run, adminRoles) {
|
|
964
|
+
const group = REBASE_ADMIN_REQUEST_ROLE;
|
|
965
|
+
const [present] = await run(`SELECT to_regrole('${group}') IS NOT NULL AS present`);
|
|
966
|
+
if (present?.present !== true) return {
|
|
967
|
+
others: [],
|
|
968
|
+
adminsHold: false
|
|
969
|
+
};
|
|
970
|
+
const [check] = await run(`
|
|
971
|
+
SELECT ARRAY(
|
|
972
|
+
SELECT r.rolname::text FROM pg_roles r
|
|
973
|
+
WHERE pg_has_role(r.oid, '${group}'::regrole, 'USAGE')
|
|
974
|
+
AND r.rolname <> '${group}'
|
|
975
|
+
AND NOT r.rolsuper AND NOT r.rolbypassrls
|
|
976
|
+
AND r.rolname <> ALL(${textArray(adminRoles)})
|
|
977
|
+
ORDER BY 1
|
|
978
|
+
) AS others,
|
|
979
|
+
(SELECT bool_and(pg_has_role(r.oid, '${group}'::regrole, 'USAGE')) FROM pg_roles r
|
|
980
|
+
WHERE r.rolname = ANY(${textArray(adminRoles)})) AS admins
|
|
981
|
+
`);
|
|
982
|
+
return {
|
|
983
|
+
others: textArrayValue(check?.others),
|
|
984
|
+
adminsHold: check?.admins === true
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
/**
|
|
988
|
+
* Whether a companion found in the database may stay: the admin switch would
|
|
989
|
+
* be live for this database's request roles, and nothing but their admin
|
|
990
|
+
* roles holds {@link REBASE_ADMIN_REQUEST_ROLE}. `db push` and `rebase doctor`
|
|
991
|
+
* ask this before taking a live companion for Rebase's own — otherwise it is
|
|
992
|
+
* an orphan, and push drops it. Anything it cannot read answers `false`.
|
|
993
|
+
*/
|
|
994
|
+
async function adminRequestCompanionsSafeForCli(run) {
|
|
995
|
+
try {
|
|
996
|
+
const settings = cliRlsSettings(await readRecordedRequestRoles(run));
|
|
997
|
+
if (settings.adminPolicies !== "adminRole" || settings.adminRoles.size === 0) return false;
|
|
998
|
+
const { others } = await adminRequestGroupHolders(run, [...settings.adminRoles.values()]);
|
|
999
|
+
return others.length === 0;
|
|
1000
|
+
} catch {
|
|
1001
|
+
return false;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Where `db push` and `rebase doctor` expect the server-or-admin policies, for
|
|
1006
|
+
* the request roles this database records (or the configured ones): `TO
|
|
1007
|
+
* rebase_admin` only when {@link adminSwitchLive} says a server on this
|
|
1008
|
+
* connection would have the switch live, `TO public` otherwise — the same
|
|
1009
|
+
* answer a boot reaches, without provisioning anything. Settings that do not
|
|
1010
|
+
* resolve answer `false`.
|
|
1011
|
+
*/
|
|
1012
|
+
async function adminPoliciesLiveForCli(run) {
|
|
1013
|
+
try {
|
|
1014
|
+
const settings = cliRlsSettings(await readRecordedRequestRoles(run));
|
|
1015
|
+
if (settings.adminPolicies !== "adminRole") return false;
|
|
1016
|
+
return await adminSwitchLive(run, settings.adminRoles, { existingOnly: true });
|
|
1017
|
+
} catch {
|
|
1018
|
+
return false;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
717
1022
|
* The grant tier of {@link ensureAppRole} on its own: `USAGE` on each existing
|
|
718
1023
|
* schema in `schemas`, DML on its tables and `USAGE, SELECT` on its
|
|
719
1024
|
* sequences, the default privileges that cover what this role creates later,
|
|
@@ -850,7 +1155,8 @@ function authContextSettings(auth, userRole) {
|
|
|
850
1155
|
];
|
|
851
1156
|
const role = typeof userRole === "object" ? userRole.roleFor(auth) : userRole;
|
|
852
1157
|
if (typeof userRole === "object" && role) for (const [name, value] of userRole.settingsFor(auth, role)) settings.push([name, value]);
|
|
853
|
-
|
|
1158
|
+
const admin = role && typeof userRole === "object" && holdsAdminRole(normalizedRoles.map(String)) ? userRole.adminRoleFor?.(role) : void 0;
|
|
1159
|
+
if (role) settings.push(["role", admin ?? role]);
|
|
854
1160
|
return settings;
|
|
855
1161
|
}
|
|
856
1162
|
/** Role names from other BaaS platforms that people reach for out of habit. */
|
|
@@ -987,6 +1293,6 @@ async function validatePolicyPgRoles(run, collections, requestRoles = REBASE_USE
|
|
|
987
1293
|
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");
|
|
988
1294
|
}
|
|
989
1295
|
//#endregion
|
|
990
|
-
export {
|
|
1296
|
+
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 };
|
|
991
1297
|
|
|
992
|
-
//# sourceMappingURL=rls-enforcement-
|
|
1298
|
+
//# sourceMappingURL=rls-enforcement-Cc_UhOxb.js.map
|