Spaces:
Running

File size: 1,529 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""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))