fix: RLS fail-closed migration + per-tenant startup code

This commit is contained in:
Agent Zero
2026-07-31 01:31:41 +02:00
parent 7fbbe420bd
commit 0692fce2e4
5 changed files with 41 additions and 26 deletions
@@ -17,7 +17,7 @@ Bootstrap and startup must use:
Revision ID: 0084
Revises: 0083
""
"""
from alembic import op
from sqlalchemy import text
@@ -75,21 +75,22 @@ def upgrade() -> None:
conn.execute(text(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY"))
# Fail-closed tenant isolation policy
# NULLIF converts empty string to NULL comparison yields NULL no rows returned
# NULLIF converts empty string to NULL -> comparison yields NULL -> no rows returned
# This is fail-closed: missing tenant context = no access
conn.execute(text(f"""
CREATE POLICY {table}_tenant_isolation
ON {table}
AS PERMISSIVE
FOR ALL
TO crm_api
USING (
tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid
)
WITH CHECK (
tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid
)
"""))
policy_sql = (
"CREATE POLICY " + table + "_tenant_isolation "
"ON " + table + " "
"AS PERMISSIVE "
"FOR ALL "
"TO crm_api "
"USING ("
"tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid"
") "
"WITH CHECK ("
"tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid"
")"
)
conn.execute(text(policy_sql))
def downgrade() -> None: