Skip to content

fix(tenant): add centralized tenant context enforcement for all DB op…#36

Merged
peterod99 merged 1 commit intomainfrom
claude/fix-admin-settings-sliders-GJwP9
Jan 6, 2026
Merged

fix(tenant): add centralized tenant context enforcement for all DB op…#36
peterod99 merged 1 commit intomainfrom
claude/fix-admin-settings-sliders-GJwP9

Conversation

@peterod99
Copy link
Copy Markdown
Owner

…erations

This is a comprehensive fix for the RLS tenant context issue that was causing silent failures across the app. The problem: database RLS policies require tenant_id = get_current_tenant_id(), but the DB session context wasn't always set before operations.

Changes:

  • Add centralized tenantAwareTables list as class property
  • Wrap all write operations (insert, update, delete, upsert) on tenant-aware tables to automatically call set_tenant_context RPC before execution
  • Also wrap select operations for consistent behavior
  • Preserve query builder chainability through method wrapping
  • Add logging for debugging tenant context issues

This fixes ~26 files that had potential RLS issues including:

  • Chat sessions and messages
  • Forum posts and comments
  • Marketing funnels and steps
  • Agent categories and automations
  • Company knowledge base
  • And many more tenant-aware tables

The fix works by intercepting the .then() method on Supabase query builders and ensuring tenant context is set before the actual query executes.

…erations

This is a comprehensive fix for the RLS tenant context issue that was
causing silent failures across the app. The problem: database RLS policies
require tenant_id = get_current_tenant_id(), but the DB session context
wasn't always set before operations.

Changes:
- Add centralized tenantAwareTables list as class property
- Wrap all write operations (insert, update, delete, upsert) on tenant-aware
  tables to automatically call set_tenant_context RPC before execution
- Also wrap select operations for consistent behavior
- Preserve query builder chainability through method wrapping
- Add logging for debugging tenant context issues

This fixes ~26 files that had potential RLS issues including:
- Chat sessions and messages
- Forum posts and comments
- Marketing funnels and steps
- Agent categories and automations
- Company knowledge base
- And many more tenant-aware tables

The fix works by intercepting the .then() method on Supabase query builders
and ensuring tenant context is set before the actual query executes.
@peterod99 peterod99 merged commit 105e6da into main Jan 6, 2026
1 check passed
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jan 6, 2026

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This change introduces centralized tenant context enforcement to the Supabase client. It replaces inline tenant handling with a centralized tenantAwareTables list, adds RPC-based tenant context enforcement via the new wrapWithTenantContextEnforcement method, and exports utility functions for tenant-scoped operations including the tenantAwareClient singleton and withTenantContext helper.

Changes

Cohort / File(s) Summary
Tenant Context Management
src/integrations/supabase/tenant-client.ts
Added centralized tenantAwareTables list for tracking RLS-enabled tables. Refactored createTableProxy to log tenant-violation warnings when accessing tenant-aware tables without context. Enhanced enhanceQueryBuilder to conditionally enforce tenant context for read/write operations. Introduced wrapWithTenantContextEnforcement method that wraps query builders with RPC-based set_tenant_context calls. Added withTenantContext helper function and exported tenantAwareClient singleton for tenant-scoped operations.

Sequence Diagrams

sequenceDiagram
    actor User
    participant App as Application
    participant Client as TenantAwareClient
    participant QB as QueryBuilder
    participant RPC as Supabase RPC
    participant DB as Database

    User->>App: Execute operation with tenantId
    App->>Client: withTenantContext(tenantId, operation)
    activate Client
    Client->>Client: Store previous tenant context
    
    rect rgba(100, 200, 100, 0.2)
        Note over Client,DB: Tenant Context Enforcement Phase
        App->>QB: Query (insert/update/delete/select)
        activate QB
        
        alt Tenant-Aware Table Detected
            QB->>Client: wrapWithTenantContextEnforcement()
            Client->>RPC: set_tenant_context(tenantId)
            activate RPC
            RPC-->>Client: Context set successfully
            deactivate RPC
        end
        
        QB->>DB: Execute query with tenant context
        activate DB
        DB-->>QB: Query result
        deactivate DB
        QB-->>App: Return result
        deactivate QB
    end
    
    Client->>Client: Restore previous tenant context
    deactivate Client
    App-->>User: Operation complete
Loading
sequenceDiagram
    participant App as Application
    participant Client as TenantAwareClient
    participant Proxy as Table Proxy
    
    App->>Client: Access table via createTableProxy()
    activate Client
    Client->>Proxy: Check if tenant-aware table
    
    alt Tenant-Aware Table without Context
        Proxy->>Proxy: Log tenant-violation warning
        Proxy-->>App: Return proxy (denied)
        Note over Proxy: Logs: pathname + simplified message
    else Tenant-Aware Table with Context
        Proxy->>Proxy: Confirm tenant-contextful access
        Proxy-->>App: Return proxy (allowed)
    end
    deactivate Client
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 A tenant-aware tale of tables and chains,
Where contexts flow through the query's veins,
RPC whispers "set_tenant_context" calls,
And proxies guard the database halls,
With wrappers and singletons, rabbits rejoice,
For tenants now speak with one unified voice! 🌳


📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Free

📥 Commits

Reviewing files that changed from the base of the PR and between d69c1ae and 6015ac2.

📒 Files selected for processing (1)
  • src/integrations/supabase/tenant-client.ts

Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants