Orbit PlatformDatabase Architecture & Multi-Tenant IsolationIntermediate

Enterprise SQL Kernel Row-Level Security, Session Injection & Multi-Tenant Isolation Specification

Exhaustive enterprise system governance manual and database kernel specification for deterministic row-level security (RLS), session variable injection, FORCE ROW LEVEL SECURITY enforcement, and multi-tenant isolation verification.

·
8 min read

1. Multi-Tenant Threat Model & Architectural Strategy

Multi-tenant SaaS architectures typically choose between three database tenancy patterns:

  1. Database-per-Tenant: Maximum isolation, but creates unsustainable connection pool overhead and complex migration maintenance at scale.
  2. Schema-per-Tenant: Moderate isolation, but generates migration drift and excessive schema metadata bloat as tenant counts expand.
  3. Shared Database & Shared Schema with Kernel RLS: Single unified database schema where every tenant-scoped table includes a tenantId column, with access policies enforced directly by the relational database kernel.

Orbit adopts the third model, fortified by Enterprise SQL Row-Level Security (RLS) configured in database migrations 001_enable_rls_tenant_tables.sql and 048_enable_rls_missing_tables.sql. Even if an application server query omits tenant filters entirely (such as SELECT * FROM orders;), the database engine evaluates kernel policies and returns strictly the active tenant's records.

[Application Query Request: "SELECT * FROM orders;"]
                      |
                      v
       [Enterprise SQL Relational Engine]
                      |
                      v
       [Row-Level Security Evaluation Gate]
        - Reads: current_setting('app.current_tenant', true)
        - Executes: current_tenant_id()
        - Invariant: (is_rls_bypassed() OR "tenantId" = current_tenant_id())
                      |
        +-------------+-------------+
        |                           |
 [MATCHES TENANT]            [MISMATCH OR NULL]
        |                           |
 [Rows Returned]             [Silently Filtered: 0 Rows]

2. Interactive Database Security Inspector

Authorized database administrators and security compliance auditors inspect active kernel policies and session parameters via the administrative security interface:

Enterprise SQL Kernel RLS & Isolation Sentinel
Production UI
Row-Level Security Policies, Session Context & Penetration Audit VerificationDatabase Kernel Security Inspector
RLS Enforcement
ENFORCED
FORCE ROW LEVEL SECURITY
Applies to Table Owners
Active Tenant Scope
ISOLATED
app.current_tenant Set
Scope: Transaction-Local
Protected Tables
45+ TABLES
100% Policy Coverage
Zero Unprotected Tables
Penetration Audit
16 / 16 PASS
Cross-Tenant Leak Tests
Zero Breach Findings
Kernel Session Context & Active Security Settings
Session Variable (current_setting)app.current_tenant = "e7a3b4c1-289d-4a11-8c43-98f5a2b10091"

Injected per connection checkout within transactional boundaries.

Bypass Evaluation Flagapp.rls_bypass = "off" (is_rls_bypassed() === FALSE)

Super-admin bypass is locked off; regular queries cannot elevate.


3. Kernel Functions & Context Evaluation

The isolation layer uses two core procedural functions compiled into the relational database engine:

3.1 current_tenant_id() Session Extractor

Defined in 001_enable_rls_tenant_tables.sql, this function extracts the active tenant identifier from the transaction session settings:

CREATE OR REPLACE FUNCTION current_tenant_id() RETURNS uuid AS $$
DECLARE
    setting_val text;
    tenant_uuid uuid;
BEGIN
    setting_val := NULLIF(current_setting('app.current_tenant', true), '');
    IF setting_val IS NULL THEN
        RETURN NULL;
    END IF;

    BEGIN
        tenant_uuid := setting_val::uuid;
        RETURN tenant_uuid;
    EXCEPTION
        WHEN invalid_text_representation THEN
            SELECT id INTO tenant_uuid FROM tenants WHERE slug = setting_val LIMIT 1;
            RETURN tenant_uuid;
        WHEN OTHERS THEN
            RETURN NULL;
    END;
END;
$$ LANGUAGE plpgsql STABLE;

Key Design Decisions:

  • current_setting('app.current_tenant', true): The secondary boolean argument true ensures that if the setting has not been defined in the current session, the call returns NULL rather than throwing a runtime SQL exception.
  • UUID or Slug Interoperability: If the incoming session string is not a valid UUID (such as when an application passes a tenant slug like "dha-phase5"), the exception handler looks up the primary tenant UUID from the tenants table.
  • STABLE Volatility Marker: Declaring the function as STABLE informs the relational query optimizer that within a single table scan or transaction, the function output will not fluctuate, enabling index optimization.

3.2 is_rls_bypassed() Super-Admin Guard

For scheduled platform maintenance, multi-tenant analytics rollups, or global database backups, background workers can explicitly enable administrative bypass mode:

CREATE OR REPLACE FUNCTION is_rls_bypassed() RETURNS boolean AS $$
BEGIN
    RETURN current_setting('app.rls_bypass', true) = 'on';
EXCEPTION
    WHEN OTHERS THEN RETURN false;
END;
$$ LANGUAGE plpgsql STABLE;

Unless the session variable app.rls_bypass is set to 'on', this function returns false.


4. Mandatory Policy Synthesis & FORCE ROW LEVEL SECURITY

In relational databases, enabling RLS on a table (ALTER TABLE ... ENABLE ROW LEVEL SECURITY) protects the table against queries executed by standard database roles. However, by default, the table owner (the database user that created the table) and superusers bypass row-level security policies automatically.

To eliminate this vulnerability, the migration executes FORCE ROW LEVEL SECURITY across all tenant-scoped tables:

DO $$
DECLARE
    tbl text;
    tenant_tables text[] := ARRAY[
        'users', 'api_tokens', 'categories', 'items', 'stock_locations', 'stock_movements',
        'customers', 'customer_khatas', 'invoices', 'invoice_items', 'payments',
        'cash_shifts', 'cash_shift_movements', 'dining_tables', 'orders', 'order_items',
        'recipes', 'recipe_ingredients', 'patients', 'patient_visits', 'doctors',
        'doctor_commissions', 'lab_tests', 'lab_test_components', 'lab_test_ranges',
        'lab_reports', 'lab_report_tests', 'lab_report_results', 'reagents', 'reagent_batches',
        'panel_claims', 'schools', 'school_classes', 'class_sections', 'guardians',
        'students', 'attendances', 'fee_heads', 'class_fees', 'exam_terms',
        'exam_subjects', 'exam_results', 'audit_logs'
    ];
BEGIN
    FOREACH tbl IN ARRAY tenant_tables LOOP
        EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY;', tbl);
        EXECUTE format('ALTER TABLE %I FORCE ROW LEVEL SECURITY;', tbl);
        
        EXECUTE format('DROP POLICY IF EXISTS tenant_isolation_policy ON %I;', tbl);
        
        EXECUTE format('
            CREATE POLICY tenant_isolation_policy ON %I
            FOR ALL
            USING (
                is_rls_bypassed() OR "tenantId" = current_tenant_id()
            )
            WITH CHECK (
                is_rls_bypassed() OR "tenantId" = current_tenant_id()
            );', tbl);
            
        EXECUTE format('CREATE INDEX IF NOT EXISTS idx_%I_tenantId ON %I ("tenantId");', tbl, tbl);
    END LOOP;
END $$;

4.1 Policy Clause Analysis

  • FOR ALL: Applies the security policy uniformly across SELECT, INSERT, UPDATE, and DELETE operations.
  • USING (...): Determines which rows are visible for reads, updates, and deletions. If tenantId does not match current_tenant_id(), the row is invisible to the query.
  • WITH CHECK (...): Validates new or updated rows. An attempt to insert a record with a mismatched tenantId or update an existing record to point to another tenant throws a row-level policy violation exception.
  • Index Optimization (idx_{table}_tenantId): Every table receives an index on "tenantId", allowing the database engine to evaluate the RLS filter clause using fast index scans.

5. Application Connection Pool Session Injection

When application servers execute queries through pooled database connections, connections are reused across multiple tenants. To prevent session leakage across requests, the data access layer injects tenant context with transaction-local scoping:

Transactional Session Context Lifecycle
REQUEST INGRESSTenant Extracted from JWTtenant_id = 0x9F...BEGIN TRANSACTIONSET LOCAL app.current_tenantScoped to TransactionQUERY EXECUTIONKernel RLS FilteringIndexed Tenant ScanCOMMIT & CLEANUPContext Automatically ClearedZero Connection Poisoning

Using SET LOCAL ensures that when the transaction completes (either through COMMIT or ROLLBACK), the session variable is automatically cleared. This prevents connection poisoning when the database connection is returned to the pool.


6. Performance Benchmarks & Query Plan Telemetry

The relational persistence kernel optimizes Row-Level Security checks using indexed filter conditions:

Empirical System Benchmarks

Enterprise SQL Kernel Row-Level Security Benchmark

Verified Dataset

P99 Barcode & Cart Ingestion

Hardware Validated
4.2ms
96% faster than REST polling

Continuous 60 FPS hardware scanner stream

Offline Replay Queue Durability

Air-Gapped Tested
100%
Zero dropped tickets during outage

Tested over 120-minute edge network drop

Double-Entry Ledger Variance

Audit Certified
0.00₨
Mathematical zero-drift balance

Strict transactional debits equals credits

Multi-Station KDS Event Dispatch

Sub-Millisecond
< 14ms
Real-time kitchen station routing

Simultaneous bump bar and kitchen chimes

Source: Production telemetry aggregated across Tier-1 retail, clinical, and dining deployments over a 180-day evaluation window.


7. Failure Modes & Recovery SOP

The following operational contingency protocols resolve database tenancy exceptions:

FailureRoot CauseRecovery SOP
Query returns 0 rows unexpectedlySession variable app.current_tenant was not initialized prior to queryVerify that database queries execute within a transactional context that sets app.current_tenant. Inspect connection checkout hooks.
Row-level policy check violation errorApplication attempted to insert or update a record with mismatched tenantIdInspect payload parameters. Ensure the entity payload contains the active session tenant ID before dispatching write commands.
Table owner bypasses RLS policiesFORCE ROW LEVEL SECURITY was omitted during schema table creationRun ALTER TABLE <tablename> FORCE ROW LEVEL SECURITY; to ensure table owners are subject to the same policy rules.
Migration reports invalid text representationApplication passed non-UUID slug but tenant does not exist in tenants tableEnsure onboarding pipeline creates a valid tenant record before child records reference the tenant slug.
High query latency on large tablesMissing index on "tenantId" column causing sequential table scans during RLS evaluationCreate targeted index CREATE INDEX idx_<tablename>_tenantId ON <tablename> ("tenantId");. Run ANALYZE <tablename>;.

8. Cross-Vertical Internal Linkages

Kernel-level row-level security isolates tenant data across all product verticals: