You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat(db): Integrate PostgreSQL Row-Level Security (RLS) and automatic tenant isolation in SQLAlchemy models #26
Context & Problem Statement
docsgraph-server is a multi-tenant platform where document security is paramount. A single leakage of one tenant's contract data to another tenant constitutes a catastrophic failure. Relying on developers to manually append WHERE tenant_id = :current_tenant to every database query is error-prone.
We need to implement automatic query interception at the SQLAlchemy session level or integrate PostgreSQL's native Row Level Security (RLS) combined with setting local session variables (SET LOCAL app.current_tenant = ...) on each checkout from the DB pool.
Technical Implementation Blueprint
Alembic RLS Migration: Write a migration script that enables RLS on all syncable tables and defines a policy:
sql
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_policy ON documents
USING (tenant_id = current_setting('app.current_tenant', true))
WITH CHECK (tenant_id = current_setting('app.current_tenant', true));
SQLAlchemy Event Listener: Add a listener in docsgraph_server/db/session.py hook to after_begin event. Whenever a session begins a transaction, read the current tenant ID from a Python context variable (ContextVar) set by the auth middleware and set it in the Postgres local session state.
python
from sqlalchemy import event
@event.listens_for(AsyncSession, "after_begin")
def set_postgres_tenant(session, transaction):
tenant_id = current_tenant_var.get(None)
if tenant_id:
# Set tenant ID in Postgres session environment context
session.execute(text(f"SET LOCAL app.current_tenant = '{tenant_id}'"))
Auth Context Middleware: Add middleware that parses JWT, extracts the workspace/tenant ID, and writes it to current_tenant_var.
Acceptance Criteria
Any manual raw SQL execution or ORM query executed within a session automatically inherits the context tenant filter.
Running a query without setting the tenant context variable must return empty results (Postgres RLS blocks visibility).
Integration tests verify that even if a tenant attempts to read document ID belonging to another tenant via API, Postgres returns a Row Not Found or Access Denied error.
Activity