feat(m0): 后端骨架 + Web/安卓前端骨架 + 设计文档
- backend: FastAPI 应用工厂、统一错误信封、JWT、短信登录、工作区/成员/邀请、幂等中间件 - alembic 0001: workspace/member/invitation/audit_log/app_user + RLS 策略 + 双角色 GRANT - tests: 认证/工作区/租户隔离/幂等 四组用例(尚未在本机执行) - web: React18+Vite 骨架(登录、工作区、邀请落地页) - android: Compose 骨架(登录、工作区列表) - 2.Design: PRODUCT-PLAN / ROADMAP-M0-M1 / NAMING / DEVELOPMENT
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"""Alembic 环境:用**迁移角色**(owner)连接,与应用的受限角色分开。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.engine import Connection
|
||||
from sqlalchemy.ext.asyncio import async_engine_from_config
|
||||
|
||||
from app.config import get_settings
|
||||
from app.models import Base
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
config.set_main_option("sqlalchemy.url", get_settings().migration_database_url)
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=config.get_main_option("sqlalchemy.url"),
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
compare_type=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection: Connection) -> None:
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
compare_type=True,
|
||||
# RLS 策略、GRANT 这类"非表结构"变更 autogenerate 看不见,必须手写
|
||||
include_schemas=False,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
connectable = async_engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,27 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
${imports if imports else ""}
|
||||
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: str | None = ${repr(down_revision)}
|
||||
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
|
||||
depends_on: str | Sequence[str] | None = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,197 @@
|
||||
"""M0 初始结构:workspace / app_user / member / invitation / audit_log + 行级安全。
|
||||
|
||||
注意:RLS 策略是**安全边界**,不是优化项。改这个文件请同时改
|
||||
`tests/test_tenant_isolation.py`,并在 PR 里说明为什么。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "0001"
|
||||
down_revision: str | None = None
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
APP_ROLE = "dadao_app"
|
||||
|
||||
HELPER_SQL = """
|
||||
CREATE OR REPLACE FUNCTION app_ws_id() RETURNS uuid
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT nullif(current_setting('app.ws_id', true), '')::uuid
|
||||
$$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION app_user_id() RETURNS uuid
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT nullif(current_setting('app.user_id', true), '')::uuid
|
||||
$$;
|
||||
"""
|
||||
|
||||
POLICY_SQL = f"""
|
||||
-- ── workspace:本租户 OR 我是其成员(用于"我加入了哪些工作区")──
|
||||
ALTER TABLE workspace ENABLE ROW LEVEL SECURITY;
|
||||
CREATE POLICY workspace_isolation ON workspace
|
||||
USING (
|
||||
id = app_ws_id()
|
||||
OR id IN (SELECT m.workspace_id FROM member m WHERE m.user_id = app_user_id())
|
||||
)
|
||||
WITH CHECK (id = app_ws_id());
|
||||
|
||||
-- ── member:本租户成员 OR 我自己那条 ──
|
||||
ALTER TABLE member ENABLE ROW LEVEL SECURITY;
|
||||
CREATE POLICY member_isolation ON member
|
||||
USING (workspace_id = app_ws_id() OR user_id = app_user_id())
|
||||
WITH CHECK (workspace_id = app_ws_id());
|
||||
|
||||
-- ── invitation ──
|
||||
ALTER TABLE invitation ENABLE ROW LEVEL SECURITY;
|
||||
CREATE POLICY invitation_isolation ON invitation
|
||||
USING (workspace_id = app_ws_id())
|
||||
WITH CHECK (workspace_id = app_ws_id());
|
||||
|
||||
-- ── audit_log:只增不改,租户内可见 ──
|
||||
ALTER TABLE audit_log ENABLE ROW LEVEL SECURITY;
|
||||
CREATE POLICY audit_log_isolation ON audit_log
|
||||
USING (workspace_id = app_ws_id())
|
||||
WITH CHECK (workspace_id = app_ws_id());
|
||||
|
||||
-- ── 授权:应用角色没有 DDL、没有 BYPASSRLS,只能读写到自己该看的数据 ──
|
||||
GRANT USAGE ON SCHEMA public TO {APP_ROLE};
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON
|
||||
workspace, app_user, member, invitation, audit_log TO {APP_ROLE};
|
||||
ALTER DEFAULT PRIVILEGES FOR ROLE dadao_owner IN SCHEMA public
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {APP_ROLE};
|
||||
"""
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(HELPER_SQL)
|
||||
|
||||
op.create_table(
|
||||
"app_user",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column("phone", sa.String(32), nullable=False, unique=True),
|
||||
sa.Column("nickname", sa.String(64), nullable=False, server_default=""),
|
||||
sa.Column("avatar_url", sa.String(512)),
|
||||
sa.Column("status", sa.String(16), nullable=False, server_default="active"),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("version", sa.Integer, nullable=False, server_default="1"),
|
||||
)
|
||||
op.create_index("ix_app_user_phone", "app_user", ["phone"])
|
||||
|
||||
op.create_table(
|
||||
"workspace",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column("name", sa.String(64), nullable=False),
|
||||
sa.Column("slug", sa.String(64), nullable=False, unique=True),
|
||||
sa.Column("plan", sa.String(16), nullable=False, server_default="free"),
|
||||
sa.Column(
|
||||
"owner_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("app_user.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("version", sa.Integer, nullable=False, server_default="1"),
|
||||
sa.Column("deleted_at", sa.DateTime(timezone=True)),
|
||||
)
|
||||
op.create_index("ix_workspace_owner", "workspace", ["owner_id"])
|
||||
|
||||
op.create_table(
|
||||
"member",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column(
|
||||
"workspace_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("workspace.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"user_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("app_user.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("role", sa.String(16), nullable=False, server_default="member"),
|
||||
sa.Column("status", sa.String(16), nullable=False, server_default="active"),
|
||||
sa.Column("joined_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("version", sa.Integer, nullable=False, server_default="1"),
|
||||
sa.UniqueConstraint("workspace_id", "user_id", name="uq_member_ws_user"),
|
||||
sa.CheckConstraint("role IN ('owner','admin','member','guest')", name="ck_member_role"),
|
||||
sa.CheckConstraint("status IN ('active','removed')", name="ck_member_status"),
|
||||
)
|
||||
op.create_index("ix_member_user", "member", ["user_id"])
|
||||
op.create_index("ix_member_created", "member", ["created_at", "id"])
|
||||
|
||||
op.create_table(
|
||||
"invitation",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column(
|
||||
"workspace_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("workspace.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("code", sa.String(32), nullable=False),
|
||||
sa.Column("role", sa.String(16), nullable=False, server_default="member"),
|
||||
sa.Column(
|
||||
"invited_by",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("app_user.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("accepted_at", sa.DateTime(timezone=True)),
|
||||
sa.Column(
|
||||
"accepted_by",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("app_user.id", ondelete="SET NULL"),
|
||||
),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("version", sa.Integer, nullable=False, server_default="1"),
|
||||
sa.UniqueConstraint("code", name="uq_invitation_code"),
|
||||
)
|
||||
op.create_index("ix_invitation_ws", "invitation", ["workspace_id"])
|
||||
|
||||
op.create_table(
|
||||
"audit_log",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
|
||||
sa.Column(
|
||||
"workspace_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("workspace.id", ondelete="SET NULL"),
|
||||
),
|
||||
sa.Column(
|
||||
"actor_user_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("app_user.id", ondelete="SET NULL"),
|
||||
),
|
||||
sa.Column("action", sa.String(64), nullable=False),
|
||||
sa.Column("target_type", sa.String(32), nullable=False, server_default=""),
|
||||
sa.Column("target_id", sa.String(64), nullable=False, server_default=""),
|
||||
sa.Column("payload", postgresql.JSONB),
|
||||
sa.Column("ip", sa.String(64), nullable=False, server_default=""),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
|
||||
)
|
||||
op.create_index("ix_audit_ws_created", "audit_log", ["workspace_id", "created_at"])
|
||||
|
||||
op.execute(POLICY_SQL)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(f"REVOKE ALL ON workspace, app_user, member, invitation, audit_log FROM {APP_ROLE};")
|
||||
op.drop_table("audit_log")
|
||||
op.drop_table("invitation")
|
||||
op.drop_table("member")
|
||||
op.drop_table("workspace")
|
||||
op.drop_table("app_user")
|
||||
op.execute("DROP FUNCTION IF EXISTS app_ws_id(); DROP FUNCTION IF EXISTS app_user_id();")
|
||||
Reference in New Issue
Block a user