66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
"""Fix DB roles — add default privileges and grants for all tables.
|
|
|
|
Revision ID: 0061
|
|
Revises: 0060
|
|
Create Date: 2026-07-29
|
|
|
|
Problems fixed:
|
|
1. crm_runtime role has no grants on tables created after migration 0044
|
|
2. No ALTER DEFAULT PRIVILEGES for future tables
|
|
3. Auth tables (users, tenants, user_tenants, user_groups) need SELECT grants
|
|
4. New permission/guest/policy tables need grants
|
|
"""
|
|
|
|
from alembic import op
|
|
|
|
revision = "0061"
|
|
down_revision = "0060"
|
|
branch_labels = None
|
|
depends_on = None
|
|
|
|
|
|
def upgrade() -> None:
|
|
# Grant privileges on all existing tables to crm_runtime
|
|
op.execute("GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO crm_runtime")
|
|
|
|
# Grant USAGE on sequences
|
|
op.execute("GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO crm_runtime")
|
|
|
|
# Default privileges for future tables created by migration owner
|
|
op.execute("ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO crm_runtime")
|
|
op.execute("ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO crm_runtime")
|
|
|
|
# Ensure RLS is enabled on all tenant tables that have tenant_id
|
|
# (covers tables created after migration 0044 that missed RLS)
|
|
tenant_tables = [
|
|
"entity_permissions",
|
|
"entity_policies",
|
|
"permission_templates",
|
|
"guest_users",
|
|
"contact_folder_permissions",
|
|
]
|
|
for table in tenant_tables:
|
|
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
|
# Create tenant isolation policy if not exists
|
|
op.execute(f"""
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM pg_policy
|
|
WHERE polname = '{table}_tenant_isolation'
|
|
AND polrelid = '{table}'::regclass
|
|
) THEN
|
|
CREATE POLICY {table}_tenant_isolation ON {table}
|
|
FOR ALL
|
|
USING (tenant_id = current_setting('app.current_tenant_id', true)::uuid)
|
|
WITH CHECK (tenant_id = current_setting('app.current_tenant_id', true)::uuid);
|
|
END IF;
|
|
END $$;
|
|
""")
|
|
|
|
|
|
def downgrade() -> None:
|
|
# Revoke default privileges
|
|
op.execute("ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE SELECT, INSERT, UPDATE, DELETE ON TABLES FROM crm_runtime")
|
|
op.execute("ALTER DEFAULT PRIVILEGES IN SCHEMA public REVOKE USAGE, SELECT ON SEQUENCES FROM crm_runtime")
|