feat: 멀티테넌트 1단계 — 사용자별 KIS 계좌·포트폴리오·수동매매 (MULTI_TENANT_ENABLED 기본 OFF)
설계: docs/multi_tenant_design.md / 검수: docs/multi_tenant_phase1_review.md (High 0, MT=False 배포 가능)
데이터·인프라
- user_kis_credentials(Fernet 암호화, PBKDF2 키 파생, key_version), stock_bans_v2 신설,
portfolio/trade_history/active_trades/trade_journals/trading_sessions 등 user_id nullable 추가
- alembic 0009~0011(idempotent, legacy owner 백필). main.py 기동 시 portfolio.user_id 스키마 검사(H1)
- Jenkinsfile: DB Migration 을 Deploy 앞으로, alembic 이력 없으면 stamp 0008 후 upgrade(N1)
- bootstrap: users 비어 있으면 BOOTSTRAP_ADMIN_* 로 관리자 시드 + .env KIS 자격증명 이관 + 백필(SAVEPOINT)
백엔드
- core/crypto.py, core/tenant_auth.py(get_current_user — 비활성 사용자 401, API 키→legacy owner,
deny_non_owner_session_when_mt), core/dt_utils.py
- services/tenant: context, kis_pool, registry(UserContextRegistry, 락 최소화·복호화 to_thread), risk_factory
- KoreaInvestmentAPI.for_user(사용자별 인스턴스, 토큰캐시 users/{id}/, 시세는 공용 위임)
- trade_executor.safe_place_order_v2(사용자별 락/세마포어, legacy ctx 는 기존 키)
- mdd_manager/loss_tracker _v2 + ban_until tz-aware/naive 경계 정규화(레거시 경로 버그 포함 수정)
- db_worker: payload user_id 옵션 필터, upsert_stock_ban_v2, legacy ActiveTrade 조회 LIMIT 1
- API: /account/credentials(등록·마스킹조회·삭제·연결테스트·자동매매), /auth/admin/tenant/*,
/portfolio/v2(조회·요약·sync·buy·sell), /trades/v2(+pending). PortfolioResponse Optional 수정
프론트
- /account 내 계좌 설정, useTenantMode(세션=v2 / API키=legacy, 미확정 시 쿼리·버튼 비활성),
계좌 미등록 인라인 안내, v2 매수/매도/거래이력 분기
테스트: tests/integration(격리 Postgres, KIS 전면 mock) 20 passed / 1 xfailed(0012 이전 제약)
2단계(스케줄러 사용자화·legacy 라우터 격리) 전까지 MULTI_TENANT_ENABLED=True 전환 금지
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
65
backend/alembic/versions/0009_user_kis_credentials.py
Normal file
65
backend/alembic/versions/0009_user_kis_credentials.py
Normal file
@@ -0,0 +1,65 @@
|
||||
"""add user_kis_credentials table (multi-tenant phase 1)
|
||||
|
||||
Revision ID: 0009
|
||||
Revises: 0008
|
||||
Create Date: 2026-09-21
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0009"
|
||||
down_revision = "0008"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
exists = conn.execute(sa.text(
|
||||
"SELECT 1 FROM information_schema.tables WHERE table_name='user_kis_credentials'"
|
||||
)).fetchone()
|
||||
if exists:
|
||||
return # create_all 로 이미 생성됨
|
||||
op.create_table(
|
||||
"user_kis_credentials",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("mode", sa.String(10), nullable=False),
|
||||
sa.Column("app_key_enc", sa.Text(), nullable=False),
|
||||
sa.Column("app_secret_enc", sa.Text(), nullable=False),
|
||||
sa.Column("account_no_enc", sa.Text(), nullable=False),
|
||||
sa.Column("account_product_code", sa.String(2), nullable=False, server_default="01"),
|
||||
sa.Column("app_key_hash", sa.String(64), nullable=False),
|
||||
sa.Column("app_key_hint", sa.String(8), nullable=True),
|
||||
sa.Column("is_enabled", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("auto_trade_enabled", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("last_verified_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("key_version", sa.Integer(), nullable=False, server_default="1"),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_user_kis_credentials_user_id", "user_kis_credentials", ["user_id"], unique=True
|
||||
)
|
||||
op.create_index(
|
||||
"ix_user_kis_credentials_app_key_hash", "user_kis_credentials", ["app_key_hash"], unique=True
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# L3: 테이블이 `create_all`(SQLAlchemy 모델의 `unique=True` 컬럼)로 먼저 생성된
|
||||
# 경우 실제로는 named index가 아니라 unique constraint(`..._key`)로 존재해
|
||||
# `drop_index`가 실패한다. 존재할 때만 드롭한다.
|
||||
conn = op.get_bind()
|
||||
for index_name in (
|
||||
"ix_user_kis_credentials_app_key_hash",
|
||||
"ix_user_kis_credentials_user_id",
|
||||
):
|
||||
exists = conn.execute(sa.text(
|
||||
"SELECT 1 FROM pg_indexes WHERE tablename='user_kis_credentials' AND indexname=:name"
|
||||
), {"name": index_name}).fetchone()
|
||||
if exists:
|
||||
op.drop_index(index_name, table_name="user_kis_credentials")
|
||||
op.drop_table("user_kis_credentials")
|
||||
79
backend/alembic/versions/0010_add_user_id_nullable.py
Normal file
79
backend/alembic/versions/0010_add_user_id_nullable.py
Normal file
@@ -0,0 +1,79 @@
|
||||
"""add nullable user_id to tenant-scoped tables + stock_bans_v2 (multi-tenant phase 1)
|
||||
|
||||
Revision ID: 0010
|
||||
Revises: 0009
|
||||
Create Date: 2026-09-21
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0010"
|
||||
down_revision = "0009"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# (table, index_name)
|
||||
_USER_ID_TABLES = [
|
||||
"portfolio",
|
||||
"trade_history",
|
||||
"active_trades",
|
||||
"trade_journals",
|
||||
"trading_sessions",
|
||||
"mcp_tool_calls",
|
||||
"claude_analysis_log",
|
||||
]
|
||||
|
||||
|
||||
def _has_column(conn, table: str, column: str) -> bool:
|
||||
return conn.execute(sa.text(
|
||||
"SELECT 1 FROM information_schema.columns WHERE table_name=:t AND column_name=:c"
|
||||
), {"t": table, "c": column}).fetchone() is not None
|
||||
|
||||
|
||||
def _has_table(conn, table: str) -> bool:
|
||||
return conn.execute(sa.text(
|
||||
"SELECT 1 FROM information_schema.tables WHERE table_name=:t"
|
||||
), {"t": table}).fetchone() is not None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
|
||||
for table in _USER_ID_TABLES:
|
||||
if not _has_table(conn, table):
|
||||
continue # create_all 이전 스키마 없음 — 스킵(다음 실행에서 재시도)
|
||||
if _has_column(conn, table, "user_id"):
|
||||
continue # create_all 로 이미 생성됨
|
||||
op.add_column(
|
||||
table,
|
||||
sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
|
||||
)
|
||||
op.create_index(f"ix_{table}_user_id", table, ["user_id"])
|
||||
|
||||
if not _has_table(conn, "stock_bans_v2"):
|
||||
op.create_table(
|
||||
"stock_bans_v2",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
|
||||
sa.Column("stock_code", sa.String(20), nullable=False),
|
||||
sa.Column("consecutive_losses", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("ban_until", sa.DateTime(), nullable=True),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
op.create_index("ix_stock_bans_v2_user_id", "stock_bans_v2", ["user_id"])
|
||||
op.create_index("ix_stock_bans_v2_stock_code", "stock_bans_v2", ["stock_code"])
|
||||
op.create_unique_constraint(
|
||||
"uq_stock_bans_v2_user_stock", "stock_bans_v2", ["user_id", "stock_code"]
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
if _has_table(conn, "stock_bans_v2"):
|
||||
op.drop_table("stock_bans_v2")
|
||||
for table in _USER_ID_TABLES:
|
||||
if _has_table(conn, table) and _has_column(conn, table, "user_id"):
|
||||
op.drop_index(f"ix_{table}_user_id", table_name=table)
|
||||
op.drop_column(table, "user_id")
|
||||
73
backend/alembic/versions/0011_backfill_legacy_owner.py
Normal file
73
backend/alembic/versions/0011_backfill_legacy_owner.py
Normal file
@@ -0,0 +1,73 @@
|
||||
"""backfill legacy owner user_id + stock_bans -> stock_bans_v2 (multi-tenant phase 1)
|
||||
|
||||
Revision ID: 0011
|
||||
Revises: 0010
|
||||
Create Date: 2026-09-21
|
||||
|
||||
- legacy_owner = users 중 is_admin=True, id 최소인 사용자.
|
||||
- 없으면 스킵 (앱 기동 시 ensure_bootstrap_admin() 또는 관리자 API
|
||||
POST /auth/admin/tenant/migrate-legacy 가 동일 로직으로 재실행 가능 — idempotent).
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0011"
|
||||
down_revision = "0010"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_BACKFILL_TABLES = [
|
||||
"portfolio",
|
||||
"trade_history",
|
||||
"active_trades",
|
||||
"trade_journals",
|
||||
"trading_sessions",
|
||||
"mcp_tool_calls",
|
||||
"claude_analysis_log",
|
||||
]
|
||||
|
||||
|
||||
def _has_table(conn, table: str) -> bool:
|
||||
return conn.execute(sa.text(
|
||||
"SELECT 1 FROM information_schema.tables WHERE table_name=:t"
|
||||
), {"t": table}).fetchone() is not None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
conn = op.get_bind()
|
||||
|
||||
if not _has_table(conn, "users"):
|
||||
return
|
||||
|
||||
owner_row = conn.execute(sa.text(
|
||||
"SELECT id FROM users WHERE is_admin = TRUE ORDER BY id LIMIT 1"
|
||||
)).fetchone()
|
||||
if owner_row is None:
|
||||
return # 관리자 미존재 — migrate-legacy API 또는 ensure_bootstrap_admin() 이 지연 백필
|
||||
|
||||
owner_id = owner_row[0]
|
||||
|
||||
for table in _BACKFILL_TABLES:
|
||||
if not _has_table(conn, table):
|
||||
continue
|
||||
conn.execute(sa.text(
|
||||
f"UPDATE {table} SET user_id = :owner WHERE user_id IS NULL"
|
||||
), {"owner": owner_id})
|
||||
|
||||
if _has_table(conn, "stock_bans") and _has_table(conn, "stock_bans_v2"):
|
||||
conn.execute(sa.text(
|
||||
"""
|
||||
INSERT INTO stock_bans_v2 (user_id, stock_code, consecutive_losses, ban_until, updated_at)
|
||||
SELECT :owner, stock_code, consecutive_losses, ban_until, updated_at
|
||||
FROM stock_bans
|
||||
ON CONFLICT (user_id, stock_code) DO NOTHING
|
||||
"""
|
||||
), {"owner": owner_id})
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# 데이터 백필 롤백은 위험(다른 정상 데이터와 구분 불가) — no-op.
|
||||
# 필요 시 수동으로 UPDATE ... SET user_id = NULL WHERE user_id = <owner_id> 실행.
|
||||
pass
|
||||
Reference in New Issue
Block a user