@rebasepro/server-postgres 0.29.0 → 0.29.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchService-JiYJ_n9E.js → BranchService-BIIBF5ZL.js} +3 -3
- package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +27 -9
- package/dist/PostgresBootstrapper.d.ts +14 -0
- package/dist/{backup-cli-D_aKXPyX.js → backup-cli-QcOpmRpQ.js} +3 -3
- package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
- package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-BSNpEUOS.js} +2 -2
- package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
- package/dist/{cli-console-DPdZCWTi.js → cli-console-DTsm96lW.js} +5 -5
- package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DTsm96lW.js.map} +1 -1
- package/dist/{cli-errors-D8s4z_3g.js → cli-errors-DwqFRIWz.js} +49 -6
- package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-DwqFRIWz.js.map} +1 -1
- package/dist/cli.js +81 -41
- package/dist/cli.js.map +1 -1
- package/dist/database-preflight-D5JtPt8i.js +151 -0
- package/dist/database-preflight-D5JtPt8i.js.map +1 -0
- package/dist/db-subcommands.d.ts +1 -1
- package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-B8feKnUj.js} +12 -8
- package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
- package/dist/{doctor-_g2tHRtG.js → doctor-BaR11xUe.js} +6 -6
- package/dist/{doctor-_g2tHRtG.js.map → doctor-BaR11xUe.js.map} +1 -1
- package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-85HiG-k1.js} +8 -8
- package/dist/{ensure-collection-policies-DUpWJb5D.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
- package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-DR_WcxLA.js} +15 -10
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
- package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-Dh5UP_Zs.js} +4 -4
- package/dist/{ensure-tables-Bx1DYarz.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
- package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-DSU8lAnd.js} +3 -3
- package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
- package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
- package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
- package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
- package/dist/{generate-files-DbwU8Btx.js → generate-files-Bl3_D_oP.js} +3 -3
- package/dist/{generate-files-DbwU8Btx.js.map → generate-files-Bl3_D_oP.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-BC3JA93M.js} +3 -3
- package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
- package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-Jm93vyJB.js} +12 -4
- package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.es.js +20 -12
- package/dist/index.es.js.map +1 -1
- package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-BfHmq3vN.js} +49 -4
- package/dist/{migrate-baseline-BeepEphh.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
- package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-B4k1ggma.js} +6 -6
- package/dist/{migrate-policy-stamps-cYMJ_9Ha.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
- package/dist/{open-rebase-CTNBmmH8.js → open-rebase-CiO_sjMT.js} +465 -80
- package/dist/open-rebase-CiO_sjMT.js.map +1 -0
- package/dist/open-rebase.d.ts +6 -1
- package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-D1Nc0UML.js} +2 -2
- package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
- package/dist/{plan-schema-CMNWvqIa.js → plan-schema-BYxOzflz.js} +89 -9
- package/dist/plan-schema-BYxOzflz.js.map +1 -0
- package/dist/{policy-drift-IjD2AUD-.js → policy-drift-DKuTJHfc.js} +2 -2
- package/dist/{policy-drift-IjD2AUD-.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
- package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-bqXimSZz.js} +4 -4
- package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
- package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-CN9R8cHf.js} +2 -2
- package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
- package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-CU_UYPbz.js} +4 -4
- package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
- package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-JcyK94bc.js} +4 -4
- package/dist/{push-policy-plan--oRXOj4X.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
- package/dist/{render-ddl-CzVcbbR1.js → render-ddl-DCdVP-pQ.js} +27 -10
- package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
- package/dist/request-role-cli-DSdRtvgH.js +260 -0
- package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
- package/dist/request-role-cli.d.ts +86 -0
- package/dist/request-role-migration-D9BZ5Uba.js +150 -0
- package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
- package/dist/rls-enforcement-BO618rnr.js +992 -0
- package/dist/rls-enforcement-BO618rnr.js.map +1 -0
- package/dist/rls-settings-De5NoHHy.js +211 -0
- package/dist/rls-settings-De5NoHHy.js.map +1 -0
- package/dist/schema/doctor-cli.js +144 -6
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/doctor-database.d.ts +27 -0
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/introspect-db.js +1 -1
- package/dist/schema/plan/diff-plan.d.ts +6 -1
- package/dist/schema/plan/render-ddl.d.ts +10 -3
- package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
- package/dist/schema/plan/types.d.ts +15 -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/rls-bootstrap-sql.d.ts +23 -0
- 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/request-role-migration.d.ts +36 -0
- package/dist/security/rls-enforcement.d.ts +191 -21
- package/dist/security/rls-settings.d.ts +177 -0
- package/dist/services/dataService.d.ts +2 -0
- package/dist/services/realtimeService.d.ts +3 -0
- package/dist/services/view-access.d.ts +2 -2
- 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-B33YjKhs.js} +3 -3
- package/dist/{websocket-D2y88dOa.js.map → websocket-B33YjKhs.js.map} +1 -1
- package/package.json +7 -7
- package/dist/deferred-index-build-F2GWu009.js.map +0 -1
- package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
- package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
- package/dist/open-rebase-CTNBmmH8.js.map +0 -1
- package/dist/plan-schema-CMNWvqIa.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
|
@@ -2,29 +2,31 @@ import { createRequire as __createRequire } from "module";
|
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, h as transactionSettingsStatements, l as isPooledPool, m as transactionSettingsConfig, n as closeWithPool, p as searchPathList } from "./connection-COuS5Fm-.js";
|
|
4
4
|
import { _ as visibleColumnProjection, a as buildSearchColumnSpec, r as SEARCH_UNACCENT_FN, s as hiddenColumnsOption } from "./search-column-BM-GV6vH.js";
|
|
5
|
-
import {
|
|
6
|
-
import { a as
|
|
7
|
-
import { t as
|
|
8
|
-
import {
|
|
5
|
+
import { r as viewRowsName, t as DEFAULT_VIEW_ROLES } from "./view-names-Dscp6--B.js";
|
|
6
|
+
import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, ot as extractCauseMessage, r as deepestErrorMessage, u as parseHostInfo } from "./cli-errors-DwqFRIWz.js";
|
|
7
|
+
import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-D1Nc0UML.js";
|
|
8
|
+
import { t as BranchService } from "./BranchService-BIIBF5ZL.js";
|
|
9
|
+
import { C as warnOnRoleSchemaCollision, S as warnOnLegacyRlsFunctions, _ as revokeUserRoleSql, a as assertRecordedRequestRoles, b as validatePolicyPgRoles, c as ensureAppRole, d as findOtherRoleMembers, f as findUngrantableTables, g as recordRequestRoles, h as readRecordedRequestRoles, i as assertAppRoleRestricted, l as ensureAppRoleGrants, m as proveRoleSwitch, o as authContextStatement, r as applyAuthContext, s as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as findExposedInternalTables, x as warnOnAnonymousGrants, y as roleHoldsTableGrants } from "./rls-enforcement-BO618rnr.js";
|
|
9
10
|
import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
|
|
10
11
|
import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
|
|
11
|
-
import { n as planSchema } from "./plan-schema-
|
|
12
|
-
import { t as generateSchema } from "./generate-drizzle-schema-logic-
|
|
13
|
-
import { i as renderPgType } from "./render-ddl-
|
|
14
|
-
import {
|
|
15
|
-
import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-
|
|
16
|
-
import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-
|
|
12
|
+
import { n as planSchema } from "./plan-schema-BYxOzflz.js";
|
|
13
|
+
import { t as generateSchema } from "./generate-drizzle-schema-logic-C5FB7Fpo.js";
|
|
14
|
+
import { i as renderPgType } from "./render-ddl-DCdVP-pQ.js";
|
|
15
|
+
import { d as typesAgree, s as diffPlanAgainstCatalogue } from "./deferred-index-build-B8feKnUj.js";
|
|
16
|
+
import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-BSNpEUOS.js";
|
|
17
|
+
import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-DR_WcxLA.js";
|
|
17
18
|
import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
|
|
18
19
|
import { t as DatabasePoolManager } from "./databasePoolManager-7hXVurmG.js";
|
|
19
|
-
import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-
|
|
20
|
-
import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-
|
|
20
|
+
import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-Dh5UP_Zs.js";
|
|
21
|
+
import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-Jm93vyJB.js";
|
|
22
|
+
import { i as rlsHandoverNotes, n as resolveRlsSettings, r as rlsConfigFromEnv } from "./rls-settings-De5NoHHy.js";
|
|
21
23
|
import pg, { Client, DatabaseError, Pool } from "pg";
|
|
22
24
|
import { NodePgDatabase, NodePgSession, NodePgTransaction, drizzle } from "drizzle-orm/node-postgres";
|
|
23
25
|
import { ApiError, assertQueryFieldsReadable, createDdlBootstrapper, createEmailService, logger, rawQueryLoggingEnabled, resolveBatchRefs, rowETag, splitFieldOps } from "@rebasepro/server";
|
|
24
26
|
import { and, asc, count, desc, eq, getTableColumns, getTableName, gt, ilike, inArray, is, isNotNull, isNull, isTable, lt, lte, not, notInArray, or, relations, sql } from "drizzle-orm";
|
|
25
27
|
import { PgArray, PgDialect, PgNumeric, PgTable, PgTimestamp, PgTimestampString, PgTransaction, bigint, boolean, getTableConfig, index, integer, jsonb, pgSchema, pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
|
|
26
|
-
import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isPostgresCollectionConfig, isRelationalCollectionConfig, isSQLAdmin, joinConditions, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf, roleNameProblem, soleJoinCondition } from "@rebasepro/types";
|
|
27
|
-
import { COMPOSITE_ID_SEPARATOR, COMPOSITE_ID_SEPARATOR as COMPOSITE_ID_SEPARATOR$1, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, OrderBySpecError,
|
|
28
|
+
import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, declaredDatabaseRls, declaredRlsPolicyShape, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isPostgresCollectionConfig, isRelationalCollectionConfig, isSQLAdmin, joinConditions, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf, roleNameProblem, soleJoinCondition } from "@rebasepro/types";
|
|
29
|
+
import { COMPOSITE_ID_SEPARATOR, COMPOSITE_ID_SEPARATOR as COMPOSITE_ID_SEPARATOR$1, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, OrderBySpecError, UnknownFilterOperatorError, apiHiddenFieldNames, applyDefaultValuesOnCreate, buildCompositeId, buildCompositeId as buildCompositeId$1, buildPropertyCallbacks, buildSdkData, callbackRefusal, canReadField, classifyTable, createAccessorSlugResolver, createRelationRef, createRelationRefWithData, deserializeFilter, detectJunctionTables, effectiveAccess, encodeCursor, fieldKeyForColumn, findRelation, firstSqlRow, getColumnName, getDeclaredPrimaryKeys, getJunctionConfigForRelation, getTableName as getTableName$1, getTenantConfig, grantExecuteToRequestRolesSql, hasFieldAccessRules, includableRelationNames, isAddressableId, normalizeDriverOrderBy, normalizeEmail, normalizeInclude, normalizeToEntityRelation, parseIdValues, parseIdValues as parseIdValues$1, parseOrderBySpecStrict, queryableFieldNames, requireCallbackClient, requireCallbackCollection, resolveCollectionRelations, resolveTenantWrite, restoresSoftDeletedRow, restrictedFieldNames, revokeInternalTableSql, softDeleteFieldOf, sqlRows, tenantBypassRoles, toCallbackError, toFilterTuples, unknownAggregateField, unknownFilterField, unknownIncludeRelation, unknownOrderByField, unknownProjectionField, unknownRelationTargetField, unknownVectorProperty, updateDateAutoValues, updateUserAutoValues, warnOnTableDdl, withRelationReferencesOnly } from "@rebasepro/common";
|
|
28
30
|
import { camelCase, generateForeignKeyName, isPrototypePollutingKey, legacyForeignKeyName, splitSearchTerms, toSnakeCase, toWireKey, unref } from "@rebasepro/utils";
|
|
29
31
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
30
32
|
import { createHash } from "node:crypto";
|
|
@@ -3078,8 +3080,6 @@ function rowInTrashError(path, key, softDelete) {
|
|
|
3078
3080
|
* `beforeQueryConditions`) — and not of the server's own work, which reads
|
|
3079
3081
|
* with no viewer at all.
|
|
3080
3082
|
*/
|
|
3081
|
-
/** The roles a materialized view is served to when it names none. */
|
|
3082
|
-
var DEFAULT_VIEW_ROLES = ["admin"];
|
|
3083
3083
|
/** Whether a collection serves a view rather than a table. */
|
|
3084
3084
|
function isViewCollection(collection) {
|
|
3085
3085
|
return Boolean(collection && isPostgresCollectionConfig(collection) && collection.view);
|
|
@@ -7686,6 +7686,10 @@ var DataService = class {
|
|
|
7686
7686
|
* Execute raw SQL
|
|
7687
7687
|
*/
|
|
7688
7688
|
async executeSql(sqlText, params) {
|
|
7689
|
+
return rowsOfResult(await this.executeSqlResult(sqlText, params));
|
|
7690
|
+
}
|
|
7691
|
+
/** {@link executeSql}, answering with the driver's whole result: its rows and its column descriptions. */
|
|
7692
|
+
async executeSqlResult(sqlText, params) {
|
|
7689
7693
|
if (rawQueryLoggingEnabled()) logger.debug(`Executing raw SQL: ${sqlText}${params?.length ? ` with ${params.length} params` : ""}`);
|
|
7690
7694
|
const { sql } = await import("drizzle-orm");
|
|
7691
7695
|
let result;
|
|
@@ -7701,9 +7705,8 @@ var DataService = class {
|
|
|
7701
7705
|
const query = sql.join(chunks, sql.raw(""));
|
|
7702
7706
|
result = await this.db.execute(query);
|
|
7703
7707
|
} else result = await this.db.execute(sql.raw(sqlText));
|
|
7704
|
-
|
|
7705
|
-
|
|
7706
|
-
return rows;
|
|
7708
|
+
if (rawQueryLoggingEnabled()) logger.debug(`SQL executed successfully. Returned ${rowsOfResult(result).length} rows.`);
|
|
7709
|
+
return result;
|
|
7707
7710
|
}
|
|
7708
7711
|
/**
|
|
7709
7712
|
* Get the underlying FetchService for advanced use
|
|
@@ -7725,6 +7728,261 @@ var DataService = class {
|
|
|
7725
7728
|
}
|
|
7726
7729
|
};
|
|
7727
7730
|
//#endregion
|
|
7731
|
+
//#region src/security/caller-sql.ts
|
|
7732
|
+
/**
|
|
7733
|
+
* What SQL may run as a caller (`DataDriver.sql` on the authenticated driver).
|
|
7734
|
+
*
|
|
7735
|
+
* That SQL runs in the caller's transaction, as `rebase_user`, with the
|
|
7736
|
+
* caller's identity in transaction-local settings — the same footing as every
|
|
7737
|
+
* SDK read and write, so the tables' policies decide each row. Those settings
|
|
7738
|
+
* are the weak point: a statement running as `rebase_user` can change them.
|
|
7739
|
+
* `RESET ROLE` returns to the connection's owner role, and
|
|
7740
|
+
* `set_config('app.uid', …)` makes the policies see somebody else. Postgres
|
|
7741
|
+
* offers no way to stop a role from doing either.
|
|
7742
|
+
*
|
|
7743
|
+
* So the query text has to be the application's own, and anything a user
|
|
7744
|
+
* typed travels in `params`, which can never become SQL. This check is the
|
|
7745
|
+
* backstop for when that slips — a value interpolated into the text, a query
|
|
7746
|
+
* assembled from pieces: it refuses every statement that can touch session
|
|
7747
|
+
* state, and more than one statement at a time.
|
|
7748
|
+
*
|
|
7749
|
+
* - one statement;
|
|
7750
|
+
* - leading with `SELECT`, `WITH`, `VALUES`, `TABLE`, `INSERT`, `UPDATE`,
|
|
7751
|
+
* `DELETE` or `MERGE` — no `SET`, `RESET`, `DO`, `PREPARE`, DDL or
|
|
7752
|
+
* transaction control;
|
|
7753
|
+
* - never calling `set_config` or naming `pg_settings`, the two ways a query
|
|
7754
|
+
* can write a setting;
|
|
7755
|
+
* - never calling a function of the `rebase` schema but the identity readers
|
|
7756
|
+
* (`uid`, `roles`, `jwt`, `is_anonymous`) — the rest are the server's doors.
|
|
7757
|
+
*
|
|
7758
|
+
* Read after masking string literals, dollar-quoted bodies and comments, so a
|
|
7759
|
+
* value that merely contains `;` or `set_config` is not refused, and
|
|
7760
|
+
* a call hidden in a comment-split name is not missed.
|
|
7761
|
+
*/
|
|
7762
|
+
var ALLOWED_LEADS = /* @__PURE__ */ new Set([
|
|
7763
|
+
"select",
|
|
7764
|
+
"with",
|
|
7765
|
+
"values",
|
|
7766
|
+
"table",
|
|
7767
|
+
"insert",
|
|
7768
|
+
"update",
|
|
7769
|
+
"delete",
|
|
7770
|
+
"merge"
|
|
7771
|
+
]);
|
|
7772
|
+
/** `set_config(` in any spelling Postgres accepts: schema-qualified, quoted, spaced. */
|
|
7773
|
+
var SETS_A_SETTING = /(?:^|[^\w$])"?set_config"?\s*\(/i;
|
|
7774
|
+
/** `pg_settings`, which an `UPDATE` writes through to `set_config`. */
|
|
7775
|
+
var NAMES_PG_SETTINGS = /(?:^|[^\w$])"?pg_settings"?(?:[^\w$]|$)/i;
|
|
7776
|
+
/**
|
|
7777
|
+
* The functions in the `rebase` schema a caller may name: the ones policies
|
|
7778
|
+
* read the identity through. Everything else there is the server's —
|
|
7779
|
+
* `record_history` and `enqueue_job` are `SECURITY DEFINER` doors the request
|
|
7780
|
+
* role can execute, because a write's history and jobs commit in the write's
|
|
7781
|
+
* own transaction, and a statement calling one forges an entry or starts a job.
|
|
7782
|
+
*/
|
|
7783
|
+
var CALLER_REBASE_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
7784
|
+
"uid",
|
|
7785
|
+
"roles",
|
|
7786
|
+
"jwt",
|
|
7787
|
+
"is_anonymous"
|
|
7788
|
+
]);
|
|
7789
|
+
var REBASE_FUNCTION_CALL = /(?:^|[^\w$])"?rebase"?\s*\.\s*"?([A-Za-z_][\w$]*)"?\s*\(/gi;
|
|
7790
|
+
/** The doors by their bare names, for a `search_path` that reaches `rebase`. */
|
|
7791
|
+
var NAMES_A_SERVER_DOOR = /(?:^|[^\w$.])"?(record_history|enqueue_job)"?\s*\(/i;
|
|
7792
|
+
/**
|
|
7793
|
+
* The query with every string literal, dollar-quoted body and comment
|
|
7794
|
+
* replaced by a space. Quoted identifiers are kept, quotes and all, so a name
|
|
7795
|
+
* written `"set_config"` still reads as one.
|
|
7796
|
+
*/
|
|
7797
|
+
function maskSqlLiterals(text) {
|
|
7798
|
+
let out = "";
|
|
7799
|
+
let i = 0;
|
|
7800
|
+
while (i < text.length) {
|
|
7801
|
+
const ch = text[i];
|
|
7802
|
+
const next = text[i + 1];
|
|
7803
|
+
if (ch === "-" && next === "-") {
|
|
7804
|
+
const end = text.indexOf("\n", i);
|
|
7805
|
+
i = end === -1 ? text.length : end;
|
|
7806
|
+
out += " ";
|
|
7807
|
+
} else if (ch === "/" && next === "*") {
|
|
7808
|
+
let depth = 1;
|
|
7809
|
+
i += 2;
|
|
7810
|
+
while (i < text.length && depth > 0) if (text[i] === "/" && text[i + 1] === "*") {
|
|
7811
|
+
depth++;
|
|
7812
|
+
i += 2;
|
|
7813
|
+
} else if (text[i] === "*" && text[i + 1] === "/") {
|
|
7814
|
+
depth--;
|
|
7815
|
+
i += 2;
|
|
7816
|
+
} else i++;
|
|
7817
|
+
out += " ";
|
|
7818
|
+
} else if (ch === "'") {
|
|
7819
|
+
const escapes = i > 0 && /[eE]/.test(text[i - 1]) && (i < 2 || !/[\w$]/.test(text[i - 2]));
|
|
7820
|
+
i++;
|
|
7821
|
+
while (i < text.length) {
|
|
7822
|
+
if (escapes && text[i] === "\\") {
|
|
7823
|
+
i += 2;
|
|
7824
|
+
continue;
|
|
7825
|
+
}
|
|
7826
|
+
if (text[i] === "'") {
|
|
7827
|
+
if (text[i + 1] === "'") {
|
|
7828
|
+
i += 2;
|
|
7829
|
+
continue;
|
|
7830
|
+
}
|
|
7831
|
+
break;
|
|
7832
|
+
}
|
|
7833
|
+
i++;
|
|
7834
|
+
}
|
|
7835
|
+
i++;
|
|
7836
|
+
out += " ";
|
|
7837
|
+
} else if (ch === "\"") {
|
|
7838
|
+
const end = text.indexOf("\"", i + 1);
|
|
7839
|
+
const stop = end === -1 ? text.length : end + 1;
|
|
7840
|
+
out += text.slice(i, stop);
|
|
7841
|
+
i = stop;
|
|
7842
|
+
} else if (ch === "$" && (i === 0 || !/[\w$]/.test(text[i - 1]))) {
|
|
7843
|
+
const tag = /^\$(?:[A-Za-z_][\w]*)?\$/.exec(text.slice(i));
|
|
7844
|
+
if (!tag) {
|
|
7845
|
+
out += ch;
|
|
7846
|
+
i++;
|
|
7847
|
+
continue;
|
|
7848
|
+
}
|
|
7849
|
+
const end = text.indexOf(tag[0], i + tag[0].length);
|
|
7850
|
+
i = end === -1 ? text.length : end + tag[0].length;
|
|
7851
|
+
out += " ";
|
|
7852
|
+
} else {
|
|
7853
|
+
out += ch;
|
|
7854
|
+
i++;
|
|
7855
|
+
}
|
|
7856
|
+
}
|
|
7857
|
+
return out;
|
|
7858
|
+
}
|
|
7859
|
+
function refuse(reason) {
|
|
7860
|
+
throw new ApiError(400, "SQL_NOT_ALLOWED", `${reason} SQL run as the caller is one SELECT, WITH, VALUES, TABLE, INSERT, UPDATE, DELETE or MERGE statement, with every value passed in \`params\` (\$1, \$2, …). Session settings carry the caller's identity, so a statement that could change them is refused.`, void 0, true);
|
|
7861
|
+
}
|
|
7862
|
+
/** Throw `SQL_NOT_ALLOWED` unless `text` may run as the caller (see the module docs). */
|
|
7863
|
+
function assertCallerSql(text) {
|
|
7864
|
+
const code = maskSqlLiterals(text);
|
|
7865
|
+
const statements = code.split(";").filter((part) => part.trim().length > 0);
|
|
7866
|
+
if (statements.length === 0) refuse("The query is empty.");
|
|
7867
|
+
if (statements.length > 1) refuse("The query holds more than one statement.");
|
|
7868
|
+
const lead = /^[\s(]*([A-Za-z]+)/.exec(statements[0])?.[1]?.toLowerCase();
|
|
7869
|
+
if (!lead || !ALLOWED_LEADS.has(lead)) refuse(`\`${lead?.toUpperCase() ?? "?"}\` cannot run as the caller.`);
|
|
7870
|
+
if (/u&"/i.test(code)) refuse("The query spells an identifier with Unicode escapes (U&\"…\").");
|
|
7871
|
+
if (SETS_A_SETTING.test(code)) refuse("The query calls set_config.");
|
|
7872
|
+
if (NAMES_PG_SETTINGS.test(code)) refuse("The query names pg_settings.");
|
|
7873
|
+
for (const call of code.matchAll(REBASE_FUNCTION_CALL)) if (!CALLER_REBASE_FUNCTIONS.has(call[1].toLowerCase())) refuse(`The query calls rebase.${call[1]}, which is the server's.`);
|
|
7874
|
+
const door = NAMES_A_SERVER_DOOR.exec(code);
|
|
7875
|
+
if (door) refuse(`The query calls ${door[1]}, which is the server's.`);
|
|
7876
|
+
}
|
|
7877
|
+
//#endregion
|
|
7878
|
+
//#region src/security/caller-sql-columns.ts
|
|
7879
|
+
/**
|
|
7880
|
+
* The columns a caller may not read, taken out of what their SQL returned.
|
|
7881
|
+
*
|
|
7882
|
+
* Per-field read rules (`access.read`, and `excludeFromApi`, which is
|
|
7883
|
+
* `read: []`) are not something Postgres can hold for one request role shared
|
|
7884
|
+
* by every user, so the SDK applies them to each row it serves
|
|
7885
|
+
* (`stripUnreadable`). SQL run as the caller (`DataDriver.sql`) returns rows
|
|
7886
|
+
* the SDK never walked — and `SELECT *` from a users table would hand over the
|
|
7887
|
+
* password hash.
|
|
7888
|
+
*
|
|
7889
|
+
* Postgres says where each result column came from: the row description
|
|
7890
|
+
* carries the table's oid and the column's number for every column that is a
|
|
7891
|
+
* plain reference to one, aliased or not, `RETURNING` included. A column whose
|
|
7892
|
+
* origin is a collection property this caller cannot read is dropped from
|
|
7893
|
+
* every row, the way the API drops it.
|
|
7894
|
+
*
|
|
7895
|
+
* What it cannot see is a value computed from such a column — `md5(hash)`,
|
|
7896
|
+
* `hash || ''` — whose origin Postgres reports as none. That is the query
|
|
7897
|
+
* text's business, and the query text is the application's (see
|
|
7898
|
+
* `caller-sql.ts`).
|
|
7899
|
+
*
|
|
7900
|
+
* A driver that reports no origins at all (PGlite) has its result columns
|
|
7901
|
+
* matched by name instead, against every restricted column of every
|
|
7902
|
+
* collection: it may drop a column of the same name from another table, never
|
|
7903
|
+
* keep one it should drop.
|
|
7904
|
+
*/
|
|
7905
|
+
/** The columns of a result, from a pg `QueryResult` (or the last of several). */
|
|
7906
|
+
function fieldsOfResult(result) {
|
|
7907
|
+
const last = Array.isArray(result) ? result[result.length - 1] : result;
|
|
7908
|
+
if (typeof last !== "object" || last === null || !("fields" in last)) return [];
|
|
7909
|
+
const fields = last.fields;
|
|
7910
|
+
if (!Array.isArray(fields)) return [];
|
|
7911
|
+
return fields.flatMap((field) => {
|
|
7912
|
+
if (typeof field !== "object" || field === null || !("name" in field)) return [];
|
|
7913
|
+
const { name, tableID, columnID } = field;
|
|
7914
|
+
return [{
|
|
7915
|
+
name: String(name),
|
|
7916
|
+
...typeof tableID === "number" ? { tableID } : {},
|
|
7917
|
+
...typeof columnID === "number" ? { columnID } : {}
|
|
7918
|
+
}];
|
|
7919
|
+
});
|
|
7920
|
+
}
|
|
7921
|
+
/**
|
|
7922
|
+
* The relations result columns came from, by oid, read from the catalogue the
|
|
7923
|
+
* first time an oid is seen. An oid never changes meaning: a table that is
|
|
7924
|
+
* dropped and created again gets a new one, which is read when it appears.
|
|
7925
|
+
*/
|
|
7926
|
+
var ColumnOrigins = class {
|
|
7927
|
+
relations = /* @__PURE__ */ new Map();
|
|
7928
|
+
async describe(oids, run) {
|
|
7929
|
+
const unseen = [...new Set(oids)].filter((oid) => !this.relations.has(oid));
|
|
7930
|
+
if (unseen.length > 0) {
|
|
7931
|
+
const rows = await run(`SELECT c.oid::int AS oid, n.nspname AS schema, c.relname AS name, a.attnum::int AS attnum, a.attname AS column
|
|
7932
|
+
FROM pg_class c
|
|
7933
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
7934
|
+
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
|
|
7935
|
+
WHERE c.oid = ANY($1::oid[])`, [unseen]);
|
|
7936
|
+
for (const oid of unseen) this.relations.set(oid, null);
|
|
7937
|
+
for (const row of rows) {
|
|
7938
|
+
const oid = Number(row.oid);
|
|
7939
|
+
let relation = this.relations.get(oid);
|
|
7940
|
+
if (!relation) {
|
|
7941
|
+
relation = {
|
|
7942
|
+
schema: String(row.schema),
|
|
7943
|
+
name: String(row.name),
|
|
7944
|
+
columns: /* @__PURE__ */ new Map()
|
|
7945
|
+
};
|
|
7946
|
+
this.relations.set(oid, relation);
|
|
7947
|
+
}
|
|
7948
|
+
relation.columns.set(Number(row.attnum), String(row.column));
|
|
7949
|
+
}
|
|
7950
|
+
}
|
|
7951
|
+
return new Map(oids.map((oid) => [oid, this.relations.get(oid) ?? null]));
|
|
7952
|
+
}
|
|
7953
|
+
};
|
|
7954
|
+
var schemaOf = (collection) => isPostgresCollectionConfig(collection) && collection.schema || "public";
|
|
7955
|
+
/**
|
|
7956
|
+
* `rows` without the columns `viewer` may not read, by the origins `fields`
|
|
7957
|
+
* describe. The rows are changed in place and returned.
|
|
7958
|
+
*/
|
|
7959
|
+
async function withoutUnreadableColumns(rows, fields, viewer, collections, origins, run) {
|
|
7960
|
+
const restricted = collections.filter(hasFieldAccessRules);
|
|
7961
|
+
if (restricted.length === 0 || rows.length === 0 || fields.length === 0) return rows;
|
|
7962
|
+
const refusedBy = /* @__PURE__ */ new Map();
|
|
7963
|
+
for (const collection of restricted) {
|
|
7964
|
+
const { refused } = restrictedFieldNames(collection, viewer, "read");
|
|
7965
|
+
if (refused.size > 0) refusedBy.set(`${schemaOf(collection)}.${getTableName$1(collection)}`, refused);
|
|
7966
|
+
}
|
|
7967
|
+
if (refusedBy.size === 0) return rows;
|
|
7968
|
+
const drop = /* @__PURE__ */ new Set();
|
|
7969
|
+
if (fields.every((field) => field.tableID === void 0)) {
|
|
7970
|
+
const everyRefused = new Set([...refusedBy.values()].flatMap((names) => [...names]));
|
|
7971
|
+
for (const field of fields) if (everyRefused.has(field.name)) drop.add(field.name);
|
|
7972
|
+
} else {
|
|
7973
|
+
const fromTables = fields.filter((field) => field.tableID && field.columnID);
|
|
7974
|
+
const relations = await origins.describe(fromTables.map((field) => field.tableID), run);
|
|
7975
|
+
for (const field of fromTables) {
|
|
7976
|
+
const relation = relations.get(field.tableID);
|
|
7977
|
+
const column = relation?.columns.get(field.columnID);
|
|
7978
|
+
if (relation && column && refusedBy.get(`${relation.schema}.${relation.name}`)?.has(column)) drop.add(field.name);
|
|
7979
|
+
}
|
|
7980
|
+
}
|
|
7981
|
+
if (drop.size === 0) return rows;
|
|
7982
|
+
for (const row of rows) for (const name of drop) delete row[name];
|
|
7983
|
+
return rows;
|
|
7984
|
+
}
|
|
7985
|
+
//#endregion
|
|
7728
7986
|
//#region src/schema/classify-change.ts
|
|
7729
7987
|
/**
|
|
7730
7988
|
* What a collection change means for a live database.
|
|
@@ -8408,6 +8666,18 @@ function classifyTable$1(wasCollection, collection, before, after, changes, fact
|
|
|
8408
8666
|
}
|
|
8409
8667
|
for (const trigger of before.triggers) {
|
|
8410
8668
|
if (after.triggers.some((t) => t.name === trigger.name)) continue;
|
|
8669
|
+
if (trigger.kind === "keep-tenant") {
|
|
8670
|
+
push({
|
|
8671
|
+
kind: "change-constraint",
|
|
8672
|
+
verdict: "needs-migration",
|
|
8673
|
+
property: before.columns.find((c) => c.column === trigger.column)?.source.propName,
|
|
8674
|
+
detail: `The collection no longer declares a tenant, but trigger "${trigger.name}" stays and keeps refusing moves.`,
|
|
8675
|
+
remedy: `Drop it in a migration: DROP TRIGGER "${trigger.name}" ON "${after.schema}"."${after.table}".`,
|
|
8676
|
+
sourceOnly: `Trigger "${trigger.name}" stays and keeps "${trigger.column}" from changing.`,
|
|
8677
|
+
kept: `trigger ${trigger.name} kept`
|
|
8678
|
+
});
|
|
8679
|
+
continue;
|
|
8680
|
+
}
|
|
8411
8681
|
push({
|
|
8412
8682
|
kind: "change-constraint",
|
|
8413
8683
|
verdict: "needs-migration",
|
|
@@ -8424,7 +8694,7 @@ function classifyTable$1(wasCollection, collection, before, after, changes, fact
|
|
|
8424
8694
|
kind: "change-constraint",
|
|
8425
8695
|
verdict: "safe",
|
|
8426
8696
|
property: after.columns.find((c) => c.column === trigger.column)?.source.propName,
|
|
8427
|
-
detail: `"${trigger.column}" is stamped with now() on every update — creates trigger "${trigger.name}".`
|
|
8697
|
+
detail: trigger.kind === "keep-tenant" ? `An update can no longer move a row to another tenant — creates trigger "${trigger.name}".` : `"${trigger.column}" is stamped with now() on every update — creates trigger "${trigger.name}".`
|
|
8428
8698
|
});
|
|
8429
8699
|
}
|
|
8430
8700
|
}
|
|
@@ -10540,7 +10810,7 @@ var RoleSwitchUnavailableError = class extends Error {
|
|
|
10540
10810
|
/** The underlying Postgres error, when the refusal came from a live attempt. */
|
|
10541
10811
|
pgError;
|
|
10542
10812
|
constructor(role, pgError) {
|
|
10543
|
-
super(`Cannot execute SQL as role "${role}": this connection is not permitted to SET ROLE. The statement was NOT executed — running it as the connection owner would return owner-visible rows, which is a different question from the one that was asked. Grant the connection user membership in "${role}", or set DISABLE_DB_ROLE_SWITCHING=true to run SQL Editor queries as the connection owner.`);
|
|
10813
|
+
super(`Cannot execute SQL as role "${role}": this connection is not permitted to SET ROLE. The statement was NOT executed — running it as the connection owner would return owner-visible rows, which is a different question from the one that was asked. Grant the connection user membership in "${role}" with the right to switch to it — \`GRANT "${role.replace(/"/g, "\"\"")}" TO <connection user> WITH SET TRUE\` on PostgreSQL 16+, where a membership can exist without it (a role created by a non-superuser with CREATEROLE is one), or a plain \`GRANT\` before 16 — or set DISABLE_DB_ROLE_SWITCHING=true to run SQL Editor queries as the connection owner.` + (pgError ? ` Postgres said: ${extractPgError(pgError)?.message ?? (pgError instanceof Error ? pgError.message : String(pgError))}` : ""));
|
|
10544
10814
|
this.name = "RoleSwitchUnavailableError";
|
|
10545
10815
|
this.role = role;
|
|
10546
10816
|
this.pgError = pgError;
|
|
@@ -10738,6 +11008,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10738
11008
|
branchService;
|
|
10739
11009
|
user;
|
|
10740
11010
|
data;
|
|
11011
|
+
/** Where the columns of a caller's SQL came from — see `caller-sql-columns.ts`. */
|
|
11012
|
+
columnOrigins = new ColumnOrigins();
|
|
10741
11013
|
/**
|
|
10742
11014
|
* The server singleton, attached by `initializeRebaseBackend` after boot —
|
|
10743
11015
|
* a driver exists before the client does. Typed as what is attached: a
|
|
@@ -10746,18 +11018,23 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10746
11018
|
*/
|
|
10747
11019
|
client;
|
|
10748
11020
|
/**
|
|
10749
|
-
*
|
|
10750
|
-
*
|
|
10751
|
-
* to be refused again.
|
|
11021
|
+
* Roles a `SET ROLE` has been refused for with insufficient privileges,
|
|
11022
|
+
* with the refusal, so later statements as that role refuse without
|
|
11023
|
+
* spending the round trip to be refused again.
|
|
10752
11024
|
*
|
|
10753
11025
|
* Deliberately NOT a mirror of `DISABLE_DB_ROLE_SWITCHING`, which it used
|
|
10754
11026
|
* to be described as. The env var is an operator saying "run these as the
|
|
10755
|
-
* connection owner"; this
|
|
10756
|
-
*
|
|
10757
|
-
*
|
|
10758
|
-
*
|
|
11027
|
+
* connection owner"; this is the database saying "I cannot give you the
|
|
11028
|
+
* role you asked for". The first is a decision and permits the fallback,
|
|
11029
|
+
* the second is a failure and must not — see the SECURITY note in
|
|
11030
|
+
* {@link executeSql}.
|
|
11031
|
+
*
|
|
11032
|
+
* Per role, and keeping Postgres's own error. It was one flag: a single
|
|
11033
|
+
* refusal for a role picked in the SQL editor then refused every other
|
|
11034
|
+
* role too, `rebase_user` included, and every later refusal said "not
|
|
11035
|
+
* permitted to SET ROLE" with the reason Postgres gave already dropped.
|
|
10759
11036
|
*/
|
|
10760
|
-
|
|
11037
|
+
_roleSwitchRefusals = /* @__PURE__ */ new Map();
|
|
10761
11038
|
/**
|
|
10762
11039
|
* Restricted role that authenticated (user-context) requests run as (via
|
|
10763
11040
|
* `SET LOCAL ROLE`) so RLS binds every statement — reads *and* writes. Set
|
|
@@ -10768,6 +11045,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10768
11045
|
* migrations, `dataAsAdmin`).
|
|
10769
11046
|
*/
|
|
10770
11047
|
rlsUserRole;
|
|
11048
|
+
/** How a request picks its role and identity settings (`rls`), set with {@link rlsUserRole}. */
|
|
11049
|
+
rlsRequest;
|
|
10771
11050
|
/**
|
|
10772
11051
|
* The direct (non-pooled) URL {@link listen} holds its `LISTEN` on — this
|
|
10773
11052
|
* source's, set by the bootstrapper. Never read from `DATABASE_DIRECT_URL`
|
|
@@ -12240,7 +12519,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
12240
12519
|
const collection = this.resolveCollectionCallbacks(void 0, path).collection;
|
|
12241
12520
|
if (!collection || !isPostgresCollectionConfig(collection) || !collection.view?.materialized) throw ApiError.badRequest(`"${collection?.slug ?? path}" is not a materialized view, so there is nothing to refresh.`, "NOT_A_MATERIALIZED_VIEW");
|
|
12242
12521
|
const schema = collection.schema ?? "public";
|
|
12243
|
-
const qualified = sql`${sql.identifier(schema)}.${sql.identifier(getTableName$1(collection))}`;
|
|
12522
|
+
const qualified = sql`${sql.identifier(schema)}.${sql.identifier(viewRowsName(getTableName$1(collection)))}`;
|
|
12244
12523
|
await this.db.execute(options?.concurrently ? sql`REFRESH MATERIALIZED VIEW CONCURRENTLY ${qualified}` : sql`REFRESH MATERIALIZED VIEW ${qualified}`);
|
|
12245
12524
|
await this.realtimeService.notifyUpdate(path, "*", null);
|
|
12246
12525
|
}
|
|
@@ -12439,12 +12718,12 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
12439
12718
|
logger.debug(`[PostgresBackendDriver] DISABLE_DB_ROLE_SWITCHING=true — running as the connection owner rather than "${role}".`);
|
|
12440
12719
|
return;
|
|
12441
12720
|
}
|
|
12442
|
-
if (this.
|
|
12721
|
+
if (this._roleSwitchRefusals.has(role)) throw new RoleSwitchUnavailableError(role, this._roleSwitchRefusals.get(role));
|
|
12443
12722
|
try {
|
|
12444
12723
|
await connection.query(`SET ROLE "${role.replace(/"/g, "\"\"")}"`);
|
|
12445
12724
|
} catch (roleError) {
|
|
12446
12725
|
if (isRoleSwitchingPermissionError(roleError)) {
|
|
12447
|
-
this.
|
|
12726
|
+
this._roleSwitchRefusals.set(role, roleError);
|
|
12448
12727
|
throw new RoleSwitchUnavailableError(role, roleError);
|
|
12449
12728
|
}
|
|
12450
12729
|
throw roleError;
|
|
@@ -12492,7 +12771,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
12492
12771
|
needsRoleSwitch = true;
|
|
12493
12772
|
}
|
|
12494
12773
|
if (needsRoleSwitch && options?.role) if (isRoleSwitchingOptedOut()) logger.debug(`[PostgresBackendDriver] DISABLE_DB_ROLE_SWITCHING=true — running as the connection owner rather than "${options.role}".`);
|
|
12495
|
-
else if (this.
|
|
12774
|
+
else if (this._roleSwitchRefusals.has(options.role)) throw new RoleSwitchUnavailableError(options.role, this._roleSwitchRefusals.get(options.role));
|
|
12496
12775
|
else {
|
|
12497
12776
|
const safeRole = options.role.replace(/"/g, "\"\"");
|
|
12498
12777
|
try {
|
|
@@ -12502,7 +12781,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
12502
12781
|
});
|
|
12503
12782
|
} catch (roleError) {
|
|
12504
12783
|
if (isRoleSwitchingPermissionError(roleError)) {
|
|
12505
|
-
this.
|
|
12784
|
+
this._roleSwitchRefusals.set(options.role, roleError);
|
|
12506
12785
|
throw new RoleSwitchUnavailableError(options.role, roleError);
|
|
12507
12786
|
}
|
|
12508
12787
|
throw roleError;
|
|
@@ -12753,6 +13032,19 @@ var AuthenticatedPostgresBackendDriver = class {
|
|
|
12753
13032
|
});
|
|
12754
13033
|
}
|
|
12755
13034
|
/**
|
|
13035
|
+
* One statement as this caller — see {@link DataDriver.sql}. The same
|
|
13036
|
+
* transaction every SDK call on this driver opens (`rebase_user`, the
|
|
13037
|
+
* caller's identity), read-only unless `write`, and so on the read replica
|
|
13038
|
+
* when a read may go there.
|
|
13039
|
+
*/
|
|
13040
|
+
async sql(query, options) {
|
|
13041
|
+
assertCallerSql(query);
|
|
13042
|
+
return this.withTransaction(async (delegate) => {
|
|
13043
|
+
const result = await delegate.dataService.executeSqlResult(query, options?.params);
|
|
13044
|
+
return withoutUnreadableColumns(rowsOfResult(result), fieldsOfResult(result), { roles: this.user?.roles ?? [] }, this.delegate.registry?.getCollections() ?? [], this.delegate.columnOrigins, (text, params) => delegate.dataService.executeSql(text, params));
|
|
13045
|
+
}, { accessMode: options?.write ? "read write" : "read only" });
|
|
13046
|
+
}
|
|
13047
|
+
/**
|
|
12756
13048
|
* Run `operation` in a transaction as this caller — on the read replica
|
|
12757
13049
|
* when this is a read the replica may serve (see {@link replicaFor}), else
|
|
12758
13050
|
* on the primary.
|
|
@@ -12850,13 +13142,13 @@ var AuthenticatedPostgresBackendDriver = class {
|
|
|
12850
13142
|
};
|
|
12851
13143
|
const auth = authContextOf(this.user);
|
|
12852
13144
|
if (pipelined) {
|
|
12853
|
-
const opening = authContextStatement(auth, this.delegate.rlsUserRole, transactionSettingsConfig(pooledSettings));
|
|
13145
|
+
const opening = authContextStatement(auth, this.delegate.rlsRequest ?? this.delegate.rlsUserRole, transactionSettingsConfig(pooledSettings));
|
|
12854
13146
|
return runPipelinedTransaction(pipelined.db, pipelined.pool, [opening], options, inTransaction);
|
|
12855
13147
|
}
|
|
12856
13148
|
return db.transaction(async (tx) => {
|
|
12857
13149
|
const transactionSettings = transactionSettingsStatements(pooledSettings);
|
|
12858
13150
|
if (transactionSettings.length > 0) await tx.execute(sql.raw(transactionSettings.join("; ")));
|
|
12859
|
-
await applyAuthContext(tx, auth, this.delegate.rlsUserRole);
|
|
13151
|
+
await applyAuthContext(tx, auth, this.delegate.rlsRequest ?? this.delegate.rlsUserRole);
|
|
12860
13152
|
return inTransaction(tx);
|
|
12861
13153
|
}, options);
|
|
12862
13154
|
}).finally(() => writeScope?.close())).catch(async (error) => {
|
|
@@ -16516,6 +16808,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
16516
16808
|
* would leak rows the initial (isolated) fetch correctly hid.
|
|
16517
16809
|
*/
|
|
16518
16810
|
rlsUserRole;
|
|
16811
|
+
/** How a request picks its role and identity settings (`rls`), set with {@link rlsUserRole}. */
|
|
16812
|
+
rlsRequest;
|
|
16519
16813
|
/**
|
|
16520
16814
|
* Verbose subscription tracing.
|
|
16521
16815
|
*
|
|
@@ -17443,7 +17737,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
17443
17737
|
roles: activeAuth.roles,
|
|
17444
17738
|
isAnonymous: activeAuth.isAnonymous === true,
|
|
17445
17739
|
claims: activeAuth.claims
|
|
17446
|
-
}, this.rlsUserRole);
|
|
17740
|
+
}, this.rlsRequest ?? this.rlsUserRole);
|
|
17447
17741
|
let hookContext;
|
|
17448
17742
|
const txEntityService = new DataService(tx, this.registry, () => hookContext ??= callbackContextWithin(this.driver, tx, activeAuth));
|
|
17449
17743
|
const fetchedEntities = collectionRequest.countOnly ? [] : await txEntityService.fetchCollectionForRest(notifyPath, {
|
|
@@ -17644,7 +17938,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
17644
17938
|
roles: activeAuth.roles,
|
|
17645
17939
|
isAnonymous: activeAuth.isAnonymous === true,
|
|
17646
17940
|
claims: activeAuth.claims
|
|
17647
|
-
}, this.rlsUserRole);
|
|
17941
|
+
}, this.rlsRequest ?? this.rlsUserRole);
|
|
17648
17942
|
let hookContext;
|
|
17649
17943
|
let processedEntity = await new DataService(tx, this.registry, () => hookContext ??= callbackContextWithin(this.driver, tx, activeAuth)).fetchOneForRest(notifyPath, id, include, collection?.databaseId) ?? void 0;
|
|
17650
17944
|
if (processedEntity) {
|
|
@@ -21313,13 +21607,7 @@ async function ensureHistoryTableExists(db, options = {}) {
|
|
|
21313
21607
|
$fn$
|
|
21314
21608
|
`));
|
|
21315
21609
|
await db.execute(sql.raw(`REVOKE ALL ON FUNCTION ${signature} FROM PUBLIC`));
|
|
21316
|
-
await db.execute(sql.raw(
|
|
21317
|
-
DO $grant$ BEGIN
|
|
21318
|
-
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}') THEN
|
|
21319
|
-
GRANT EXECUTE ON FUNCTION ${signature} TO ${REBASE_USER_ROLE};
|
|
21320
|
-
END IF;
|
|
21321
|
-
END $grant$
|
|
21322
|
-
`));
|
|
21610
|
+
await db.execute(sql.raw(grantExecuteToRequestRolesSql(signature)));
|
|
21323
21611
|
return {
|
|
21324
21612
|
inTransaction: true,
|
|
21325
21613
|
entryFormat
|
|
@@ -22229,8 +22517,10 @@ function postgresDriverConfigFromEnv(config, env = process.env, sourceKey = DEFA
|
|
|
22229
22517
|
const directConnectionString = config.directConnectionString || (isDefaultSource ? read("DATABASE_DIRECT_URL") : void 0);
|
|
22230
22518
|
const pooled = config.pooled ?? (isDefaultSource ? read("DATABASE_POOLED")?.toLowerCase() === "true" : void 0);
|
|
22231
22519
|
const readRouting = config.readRouting ?? (read("REBASE_READ_STICKY_MS") || read("REBASE_READ_MAX_LAG_MS") ? readRoutingOptionsFromEnv(env) : void 0);
|
|
22520
|
+
const rls = rlsConfigFromEnv(config.rls, read);
|
|
22232
22521
|
return {
|
|
22233
22522
|
...config,
|
|
22523
|
+
...rls ? { rls } : {},
|
|
22234
22524
|
...readConnectionString ? { readConnectionString } : {},
|
|
22235
22525
|
...directConnectionString ? { directConnectionString } : {},
|
|
22236
22526
|
...pooled ? { pooled } : {},
|
|
@@ -22280,7 +22570,11 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
22280
22570
|
}));
|
|
22281
22571
|
}
|
|
22282
22572
|
if (unprotectedJoinTables.length > 0) {
|
|
22283
|
-
|
|
22573
|
+
const requestRoles = resolveRlsSettings({
|
|
22574
|
+
...declaredDatabaseRls(config.dataSourceKey ?? DEFAULT_DATA_SOURCE_KEY),
|
|
22575
|
+
...pgConfig.rls
|
|
22576
|
+
}).roles.join(", ");
|
|
22577
|
+
logger.warn(`🔒 [rls] ${unprotectedJoinTables.length} join table(s) have row-level security disabled: ${unprotectedJoinTables.join(", ")}. The API does not serve a join table, with RLS or without, but ${requestRoles} keeps its grants on these, so SQL your own code runs as a caller reaches every row.`);
|
|
22284
22578
|
for (const t of unprotectedJoinTables) schema.tablesMap.delete(t);
|
|
22285
22579
|
}
|
|
22286
22580
|
if (policyless.length > 0) logger.warn(`🔒 [rls] ${policyless.length} table(s) have RLS enabled but no policies, so they will return no rows: ${policyless.join(", ")}`);
|
|
@@ -22414,6 +22708,22 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
22414
22708
|
realtimeService.setDataDriver(driver);
|
|
22415
22709
|
let rlsEnforcement;
|
|
22416
22710
|
let exposedInternalTables;
|
|
22711
|
+
const rls = resolveRlsSettings({
|
|
22712
|
+
...declaredDatabaseRls(sourceKey),
|
|
22713
|
+
...pgConfig.rls
|
|
22714
|
+
});
|
|
22715
|
+
const policyShape = declaredRlsPolicyShape(sourceKey);
|
|
22716
|
+
if (rls.policyTarget !== policyShape.policyTarget || rls.defaultPolicies !== policyShape.defaultPolicies) throw new Error(`rls.policyTarget and rls.defaultPolicies shape the policy SQL that \`rebase db generate\` writes, and the CLI cannot see the driver's code. Declare them on the database instead — database({ rls: { policyTarget: "${rls.policyTarget}", defaultPolicies: ${rls.defaultPolicies} } }) — or set REBASE_RLS_POLICY_TARGET / REBASE_RLS_DEFAULT_POLICIES.`);
|
|
22717
|
+
/** The tables this driver serves — collections, junctions — for `grants: "managed"`. */
|
|
22718
|
+
const managedTables = () => registry.getTableNames().flatMap((name) => {
|
|
22719
|
+
const table = registry.getTable(name);
|
|
22720
|
+
if (!table) return [];
|
|
22721
|
+
const config = getTableConfig(table);
|
|
22722
|
+
return [{
|
|
22723
|
+
schema: config.schema ?? "public",
|
|
22724
|
+
table: config.name
|
|
22725
|
+
}];
|
|
22726
|
+
});
|
|
22417
22727
|
{
|
|
22418
22728
|
const runSql = async (text) => {
|
|
22419
22729
|
return (await schemaAwareDb.execute(sql.raw(text))).rows ?? [];
|
|
@@ -22427,27 +22737,72 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
22427
22737
|
const posture = await detectConnectionPosture(runSql, managedSchemas);
|
|
22428
22738
|
if (posture.privileged) {
|
|
22429
22739
|
const bypassesNow = posture.superuser || posture.bypassRLS || posture.ownsTables;
|
|
22740
|
+
const roleList = rls.roles.map((r) => `"${r}"`).join(", ");
|
|
22430
22741
|
let switched = true;
|
|
22431
22742
|
if (!provision) {
|
|
22432
|
-
const roleExists = (await runSql(`SELECT
|
|
22743
|
+
const roleExists = (await runSql(`SELECT rolname FROM pg_roles WHERE rolname = ANY(ARRAY[${rls.roles.map((r) => `'${r}'`).join(", ")}]::text[])`)).length === rls.roles.length;
|
|
22433
22744
|
switched = roleExists || bypassesNow;
|
|
22434
22745
|
if (roleExists) {
|
|
22435
|
-
|
|
22436
|
-
|
|
22746
|
+
try {
|
|
22747
|
+
assertRecordedRequestRoles(rls.roles, await readRecordedRequestRoles(runSql), await roleHoldsTableGrants(runSql, managedSchemas));
|
|
22748
|
+
for (const role of rls.roles) {
|
|
22749
|
+
await assertAppRoleRestricted(runSql, role);
|
|
22750
|
+
await proveRoleSwitch(runSql, managedSchemas, posture.role, role);
|
|
22751
|
+
}
|
|
22752
|
+
} catch (err) {
|
|
22753
|
+
if (bypassesNow) throw err;
|
|
22754
|
+
switched = false;
|
|
22755
|
+
logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" owns no tables yet and is subject to RLS, so requests are served without the switch: ${err instanceof Error ? err.message : String(err)}`);
|
|
22756
|
+
}
|
|
22757
|
+
for (const role of rls.roles) {
|
|
22758
|
+
const exposed = await findExposedInternalTables(runSql, managedSchemas, role);
|
|
22759
|
+
if (exposed.length === 0) continue;
|
|
22760
|
+
exposedInternalTables = [...exposedInternalTables ?? [], ...exposed];
|
|
22761
|
+
logger.warn(`⚠️ RLS enforcement: the request role "${role}" can reach framework tables no user should: ${exposed.join(", ")}. A provisioning boot revokes this; this driver was opened without provisioning, so nothing does.`);
|
|
22762
|
+
}
|
|
22437
22763
|
}
|
|
22438
|
-
if (!roleExists && bypassesNow) logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" bypasses row-level security and the restricted role
|
|
22764
|
+
if (!roleExists && bypassesNow) logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" bypasses row-level security and the restricted role ${roleList} does not exist yet — this driver was opened without provisioning, so it was not created. Requests made as a user will fail until a server boot (or \`rebase db push\`) creates it; requests as the connection itself are unaffected.`);
|
|
22439
22765
|
} else try {
|
|
22440
|
-
await
|
|
22766
|
+
const recorded = await readRecordedRequestRoles(runSql);
|
|
22767
|
+
assertRecordedRequestRoles(rls.roles, recorded, await roleHoldsTableGrants(runSql, managedSchemas));
|
|
22768
|
+
if (recorded ? recorded.join(",") !== rls.roles.join(",") : rls.roles.join(",") !== REBASE_USER_ROLE$1) await recordRequestRoles(runSql, rls.roles);
|
|
22769
|
+
for (const role of rls.roles) await ensureAppRole(runSql, managedSchemas, {
|
|
22770
|
+
role,
|
|
22771
|
+
provisionRole: rls.provisionRole,
|
|
22772
|
+
grants: rls.grants,
|
|
22773
|
+
managedTables: managedTables(),
|
|
22774
|
+
inheritRoles: rls.inheritTo.includes(role) ? rls.inheritRoles : []
|
|
22775
|
+
});
|
|
22441
22776
|
} catch (err) {
|
|
22442
22777
|
if (bypassesNow) throw err;
|
|
22443
22778
|
switched = false;
|
|
22444
22779
|
logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" owns no tables yet and is subject to RLS, but it may create tables in ${managedSchemas.join(", ")} — and a table's owner bypasses every non-FORCE policy on it. The restricted role could not be provisioned: ${err instanceof Error ? err.message : String(err)}`);
|
|
22445
22780
|
}
|
|
22446
22781
|
if (switched) {
|
|
22447
|
-
driver.rlsUserRole =
|
|
22448
|
-
realtimeService.rlsUserRole =
|
|
22782
|
+
driver.rlsUserRole = rls.defaultRole;
|
|
22783
|
+
realtimeService.rlsUserRole = rls.defaultRole;
|
|
22784
|
+
driver.rlsRequest = rls.request;
|
|
22785
|
+
realtimeService.rlsRequest = rls.request;
|
|
22449
22786
|
const why = posture.superuser ? "superuser" : posture.bypassRLS ? "BYPASSRLS" : posture.ownsTables ? "table owner" : "may create (and would then own) tables in the schemas it serves";
|
|
22450
|
-
rlsEnforcement = `🔐 RLS enforcement active: authenticated requests run as
|
|
22787
|
+
rlsEnforcement = `🔐 RLS enforcement active: authenticated requests run as ${roleList} (connection "${posture.role}" bypasses RLS: ${why})` + (rls.nonDefaults.length > 0 ? `; rls: ${rls.nonDefaults.join(", ")}` : "");
|
|
22788
|
+
for (const note of rlsHandoverNotes(rls)) logger.info(`🔐 [rls] ${note}`);
|
|
22789
|
+
for (const role of rls.roles) {
|
|
22790
|
+
if (rls.sharedRole === "ignore") break;
|
|
22791
|
+
const others = await findOtherRoleMembers(runSql, role);
|
|
22792
|
+
if (others.length === 0) continue;
|
|
22793
|
+
const message = `The request role "${role}" can also be used by ${others.map((o) => `"${o}"`).join(", ")}, which can connect to this database, switch into it, and pass its policies as whichever user it likes. Give this project a role of its own (rls.requestRole / REBASE_RLS_REQUEST_ROLE, then \`rebase db request-role migrate\`), revoke CONNECT on this database from PUBLIC, or set rls.sharedRole to "ignore" if the role is shared on purpose.`;
|
|
22794
|
+
if (rls.sharedRole === "refuse") throw new Error(`Refusing to serve: ${message}`);
|
|
22795
|
+
logger.warn(`⚠️ RLS enforcement: ${message}`);
|
|
22796
|
+
}
|
|
22797
|
+
for (const role of rls.roles) {
|
|
22798
|
+
const ungrantable = await findUngrantableTables(runSql, collectionsOnThisSource().map((c) => ({
|
|
22799
|
+
schema: c.schema ?? "public",
|
|
22800
|
+
table: getTableName$1(c)
|
|
22801
|
+
})).filter((t) => Boolean(t.table)), role);
|
|
22802
|
+
if (ungrantable.length === 0) continue;
|
|
22803
|
+
logger.warn(`⚠️ RLS enforcement: requests run as "${role}", which holds no privilege on ${ungrantable.length === 1 ? "this table" : "these tables"}, and connection "${posture.role}" cannot grant one because another role owns them. Every request to them will be refused until the owner runs the grant:
|
|
22804
|
+
` + ungrantable.map((t) => ` ${t.name} (owner "${t.owner}"): ${t.grant}`).join("\n"));
|
|
22805
|
+
}
|
|
22451
22806
|
}
|
|
22452
22807
|
if (posture.superuser || posture.bypassRLS) {
|
|
22453
22808
|
const message = `The database connection runs as ${posture.superuser ? "a superuser" : "a BYPASSRLS role"} ("${posture.role}"). User requests are isolated via SET LOCAL ROLE, but connect as a non-superuser table-owner role in production so the server/owner context is least-privilege.`;
|
|
@@ -22455,7 +22810,8 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
22455
22810
|
else logger.warn(`⚠️ ${message}`);
|
|
22456
22811
|
}
|
|
22457
22812
|
} else rlsEnforcement = `🔐 RLS enforcement: connection role "${posture.role}" is subject to RLS natively; no role switch needed.`;
|
|
22458
|
-
|
|
22813
|
+
if (!driver.rlsUserRole && rls.policyTarget === "requestRole") throw new Error(`rls.policyTarget is "requestRole", but requests are not switching to a request role here (connection "${posture.role}" is ${posture.privileged ? "not able to switch" : "subject to RLS natively"}), so every policy would deny every row. Use policyTarget "public" with this connection, or connect as a role that owns the tables so requests switch.`);
|
|
22814
|
+
await validatePolicyPgRoles(runSql, collectionsOnThisSource(), driver.rlsUserRole ? rls.roles : posture.role);
|
|
22459
22815
|
warnOnAnonymousGrants(collectionsOnThisSource());
|
|
22460
22816
|
warnOnLegacyRlsFunctions(collectionsOnThisSource());
|
|
22461
22817
|
}
|
|
@@ -22643,6 +22999,8 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
22643
22999
|
driver,
|
|
22644
23000
|
poolManager,
|
|
22645
23001
|
provisioned: provision,
|
|
23002
|
+
rls,
|
|
23003
|
+
managedTables,
|
|
22646
23004
|
rlsEnforcement,
|
|
22647
23005
|
exposedInternalTables,
|
|
22648
23006
|
provisionCdcForTables
|
|
@@ -22715,7 +23073,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22715
23073
|
const openIndexBuildSession = (driverResult) => async () => {
|
|
22716
23074
|
const db = requireProvisioningDb(driverResult);
|
|
22717
23075
|
const pool = "$client" in db ? db.$client : void 0;
|
|
22718
|
-
const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-
|
|
23076
|
+
const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
|
|
22719
23077
|
const config = effectiveConfig();
|
|
22720
23078
|
if (isPooledPool(pool) || config.pooled) {
|
|
22721
23079
|
if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
|
|
@@ -22746,8 +23104,9 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22746
23104
|
*/
|
|
22747
23105
|
const provisionRlsRuntime = async (driverResult) => {
|
|
22748
23106
|
const db = requireProvisioningDb(driverResult);
|
|
22749
|
-
const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-
|
|
23107
|
+
const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent, ensureRequestRoleFunction } = await import("./migrate-baseline-BfHmq3vN.js").then((n) => n.D);
|
|
22750
23108
|
const run = async (text) => sqlRows(await db.execute(sql.raw(text)));
|
|
23109
|
+
if (declaredRlsPolicyShape().policyTarget === "requestRole") await ensureRequestRoleFunction(run);
|
|
22751
23110
|
if (await rlsRuntimeIsCurrent(run).catch(() => false)) return;
|
|
22752
23111
|
await db.transaction(async (tx) => {
|
|
22753
23112
|
await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext('rebase_auth_functions_init'))`);
|
|
@@ -22770,7 +23129,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22770
23129
|
for (const [qualified, { schema, table }] of withheldTables) try {
|
|
22771
23130
|
await runSql(revokeUserRoleSql(schema, table));
|
|
22772
23131
|
} catch (err) {
|
|
22773
|
-
throw new Error(`Refusing to start: row-level security could not be enabled on "${qualified}", and the privileges the schema-wide grant just gave
|
|
23132
|
+
throw new Error(`Refusing to start: row-level security could not be enabled on "${qualified}", and the privileges the schema-wide grant just gave the request role on it could not be taken back. The table would be served with no row filtering. Fix the database permissions (the connection role must own the table, or be able to ALTER it) and boot again: ` + (err instanceof Error ? err.message : String(err)));
|
|
22774
23133
|
}
|
|
22775
23134
|
};
|
|
22776
23135
|
return {
|
|
@@ -22780,8 +23139,8 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22780
23139
|
const opened = await openPostgresDriver(effectiveConfig(init.dataSourceKey), init);
|
|
22781
23140
|
if (opened.internals.rlsEnforcement) logger.info(opened.internals.rlsEnforcement);
|
|
22782
23141
|
const exposed = opened.internals.exposedInternalTables ?? [];
|
|
22783
|
-
if (exposed.length > 0) throw new Error(`The request role
|
|
22784
|
-
` + exposed.map((table) => ` REVOKE ALL ON ${table.split(".").map((part) => `"${part}"`).join(".")} FROM ${REBASE_USER_ROLE$1};`).join("\n"));
|
|
23142
|
+
if (exposed.length > 0) throw new Error(`The request role ${(opened.internals.rls?.roles ?? [REBASE_USER_ROLE$1]).map((r) => `"${r}"`).join(", ")} can read or write framework tables that hold sessions, key hashes and job payloads: ${exposed.join(", ")}.\nA provisioning boot revokes this, and this backend changes nothing in its database (provisioning is off). Revoke it as part of your change process:
|
|
23143
|
+
` + exposed.map((table) => ` REVOKE ALL ON ${table.split(".").map((part) => `"${part}"`).join(".")} FROM ${(opened.internals.rls?.roles ?? [REBASE_USER_ROLE$1]).join(", ")};`).join("\n"));
|
|
22785
23144
|
return opened;
|
|
22786
23145
|
},
|
|
22787
23146
|
async initializeAuth(config, driverResult) {
|
|
@@ -22859,11 +23218,11 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22859
23218
|
unavailable: historyUnavailableReason(state, { requireTransaction: false })
|
|
22860
23219
|
}) };
|
|
22861
23220
|
}
|
|
22862
|
-
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-
|
|
23221
|
+
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-BSNpEUOS.js").then((n) => n.i);
|
|
22863
23222
|
const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
|
|
22864
23223
|
const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
|
|
22865
23224
|
if (historyIndexes.length > 0) {
|
|
22866
|
-
const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-
|
|
23225
|
+
const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
|
|
22867
23226
|
const indexOptions = {
|
|
22868
23227
|
log: (message) => logger.info(`[history] ${message}`),
|
|
22869
23228
|
lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
|
|
@@ -22919,9 +23278,9 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22919
23278
|
* proved it can bootstrap with.
|
|
22920
23279
|
*/
|
|
22921
23280
|
async ensureCollectionSchema(collections, driverResult, log) {
|
|
22922
|
-
const { ensureCollectionTables } = await import("./ensure-collection-tables-
|
|
23281
|
+
const { ensureCollectionTables } = await import("./ensure-collection-tables-DR_WcxLA.js").then((n) => n.n);
|
|
22923
23282
|
const queryable = provisioningQueryable(driverResult);
|
|
22924
|
-
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-
|
|
23283
|
+
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-BSNpEUOS.js").then((n) => n.i);
|
|
22925
23284
|
const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
|
|
22926
23285
|
const plan = await ensureCollectionTables(queryable, collections, log, {
|
|
22927
23286
|
lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
|
|
@@ -22933,7 +23292,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22933
23292
|
pendingIndexBuild?.cancel();
|
|
22934
23293
|
pendingIndexBuild = void 0;
|
|
22935
23294
|
if (!provisionOnly && plan.deferredIndexes.length > 0) {
|
|
22936
|
-
const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-
|
|
23295
|
+
const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
|
|
22937
23296
|
logger.info(`[schema] ${plan.deferredIndexes.length} index(es) are missing, or were left INVALID, on tables that already exist. They are built in the background once the server is serving, one at a time, without blocking reads or writes.`);
|
|
22938
23297
|
pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
|
|
22939
23298
|
log: (message) => logger.info(`[schema] ${message}`),
|
|
@@ -22973,7 +23332,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22973
23332
|
await provisionRlsRuntime(driverResult);
|
|
22974
23333
|
},
|
|
22975
23334
|
async ensureCollectionPolicies(collections, driverResult, log) {
|
|
22976
|
-
const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-
|
|
23335
|
+
const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-85HiG-k1.js");
|
|
22977
23336
|
const queryable = provisioningQueryable(driverResult);
|
|
22978
23337
|
const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
|
|
22979
23338
|
if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
|
|
@@ -22995,10 +23354,10 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
22995
23354
|
else logger.warn(`${message}; they are re-applied on the next boot.`);
|
|
22996
23355
|
}
|
|
22997
23356
|
const unrevoked = outcome.unsecured.filter((u) => !u.grantWithdrawn);
|
|
22998
|
-
for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) logger.error(`🔐 [rls] Could not enable row-level security on "${u.table}": ${u.error}. Its privileges have been revoked from
|
|
22999
|
-
if (unrevoked.length > 0) throw new Error("Refusing to start: row-level security could not be enabled on " + unrevoked.map((u) => `"${u.table}" (${u.error})`).join(", ") +
|
|
23357
|
+
for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) logger.error(`🔐 [rls] Could not enable row-level security on "${u.table}": ${u.error}. Its privileges have been revoked from the request role, so the table is unreachable rather than unprotected. Reads and writes to that collection will fail until RLS can be enabled.`);
|
|
23358
|
+
if (unrevoked.length > 0) throw new Error("Refusing to start: row-level security could not be enabled on " + unrevoked.map((u) => `"${u.table}" (${u.error})`).join(", ") + ", and the privileges granted to the request role could not be revoked either. The table would be served with no row filtering. Fix the database permissions (the connection role must own these tables, or be able to ALTER them) and boot again.");
|
|
23000
23359
|
try {
|
|
23001
|
-
const { dropLegacyAuthSchema } = await import("./migrate-baseline-
|
|
23360
|
+
const { dropLegacyAuthSchema } = await import("./migrate-baseline-BfHmq3vN.js").then((n) => n.D);
|
|
23002
23361
|
await dropLegacyAuthSchema(async (text) => (await queryable.query(text)).rows, {
|
|
23003
23362
|
info: (m) => logger.info(m),
|
|
23004
23363
|
warn: (m) => logger.warn(m)
|
|
@@ -23064,11 +23423,17 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
23064
23423
|
"rebase",
|
|
23065
23424
|
...registry.getCollections().map((c) => c.schema).filter((s) => typeof s === "string")
|
|
23066
23425
|
];
|
|
23426
|
+
const rls = internals.rls ?? resolveRlsSettings(void 0);
|
|
23427
|
+
const grantOptions = (role) => ({
|
|
23428
|
+
role,
|
|
23429
|
+
mode: rls.grants,
|
|
23430
|
+
managedTables: internals.managedTables?.() ?? []
|
|
23431
|
+
});
|
|
23067
23432
|
if (driver.rlsUserRole) {
|
|
23068
23433
|
try {
|
|
23069
|
-
await ensureAppRoleGrants(runSql, managedSchemas);
|
|
23434
|
+
for (const role of rls.roles) await ensureAppRoleGrants(runSql, managedSchemas, grantOptions(role));
|
|
23070
23435
|
} catch (err) {
|
|
23071
|
-
logger.warn(`⚠️ RLS enforcement: could not grant "${
|
|
23436
|
+
logger.warn(`⚠️ RLS enforcement: could not grant ${rls.roles.map((r) => `"${r}"`).join(", ")} on the schemas provisioning created (${managedSchemas.join(", ")}). Requests that touch them will be refused with "permission denied for schema …" until a boot can: ${err instanceof Error ? err.message : String(err)}`);
|
|
23072
23437
|
}
|
|
23073
23438
|
await withholdAgain(runSql);
|
|
23074
23439
|
return;
|
|
@@ -23076,20 +23441,28 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
23076
23441
|
const posture = await detectConnectionPosture(runSql, managedSchemas);
|
|
23077
23442
|
if (!posture.superuser && !posture.bypassRLS && !posture.ownsTables) return;
|
|
23078
23443
|
try {
|
|
23079
|
-
await ensureAppRole(runSql, managedSchemas
|
|
23444
|
+
for (const role of rls.roles) await ensureAppRole(runSql, managedSchemas, {
|
|
23445
|
+
role,
|
|
23446
|
+
provisionRole: rls.provisionRole,
|
|
23447
|
+
grants: rls.grants,
|
|
23448
|
+
managedTables: internals.managedTables?.() ?? [],
|
|
23449
|
+
inheritRoles: rls.inheritTo.includes(role) ? rls.inheritRoles : []
|
|
23450
|
+
});
|
|
23080
23451
|
} catch (err) {
|
|
23081
23452
|
throw new Error(`The database connection role "${posture.role}" now owns tables in this database, so it bypasses every row-level security policy on them — but the restricted role it should switch to could not be provisioned, so authenticated requests would be served with no policy applied at all. Refusing to serve.\n\n${err instanceof Error ? err.message : String(err)}`);
|
|
23082
23453
|
}
|
|
23083
23454
|
await withholdAgain(runSql);
|
|
23084
|
-
driver.rlsUserRole =
|
|
23085
|
-
realtimeService.rlsUserRole =
|
|
23086
|
-
|
|
23455
|
+
driver.rlsUserRole = rls.defaultRole;
|
|
23456
|
+
realtimeService.rlsUserRole = rls.defaultRole;
|
|
23457
|
+
driver.rlsRequest = rls.request;
|
|
23458
|
+
realtimeService.rlsRequest = rls.request;
|
|
23459
|
+
logger.info(`🔐 RLS enforcement active: the connection role "${posture.role}" became a table owner during this boot, so authenticated requests now run as ${rls.roles.map((r) => `"${r}"`).join(", ")}.`);
|
|
23087
23460
|
},
|
|
23088
23461
|
getAdmin(driverResult) {
|
|
23089
23462
|
return driverResult.internals.driver.admin;
|
|
23090
23463
|
},
|
|
23091
23464
|
async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
|
|
23092
|
-
const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-
|
|
23465
|
+
const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-B33YjKhs.js").then((n) => n.c);
|
|
23093
23466
|
if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
|
|
23094
23467
|
const realtimeConfig = effectiveConfig().realtime;
|
|
23095
23468
|
const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
|
|
@@ -23202,8 +23575,14 @@ async function openRebase(options) {
|
|
|
23202
23575
|
throw error;
|
|
23203
23576
|
}
|
|
23204
23577
|
const resolveAccessor = createAccessorSlugResolver(() => registry.getCollections());
|
|
23205
|
-
const
|
|
23206
|
-
|
|
23578
|
+
const scopedTo = async (identity) => {
|
|
23579
|
+
const scoped = await driver.withAuth(userFor(identity));
|
|
23580
|
+
return {
|
|
23581
|
+
scoped,
|
|
23582
|
+
data: buildSdkData(scoped, { resolveAccessor })
|
|
23583
|
+
};
|
|
23584
|
+
};
|
|
23585
|
+
const dataAsAdmin = (await scopedTo(SERVICE_IDENTITY)).data;
|
|
23207
23586
|
const admin = driver.admin;
|
|
23208
23587
|
let closed = false;
|
|
23209
23588
|
return {
|
|
@@ -23222,7 +23601,13 @@ async function openRebase(options) {
|
|
|
23222
23601
|
});
|
|
23223
23602
|
},
|
|
23224
23603
|
async withAuth(user) {
|
|
23225
|
-
|
|
23604
|
+
const { scoped, data } = await scopedTo(user);
|
|
23605
|
+
const sql = scoped.sql?.bind(scoped);
|
|
23606
|
+
if (!sql) throw new Error("This driver cannot run SQL as a caller.");
|
|
23607
|
+
return {
|
|
23608
|
+
data,
|
|
23609
|
+
sql
|
|
23610
|
+
};
|
|
23226
23611
|
},
|
|
23227
23612
|
async close() {
|
|
23228
23613
|
if (closed) return;
|
|
@@ -23234,4 +23619,4 @@ async function openRebase(options) {
|
|
|
23234
23619
|
//#endregion
|
|
23235
23620
|
export { AuthenticatedPostgresBackendDriver as $, budgetSendBuffers as A, mfaFactors as B, PG_NOTIFY_MAX_PAYLOAD_BYTES as C, MemoryChannelBus as D, parseChannelBusPayload as E, createAuthSchema as F, recoveryCodesRelations as G, passwordResetTokens as H, magicLinkTokens as I, userIdentities as J, refreshTokens as K, magicLinkTokensRelations as L, terminateIfBacklogged as M, assertReadRequestReadable as N, frameByteLength as O, appConfig as P, usersSchema as Q, mfaChallenges as R, DEFAULT_BATCH_WINDOW_MS as S, parseChannelBusFrame as T, passwordResetTokensRelations as U, mfaFactorsRelations as V, recoveryCodes as W, users as X, userIdentitiesRelations as Y, usersRelations as Z, parseRealtimeTuning as _, listedColumnKeys as _t, openPostgresDriver as a, isRoleSwitchingOptedOut as at, resolveChannelBusSetting as b, resolveSourceUrls as c, SqlResultTooLargeError as ct, DEFAULT_RECOUNT_MIN_ROWS as d, DrizzleConditionBuilder as dt, CONNECTION_OWNER as et, PostgresRealtimeProvider as f, PostgresConditionBuilder as ft, parseMaxSubscriptionsPerSocket as g, joinColumn as gt, parseMaxSocketsPerUser as h, getUnknownFilterFieldsMode as ht, isScaffoldedLocalDatabase as i, effectiveSqlRole as it, reapSilentSockets as j, isChannelBusInstance$1 as k, PostgresCollectionRegistry as l, isNestedPath as lt, packEntityChanges as m, escapeLikePattern as mt, createPostgresBootstrapper as n, RoleSwitchUnavailableError as nt, postgresDriverConfigFromEnv as o, sqlRoleRanAs as ot, RealtimeService as p, configureUnknownFilterFields as pt, refreshTokensRelations as q, describeSchemaDriftCause as r, branchParentDatabase as rt, resolveDriftCheckName as s, SQL_RESULT_BYTE_BUDGET as st, openRebase as t, PostgresBackendDriver as tt, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as u, resolveNestedPath as ut, refetchConcurrencyFor as v, PostgresChannelBus as w, CHANNEL_BUS_NOTIFY_CHANNEL as x, createChannelBus as y, mfaChallengesRelations as z };
|
|
23236
23621
|
|
|
23237
|
-
//# sourceMappingURL=open-rebase-
|
|
23622
|
+
//# sourceMappingURL=open-rebase-CiO_sjMT.js.map
|