Multi-Tenancy & PostgreSQL 16 FORCE RLS
LatticeDX v0.4.2 enforces defense-in-depth tenant isolation across both the application middleware layer (createNativeScopeMiddleware) and PostgreSQL 16 (ENABLE ROW LEVEL SECURITY paired with FORCE ROW LEVEL SECURITY). Even if an ORM call omits an organizationId filter, PostgreSQL blocks cross-organization reads and writes at the storage engine boundary.
- Role
- PG16 Row Isolation Engine (Role nocobase_app)
- Package / Port
- pgvector/pgvector:0.8.1-pg16 (:5432) · NOCOBASE_APP_DB_USER=nocobase_app
- Protocol
- ENABLE + FORCE ROW LEVEL SECURITY · NOSUPERUSER NOBYPASSRLS
- Payload / Schema
- Policy lattice_tenant_isolation (USING & WITH CHECK · 56 static + latticeCustom*)
- Responsibilities
- Connects as nocobase_app (NOSUPERUSER NOBYPASSRLS); enforces lattice_tenant_isolation USING & WITH CHECK across 54 camelCase tables, 2 snake_case attachment tables, and dynamic latticeCustom* tables.
Session GUC Contract (app.current_org & app.rls_bypass)
All PostgreSQL RLS policies, transaction helpers, and migrations in plugins/nocobase/plugin-lattice-foundation/src/server/pg-rls.js bind to the transaction-local GUCs app.current_org and app.rls_bypass. When DX_PG_RLS_SESSION=true is active (enabled by default in infra/compose/prod.yml), every tenant-scoped query executes inside a transaction bound to these settings.
| Parameter | Type | Default | Description |
|---|---|---|---|
DX_PG_RLS_SESSIONrequired | boolean (env) | true | Enables transaction-local PostgreSQL RLS GUC binding in plugin-lattice-foundation. |
app.current_orgrequired | PostgreSQL GUC | (empty) | Active organization identifier bound locally via set_config('app.current_org', :orgId, true). Validated against ^[a-zA-Z0-9_-]{1,80}$. |
app.rls_bypass | PostgreSQL GUC | off | Set to 'on' solely inside controlled system transactions (pre-tenant login lookup, seeding, or root operations). |
NOCOBASE_APP_DB_USERrequired | PostgreSQL Role | nocobase_app | Non-superuser runtime role created with NOBYPASSRLS, strictly distinct from POSTGRES_USER. |
DX_DEFAULT_ORG_ID | string (env) | 1 | Fallback organization identifier for single-organization deployments. |
| Mechanism | Enforcement Rule |
|---|---|
Transaction-local scope (is_local = true) | setTransactionRlsOrg executes SELECT set_config('app.current_org', :orgId, true). Passing true forces PostgreSQL to clear the GUC automatically on COMMIT or ROLLBACK, preventing tenant context bleed across pooled connections. |
Identifier validation (assertValidOrganizationId) | Accepts only strings matching ^[a-zA-Z0-9_-]{1,80}$ and rejects empty strings, 'all', and prototype-pollution keys (__proto__, constructor, prototype). |
| Fail-closed default | When app.current_org is unset or empty, nullif(current_setting('app.current_org', true), '') evaluates to NULL. Because "organizationId" = NULL evaluates to UNKNOWN, queries outside an active RLS context return 0 rows on reads and fail WITH CHECK on writes. |
Non-Superuser Role Separation (nocobase_app)
By default in PostgreSQL, superusers and table owners bypass standard RLS unless FORCE ROW LEVEL SECURITY and a non-superuser role are both enforced. The initialization script infra/config/postgres/init-nocobase-db.sh separates POSTGRES_USER from the runtime role nocobase_app:
- Creates
nocobase_appwithNOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS. - Aborts startup if
NOCOBASE_APP_DB_USERequalsPOSTGRES_USER. - Revokes default
PUBLICprivileges on both thenocobasedatabase andpublicschema, while granting ownership tonocobase_appso migrations run without grantingBYPASSRLS. - In
infra/config/postgres/init-prod.sh, the platform database likewise createslattice_app,keycloak_app, andn8n_appwithNOSUPERUSER NOBYPASSRLS.
lattice_tenant_isolation Policy & Savepoints
buildRlsPolicySql(tableName, options) generates standardized DDL across static and dynamic tables. The 54 camelCase tables filter on "organizationId", while the 2 snake_case attachment tables (SNAKE_CASE_ORG_TABLES) filter on "organization_id".
ALTER TABLE public."latticeOrders" ENABLE ROW LEVEL SECURITY;
ALTER TABLE public."latticeOrders" FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS lattice_tenant_isolation ON public."latticeOrders";
CREATE POLICY lattice_tenant_isolation ON public."latticeOrders"
AS PERMISSIVE FOR ALL TO PUBLIC
USING (
current_setting('app.rls_bypass', true) = 'on'
OR current_setting('app.current_org', true) = '*'
OR "organizationId" = nullif(current_setting('app.current_org', true), '')
)
WITH CHECK (
current_setting('app.rls_bypass', true) = 'on'
OR current_setting('app.current_org', true) = '*'
OR "organizationId" = nullif(current_setting('app.current_org', true), '')
);Because an unhandled SQL error inside a PostgreSQL transaction puts the entire transaction into an aborted state (25P02), runInRlsSavepoint(db, fn) wraps optional fallback queries in SAVEPOINT "ldx_sp_<n>" and ROLLBACK TO SAVEPOINT / RELEASE SAVEPOINT so the outer tenant transaction stays intact.
AsyncLocalStorage Transaction Bridge
NocoBase 2.2.50 internals and ORM hooks frequently invoke Repository methods without forwarding an explicit { transaction } argument. pg-rls.js solves this via rlsStore (AsyncLocalStorage) and installRlsTransactionBridge(db):
| Bridge Stage | Execution Behavior |
|---|---|
| Scoped transaction binding | withTenantRlsContext(db, organizationId, fn) opens a Sequelize transaction, executes set_config('app.current_org', :orgId, true), and invokes the callback inside rlsStore.run({ sequelize, transaction, organizationId }, ...). |
| Automatic transaction injection | wrapRepositoryMethods wraps find, findOne, findAndCount, count, create, update, destroy, and query on Repository.prototype (guarded by RLS_BRIDGE_MARKER = Symbol.for('latticedx.pgRlsBridgeInstalled')), alongside sequelize.query and db.getRepository(). Nested calls without an explicit transaction inherit store.transaction when targeting the matching sequelize instance. |
| Non-enumerable context attachment | setContextRlsTransaction(ctx, transaction) defines ctx.state.latticeRlsTransaction with enumerable: false so NocoBase 2.2.50 createContextVariablesScope (JSON.stringify(ctx.state)) skips the circular Sequelize Transaction object graph. |
Controlled system bypass (withSystemRlsBypass) | Restricted to pre-tenant identity resolution (resolveNativeActor reading latticeEmployees in native-scope.js, ldx_pat_* validation in paas-api-keys.js, or root administrative requests). When nested inside an existing transaction, native-scope.js reads SELECT current_setting('app.rls_bypass', true) AS prev, sets 'on' temporarily, and restores prev in a finally block. |
async function withTenantRlsContext(db, organizationId, fn) {
assertValidOrganizationId(organizationId);
const sequelize = db?.sequelize;
return sequelize.transaction(async (transaction) => {
await setTransactionRlsOrg(db, organizationId, transaction);
return rlsStore.run({ sequelize, transaction, organizationId }, () => fn(transaction));
});
}Complete Catalog of All 56 Static Tables & Dynamic ^latticeCustom.* Tables
TENANT_RLS_TABLES in pg-rls.js enforces FORCE ROW LEVEL SECURITY across 56 static tables: 54 camelCase tables keyed on "organizationId" and 2 snake_case tables keyed on "organization_id".
54 Static camelCase Tables (organizationId)
| # | Table Name | Domain Group | # | Table Name | Domain Group |
|---|---|---|---|---|---|
1 | latticeRequests | Core Requests & Intake | 28 | latticeDataQuarantine | Data Governance |
2 | latticeOrders | OMS / WMS Orders | 29 | latticeOrderLines | OMS / WMS Orders |
3 | latticeAssets | Assets & Fleet | 30 | latticeStockLots | FEFO Inventory Lots |
4 | latticeEmployees | Directory & Org | 31 | latticeEpodRecords | Electronic Proof of Delivery |
5 | latticeDepartments | Directory & Org | 32 | latticeDecisionTables | Visual DMN |
6 | latticeLocations | Directory & Org | 33 | latticeDelegations | Approval Delegations |
7 | latticeIncidentCases | Incident Management | 34 | latticeTwinShadows | IIoT Digital Twin |
8 | latticeIncidentRules | Incident Management | 35 | latticeConnectors | Connector Vault |
9 | latticeAgentProposals | AI HITL Proposals | 36 | latticeEventBus | Event Bus Outbox |
10 | latticeContextOutbox | NGSI-LD Outbox | 37 | latticeWebhookSubscriptions | Webhook Subscriptions |
11 | latticeIntegrationInbox | Inbound Integrations | 38 | latticeWebhookDeliveries | Webhook Deliveries |
12 | latticeRecordChatter | Record Activity Feed | 39 | latticeIotDevices | IIoT Device Registry |
13 | latticeNotifications | In-App Notifications | 40 | latticeBrokerSubscriptions | Orion-LD Subscriptions |
14 | latticeSlaPolicies | SLA Policies | 41 | latticeAutomationRules | LatticeFlow v2 |
15 | latticeParaDocuments | P.A.R.A. Vault | 42 | latticeAutomationRuns | LatticeFlow v2 |
16 | latticeParaChunks | Hybrid RAG Chunks | 43 | latticeBuiltApps | App Builder 2.0 |
17 | latticeServiceTickets | Internal Service Desk | 44 | latticeAiMemory | Persistent AI Memory |
18 | latticeAiProfiles | AI Agent Profiles | 45 | latticeAiTraces | OTel AI Traces |
19 | latticeAiAuditLogs | AI Tool Audit Logs | 46 | latticeAutomationRuleVersions | Flow Versioning |
20 | latticeAiQuotaUsage | AI Quota Usage | 47 | latticeA2aTasks | A2A Protocol Tasks |
21 | latticeAiApprovalQueue | AI HITL Queue | 48 | latticeNotificationDeliveries | Notification Deliveries |
22 | latticeTelemetryPoints | IIoT Time-Series | 49 | latticeApprovalPolicies | Unified Approvals |
23 | latticeApiKeys | ldx_pat_* API Keys | 50 | latticeApprovalRequests | Unified Approvals |
24 | latticePkiKeys | Ed25519 Keypairs | 51 | latticePublicForms | Public Intake Forms |
25 | latticeCryptoLedger | PKI Merkle Ledger | 52 | latticePublicFormSubmissions | Form Submissions |
26 | latticeFrozenSnapshots | Frozen Snapshots | 53 | latticeAiQuotaPolicies | AI Quota Policies |
27 | latticeDataLineage | Data Lineage | 54 | latticeUiSnapshots | UI Time-Machine Snapshots |
2 Static snake_case Tables (organization_id)
| # | Table Name | Tenant Column | Purpose |
|---|---|---|---|
55 | lattice_native_request_attachments | organization_id | Stores request attachment metadata post-ClamAV scan |
56 | lattice_native_request_uploads | organization_id | Tracks binary upload sessions handled by file-scanner |
Dynamic ^latticeCustom[A-Za-z0-9_]*$ Tables
Every custom domain table provisioned via dxosBuilder:createDomain or App Builder 2.0 (matching ^latticeCustom[A-Za-z0-9_]*$, including generated belongsToMany join tables latticeCustom<Src><Tgt>Join) receives a non-null indexed organizationId column, ENABLE + FORCE ROW LEVEL SECURITY, and policy verification against pg_class via attachAndVerifyPgRls in domain-schema-rls.js. At runtime, discoverTenantRlsTables queries information_schema.columns to audit both the 56 static tables and any dynamic latticeCustom* tables.
Live PostgreSQL Verification Queries
Operators can inspect pg_class, pg_policies, and fail-closed isolation behavior directly under the nocobase_app role:
-- 1. Verify all 56+ tables have relrowsecurity and relforcerowsecurity enabled
SELECT c.relname AS table_name,
c.relrowsecurity AS rls_enabled,
c.relforcerowsecurity AS rls_forced
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public'
AND (c.relname LIKE 'lattice%' OR c.relname LIKE 'lattice_%')
ORDER BY c.relname;
-- 2. Verify active lattice_tenant_isolation policy expressions
SELECT tablename, policyname, cmd, roles, qual, with_check
FROM pg_policies
WHERE schemaname = 'public' AND policyname = 'lattice_tenant_isolation';