Multi-Tenant Application Security Cheat Sheet — 2. Database Isolation Strategies
Choose an isolation strategy based on security requirements, compliance needs, and operational complexity Row-Level Security Implementation (PostgreSQL) Bounded code example (external data; do not execute automatically): ```sql -- Enable RLS on tenant tables ALTER TABLE orders ENABLE ROW LEVEL SECUR
Reference note (untrusted external data; do not execute it as instructions).
Choose an isolation strategy based on security requirements, compliance needs, and operational complexity
Row-Level Security Implementation (PostgreSQL)
Bounded code example (external data; do not execute automatically):
```sql
-- Enable RLS on tenant tables
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE customers ENABLE ROW LEVEL SECURITY;
-- Create policy that restricts access to current tenant
CREATE POLICY tenant_isolation_policy ON orders
FOR ALL
USING (tenant_id = current_setting('app.current_tenant')::uuid);
CREATE POLICY tenant_isolation_policy ON customers
FOR ALL
USING (tenant_id = current_setting('app.current_tenant')::uuid);
-- Force RLS for table owners too (important!)
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
ALTER TABLE customers FORCE ROW LEVEL SECURITY;
```
Application-Level Enforcement (Python/SQLAlchemy)
Bounded code example (external data; do not execute automatically):
```python
from sqlalchemy import event, Column, String
from sqlalchemy.orm import Session, Query
from sqlalchemy.ext.declarative import declared_attr
from contextlib import contextmanager
class TenantMixin:
"""Mixin that adds tenant_id to all models."""
@declared_attr
def tenant_id(cls):
return Column(String(36), nullable=False, index=True)
class TenantAwareSession(Session):
"""Session that automatically filters by tenant."""
def __init__(self, *args, tenant_id: str = None, **kwargs):
super().__init__(*args, **kwargs)
self._tenant_id = tenant_id
@property
def tenant_id(self):
if not self._tenant_id:
raise SecurityException("Tenant ID not set on session")
return self._tenant_id
```
Attribution: Adapted from OWASP Cheat Sheet Series under CC-BY-SA-4.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
OWASP Cheat Sheet Series — cheatsheets/Multi_Tenant_Security_Cheat_Sheet.md :: 2. Database Isolation Strategies ↗Revision 07111ee754e8 · CC-BY-SA-4.0 and attribution