交付 FastAPI/Celery/Vue 薄壳、FORCE RLS、Compose 回环与 review 修复证据,关闭 M01 DONE_LOCAL。 Co-authored-by: Cursor <cursoragent@cursor.com>
67 lines
2.8 KiB
Python
67 lines
2.8 KiB
Python
"""Create platform tables with forced RLS.
|
|
|
|
Revision ID: 20261117_0001
|
|
Revises:
|
|
Create Date: 2026-11-17
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Sequence, Union
|
|
|
|
import sqlalchemy as sa
|
|
from alembic import op
|
|
from sqlalchemy.dialects import postgresql
|
|
|
|
revision: str = "20261117_0001"
|
|
down_revision: Union[str, None] = None
|
|
branch_labels: Union[str, Sequence[str], None] = None
|
|
depends_on: Union[str, Sequence[str], None] = None
|
|
|
|
APP_ROLE = "watchman_app"
|
|
|
|
|
|
def upgrade() -> None:
|
|
# gen_random_uuid() is built into PostgreSQL 13+; no pgcrypto required.
|
|
op.create_table(
|
|
"audit_events",
|
|
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
|
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
|
sa.Column("action", sa.String(length=128), nullable=False),
|
|
sa.Column("payload", postgresql.JSONB(astext_type=sa.Text()), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
sa.Column("idempotency_key", sa.String(length=128), nullable=False),
|
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
sa.UniqueConstraint("tenant_id", "idempotency_key", name="uq_audit_events_tenant_idem"),
|
|
)
|
|
op.create_table(
|
|
"run_records",
|
|
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
|
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
|
sa.Column("kind", sa.String(length=128), nullable=False),
|
|
sa.Column("status", sa.String(length=64), nullable=False),
|
|
sa.Column("detail", postgresql.JSONB(astext_type=sa.Text()), server_default=sa.text("'{}'::jsonb"), nullable=False),
|
|
sa.Column("idempotency_key", sa.String(length=128), nullable=False),
|
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
|
sa.UniqueConstraint("tenant_id", "idempotency_key", name="uq_run_records_tenant_idem"),
|
|
)
|
|
|
|
for table in ("audit_events", "run_records"):
|
|
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
|
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
|
|
op.execute(
|
|
f"""
|
|
CREATE POLICY tenant_isolation ON {table}
|
|
FOR ALL
|
|
TO {APP_ROLE}
|
|
USING (tenant_id = current_setting('app.tenant_id', true))
|
|
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
|
|
"""
|
|
)
|
|
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {table} TO {APP_ROLE}")
|
|
|
|
|
|
def downgrade() -> None:
|
|
for table in ("run_records", "audit_events"):
|
|
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
|
op.drop_table(table)
|