"""Row-level security helpers used by Alembic migrations. Every tenant table gets ``ENABLE`` + ``FORCE ROW LEVEL SECURITY`` so even the table owner is filtered (only superusers and BYPASSRLS roles skip RLS; the app role is neither). """ from __future__ import annotations from sqlalchemy import text from sqlalchemy.engine import Connection from core.db.base import Base CURRENT_TENANT = "NULLIF(current_setting('app.tenant_id', true), '')::uuid" CURRENT_USER_ID = "NULLIF(current_setting('app.user_id', true), '')::uuid" def tenant_policy_sql(table: str, column: str = "tenant_id") -> list[str]: return [ f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY", f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY", f"DROP POLICY IF EXISTS tenant_isolation ON {table}", ( f"CREATE POLICY tenant_isolation ON {table} " f"USING ({column} = {CURRENT_TENANT}) " f"WITH CHECK ({column} = {CURRENT_TENANT})" ), ] def enable_tenant_rls(conn: Connection, table: str, column: str = "tenant_id") -> None: for stmt in tenant_policy_sql(table, column): conn.execute(text(stmt)) def tenant_tables() -> list[str]: """Names of all mapped tables whose model declares ``__rls__ = True``.""" names: list[str] = [] for mapper in Base.registry.mappers: cls = mapper.class_ if getattr(cls, "__rls__", False): names.append(cls.__tablename__) return sorted(set(names))