Skip to content

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.

Multi-Tenant Request Pipeline & PostgreSQL 16 FORCE RLS
EDGE & IDENTITY PLANEHOST TRANSACTION & PG16 FORCE RLS ISOLATIONHTTPSX-Req-IdPKCE / RevokedorgIdBEGIN + GUCClient RequestOIDC · Bearer JWTldx_pat_* API KeyCaddy 2.10 +APISIX 3.19TLS 1.3 · JWKSValkey Rate LimitNocoBase Auth &ScopePKCE · Valkey DB 2Resolve tenant orgIdKeycloak 26.8 +Valkey DB 2PKCE S256 (300s / 60s)Revocation Guard (24h)AsyncLocalStorageTxwithTenantRlsContextSET LOCALapp.current_orgPostgreSQL 16FORCE RLSRole: nocobase_appNOBYPASSRLS56 + Custom Tables
InspectorPostgreSQL 16 FORCE RLSClick any component to inspect bindings & boundaries
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.
Every user request or ldx_pat_* token traverses Caddy, APISIX, and NocoBase scope middleware to bind transaction-local app.current_org (is_local=true) via AsyncLocalStorage and execute as nocobase_app (NOSUPERUSER NOBYPASSRLS) across 56 static and dynamic latticeCustom* tables. Only internal background workers use withSystemRlsBypass.

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.

RLS Session Parameters & Database Roles (pg-rls.js & prod.yml)
ParameterTypeDefaultDescription
DX_PG_RLS_SESSIONrequired
boolean (env)trueEnables 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 GUCoffSet to 'on' solely inside controlled system transactions (pre-tenant login lookup, seeding, or root operations).
NOCOBASE_APP_DB_USERrequired
PostgreSQL Rolenocobase_appNon-superuser runtime role created with NOBYPASSRLS, strictly distinct from POSTGRES_USER.
DX_DEFAULT_ORG_ID
string (env)1Fallback organization identifier for single-organization deployments.
MechanismEnforcement 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 defaultWhen 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_app with NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOBYPASSRLS.
  • Aborts startup if NOCOBASE_APP_DB_USER equals POSTGRES_USER.
  • Revokes default PUBLIC privileges on both the nocobase database and public schema, while granting ownership to nocobase_app so migrations run without granting BYPASSRLS.
  • In infra/config/postgres/init-prod.sh, the platform database likewise creates lattice_app, keycloak_app, and n8n_app with NOSUPERUSER 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".

sql
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 StageExecution Behavior
Scoped transaction bindingwithTenantRlsContext(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 injectionwrapRepositoryMethods 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 attachmentsetContextRlsTransaction(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.
javascript
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 NameDomain Group#Table NameDomain Group
1latticeRequestsCore Requests & Intake28latticeDataQuarantineData Governance
2latticeOrdersOMS / WMS Orders29latticeOrderLinesOMS / WMS Orders
3latticeAssetsAssets & Fleet30latticeStockLotsFEFO Inventory Lots
4latticeEmployeesDirectory & Org31latticeEpodRecordsElectronic Proof of Delivery
5latticeDepartmentsDirectory & Org32latticeDecisionTablesVisual DMN
6latticeLocationsDirectory & Org33latticeDelegationsApproval Delegations
7latticeIncidentCasesIncident Management34latticeTwinShadowsIIoT Digital Twin
8latticeIncidentRulesIncident Management35latticeConnectorsConnector Vault
9latticeAgentProposalsAI HITL Proposals36latticeEventBusEvent Bus Outbox
10latticeContextOutboxNGSI-LD Outbox37latticeWebhookSubscriptionsWebhook Subscriptions
11latticeIntegrationInboxInbound Integrations38latticeWebhookDeliveriesWebhook Deliveries
12latticeRecordChatterRecord Activity Feed39latticeIotDevicesIIoT Device Registry
13latticeNotificationsIn-App Notifications40latticeBrokerSubscriptionsOrion-LD Subscriptions
14latticeSlaPoliciesSLA Policies41latticeAutomationRulesLatticeFlow v2
15latticeParaDocumentsP.A.R.A. Vault42latticeAutomationRunsLatticeFlow v2
16latticeParaChunksHybrid RAG Chunks43latticeBuiltAppsApp Builder 2.0
17latticeServiceTicketsInternal Service Desk44latticeAiMemoryPersistent AI Memory
18latticeAiProfilesAI Agent Profiles45latticeAiTracesOTel AI Traces
19latticeAiAuditLogsAI Tool Audit Logs46latticeAutomationRuleVersionsFlow Versioning
20latticeAiQuotaUsageAI Quota Usage47latticeA2aTasksA2A Protocol Tasks
21latticeAiApprovalQueueAI HITL Queue48latticeNotificationDeliveriesNotification Deliveries
22latticeTelemetryPointsIIoT Time-Series49latticeApprovalPoliciesUnified Approvals
23latticeApiKeysldx_pat_* API Keys50latticeApprovalRequestsUnified Approvals
24latticePkiKeysEd25519 Keypairs51latticePublicFormsPublic Intake Forms
25latticeCryptoLedgerPKI Merkle Ledger52latticePublicFormSubmissionsForm Submissions
26latticeFrozenSnapshotsFrozen Snapshots53latticeAiQuotaPoliciesAI Quota Policies
27latticeDataLineageData Lineage54latticeUiSnapshotsUI Time-Machine Snapshots

2 Static snake_case Tables (organization_id) ​

#Table NameTenant ColumnPurpose
55lattice_native_request_attachmentsorganization_idStores request attachment metadata post-ClamAV scan
56lattice_native_request_uploadsorganization_idTracks 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:

sql
-- 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';

Apache-2.0 · LatticeDX v0.4.2 · Powered by NocoBase · v2.2.50 · Apache-2.0 (Clause 5.2)