feat(B2): add tenant model + migrations 035/036 + RLS policies
Migration 035: tenants table with 'Schaeffler' default seed. Migration 036: tenant_id FK on all tables, RLS policies, backfill. New domains/tenants/ with CRUD router (admin only). All domain models extended with tenant_id FK. core/database.py: get_db_for_tenant with RLS context setter. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
"""Add tenants table.
|
||||
|
||||
Revision ID: 035
|
||||
Revises: 034
|
||||
Create Date: 2026-03-06
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
revision = '035'
|
||||
down_revision = '034'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'tenants',
|
||||
sa.Column('id', UUID(as_uuid=True), primary_key=True,
|
||||
server_default=sa.text('gen_random_uuid()')),
|
||||
sa.Column('name', sa.String(200), nullable=False),
|
||||
sa.Column('slug', sa.String(100), nullable=False, unique=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=False, server_default='true'),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False,
|
||||
server_default=sa.text('NOW()')),
|
||||
)
|
||||
# Seed default tenant — all existing data will be assigned to this tenant
|
||||
op.execute("""
|
||||
INSERT INTO tenants (name, slug, is_active)
|
||||
VALUES ('Schaeffler', 'schaeffler', true)
|
||||
""")
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table('tenants')
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Add tenant_id FK to all tables + enable Row Level Security.
|
||||
|
||||
Revision ID: 036
|
||||
Revises: 035
|
||||
Create Date: 2026-03-06
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
revision = '036'
|
||||
down_revision = '035'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# Tables that receive tenant_id + RLS.
|
||||
# product_variants was removed in migration 027, so we check existence before acting.
|
||||
TENANT_TABLES = [
|
||||
"users",
|
||||
"orders",
|
||||
"order_items",
|
||||
"order_lines",
|
||||
"products",
|
||||
"cad_files",
|
||||
"materials",
|
||||
"material_aliases",
|
||||
"render_templates",
|
||||
"output_types",
|
||||
"pricing_tiers",
|
||||
"audit_log",
|
||||
"templates",
|
||||
"product_variants", # dropped in 027 — handled with existence check
|
||||
]
|
||||
|
||||
|
||||
def _table_exists(table_name: str) -> bool:
|
||||
"""Check if a table exists in the public schema."""
|
||||
conn = op.get_bind()
|
||||
result = conn.execute(
|
||||
sa.text(
|
||||
"SELECT 1 FROM information_schema.tables "
|
||||
"WHERE table_schema = 'public' AND table_name = :t"
|
||||
),
|
||||
{"t": table_name},
|
||||
)
|
||||
return result.fetchone() is not None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Grant BYPASSRLS to the DB user if possible (superuser op — ignore if insufficient privilege)
|
||||
op.execute("""
|
||||
DO $$
|
||||
BEGIN
|
||||
EXECUTE 'ALTER ROLE ' || current_user || ' BYPASSRLS';
|
||||
EXCEPTION WHEN insufficient_privilege THEN
|
||||
RAISE NOTICE 'Could not set BYPASSRLS — run manually as superuser if needed';
|
||||
END;
|
||||
$$;
|
||||
""")
|
||||
|
||||
for table in TENANT_TABLES:
|
||||
if not _table_exists(table):
|
||||
continue
|
||||
|
||||
# 1. Add nullable tenant_id column
|
||||
op.add_column(
|
||||
table,
|
||||
sa.Column(
|
||||
"tenant_id",
|
||||
UUID(as_uuid=True),
|
||||
sa.ForeignKey("tenants.id"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
),
|
||||
)
|
||||
|
||||
# 2. Backfill with the default 'schaeffler' tenant
|
||||
op.execute(
|
||||
f"UPDATE {table} "
|
||||
"SET tenant_id = (SELECT id FROM tenants WHERE slug = 'schaeffler')"
|
||||
)
|
||||
|
||||
# 3. Make NOT NULL now that every row has a value
|
||||
op.alter_column(table, "tenant_id", nullable=False)
|
||||
|
||||
# 4. Enable Row Level Security
|
||||
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
||||
|
||||
# 5. Main isolation policy: tenant_id must match current session tenant
|
||||
op.execute(f"""
|
||||
CREATE POLICY tenant_isolation ON {table}
|
||||
USING (
|
||||
tenant_id = current_setting('app.current_tenant_id', true)::uuid
|
||||
)
|
||||
""")
|
||||
|
||||
# 6. Admin bypass policy: allows queries when setting is 'bypass'
|
||||
op.execute(f"""
|
||||
CREATE POLICY admin_bypass ON {table}
|
||||
USING (
|
||||
current_setting('app.current_tenant_id', true) = 'bypass'
|
||||
)
|
||||
""")
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Grant BYPASSRLS so the downgrade itself can see all rows
|
||||
op.execute("""
|
||||
DO $$
|
||||
BEGIN
|
||||
EXECUTE 'ALTER ROLE ' || current_user || ' BYPASSRLS';
|
||||
EXCEPTION WHEN insufficient_privilege THEN
|
||||
RAISE NOTICE 'Could not set BYPASSRLS';
|
||||
END;
|
||||
$$;
|
||||
""")
|
||||
|
||||
for table in reversed(TENANT_TABLES):
|
||||
if not _table_exists(table):
|
||||
continue
|
||||
|
||||
op.execute(f"DROP POLICY IF EXISTS admin_bypass ON {table}")
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||
op.execute(f"ALTER TABLE {table} DISABLE ROW LEVEL SECURITY")
|
||||
op.drop_column(table, "tenant_id")
|
||||
Reference in New Issue
Block a user