설계: 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>
175 lines
7.0 KiB
Python
175 lines
7.0 KiB
Python
"""앱 기동 시 멀티테넌트 부트스트랩 (관리자 시드 + legacy 자격증명 이관 + 백필).
|
|
|
|
`main.py` lifespan 에서 `create_all()` 직후 1회 호출된다(§ CLAUDE.md 예외: 부트스트랩
|
|
시드·자격증명 저장은 단일 트랜잭션 직접 커밋 허용 — 실시간 계층 아님).
|
|
|
|
모든 단계는 독립적으로 try/except 로 감싸 실패해도 앱 부팅을 막지 않는다.
|
|
alembic 0011 과 동일한 백필 로직을 idempotent 하게 재수행 — alembic 이 CLI 로만
|
|
실행되는 배포 환경에서도(예: 최초 로그인 전) 앱 기동 시 스스로 보정한다.
|
|
"""
|
|
import logging
|
|
|
|
import bcrypt
|
|
from sqlalchemy import select, text
|
|
|
|
from app.core.config import settings
|
|
from app.core.crypto import current_key_version, encrypt, is_encryption_configured
|
|
from app.core.database import AsyncSessionLocal
|
|
from app.models.models import User, UserKisCredential
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# alembic 0011 과 동일한 백필 대상 테이블 목록
|
|
_BACKFILL_TABLES = [
|
|
"portfolio",
|
|
"trade_history",
|
|
"active_trades",
|
|
"trade_journals",
|
|
"trading_sessions",
|
|
"mcp_tool_calls",
|
|
"claude_analysis_log",
|
|
]
|
|
|
|
|
|
def _hash_password(password: str) -> str:
|
|
try:
|
|
from app.api.endpoints.auth import _hash_password as _auth_hash_password
|
|
|
|
return _auth_hash_password(password)
|
|
except ImportError:
|
|
# 순환 임포트 등으로 재사용 불가할 때만 동일 로직 복제 (auth.py:_hash_password 와 동치)
|
|
return bcrypt.hashpw(password.encode()[:72], bcrypt.gensalt()).decode()
|
|
|
|
|
|
async def _seed_admin_if_empty(session) -> None:
|
|
"""users 테이블이 비어 있고 BOOTSTRAP_ADMIN_PASSWORD 가 설정되어 있으면 관리자 시드."""
|
|
if not settings.BOOTSTRAP_ADMIN_PASSWORD:
|
|
return
|
|
total = (await session.execute(select(User))).scalars().first()
|
|
if total is not None:
|
|
return # 이미 사용자 존재 — 시드 불필요
|
|
|
|
user = User(
|
|
username=settings.BOOTSTRAP_ADMIN_USERNAME,
|
|
password_hash=_hash_password(settings.BOOTSTRAP_ADMIN_PASSWORD),
|
|
is_active=True,
|
|
is_admin=True,
|
|
)
|
|
session.add(user)
|
|
await session.commit()
|
|
logger.info(f"[Bootstrap] 부트스트랩 관리자 계정 생성 완료: {settings.BOOTSTRAP_ADMIN_USERNAME}")
|
|
|
|
|
|
async def _get_legacy_owner(session) -> User | None:
|
|
result = await session.execute(
|
|
select(User).where(User.is_admin.is_(True)).order_by(User.id.asc()).limit(1)
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
|
|
async def _seed_legacy_kis_credential(session, owner: User) -> None:
|
|
"""legacy owner 에게 .env KIS 자격증명이 아직 이관되지 않았으면 암호화해 저장."""
|
|
existing = await session.execute(
|
|
select(UserKisCredential).where(UserKisCredential.user_id == owner.id)
|
|
)
|
|
if existing.scalar_one_or_none() is not None:
|
|
return # 이미 이관됨
|
|
|
|
app_key = settings.KOREA_INVESTMENT_APP_KEY
|
|
app_secret = settings.KOREA_INVESTMENT_APP_SECRET
|
|
account_no = (settings.KOREA_INVESTMENT_ACCOUNT_NUMBER or "").replace("-", "")
|
|
|
|
if not (app_key and app_secret and account_no):
|
|
logger.info("[Bootstrap] .env KIS 자격증명 미설정 — legacy 자격증명 이관 스킵")
|
|
return
|
|
if not is_encryption_configured():
|
|
logger.warning("[Bootstrap] CREDENTIALS_ENCRYPTION_KEY/SECRET_KEY 미설정 — legacy 자격증명 이관 스킵")
|
|
return
|
|
|
|
import hashlib
|
|
|
|
app_key_hash = hashlib.sha256(app_key.encode()).hexdigest()
|
|
dup = await session.execute(
|
|
select(UserKisCredential).where(UserKisCredential.app_key_hash == app_key_hash)
|
|
)
|
|
if dup.scalar_one_or_none() is not None:
|
|
logger.warning("[Bootstrap] 동일 앱키가 이미 등록되어 있어 legacy 이관 스킵")
|
|
return
|
|
|
|
account_product_code = account_no[8:10] if len(account_no) >= 10 else "01"
|
|
|
|
credential = UserKisCredential(
|
|
user_id=owner.id,
|
|
mode=settings.KIS_MODE,
|
|
app_key_enc=encrypt(app_key),
|
|
app_secret_enc=encrypt(app_secret),
|
|
account_no_enc=encrypt(account_no),
|
|
account_product_code=account_product_code,
|
|
app_key_hash=app_key_hash,
|
|
app_key_hint=app_key[:6],
|
|
is_enabled=True,
|
|
auto_trade_enabled=settings.AUTO_TRADE_ENABLED,
|
|
last_verified_at=None,
|
|
key_version=current_key_version(),
|
|
)
|
|
session.add(credential)
|
|
await session.commit()
|
|
logger.info(f"[Bootstrap] legacy KIS 자격증명 이관 완료 (owner={owner.username}, app_key={app_key[:6]}…)")
|
|
|
|
|
|
async def _backfill_legacy_owner_ids(session, owner_id: int) -> None:
|
|
"""alembic 0011 과 동일한 백필을 idempotent 하게 재수행 (user_id IS NULL 인 행만 대상).
|
|
|
|
M8: PostgreSQL은 트랜잭션 내 한 문장이 실패(예: 테이블/컬럼 미존재)하면 세션이
|
|
`InFailedSqlTransaction` 상태가 되어 이후 모든 문장이 연쇄 실패한다. 문장별로
|
|
`session.begin_nested()`(SAVEPOINT)로 감싸 한 테이블의 실패가 나머지 테이블
|
|
백필을 막지 않게 한다.
|
|
"""
|
|
for table in _BACKFILL_TABLES:
|
|
try:
|
|
async with session.begin_nested():
|
|
await session.execute(
|
|
text(f"UPDATE {table} SET user_id = :owner WHERE user_id IS NULL"),
|
|
{"owner": owner_id},
|
|
)
|
|
except Exception as e: # 컬럼/테이블이 아직 없는 초기 상태 등 — 개별 실패는 무시하고 계속
|
|
logger.debug(f"[Bootstrap] {table} 백필 스킵: {e}")
|
|
|
|
try:
|
|
async with session.begin_nested():
|
|
await session.execute(
|
|
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},
|
|
)
|
|
except Exception as e:
|
|
logger.debug(f"[Bootstrap] stock_bans_v2 백필 스킵: {e}")
|
|
|
|
await session.commit()
|
|
|
|
|
|
async def ensure_bootstrap_admin() -> None:
|
|
"""앱 기동 시 1회 호출. 실패해도 예외를 전파하지 않는다(로그만 남김)."""
|
|
try:
|
|
async with AsyncSessionLocal() as session:
|
|
await _seed_admin_if_empty(session)
|
|
except Exception as e:
|
|
logger.error(f"[Bootstrap] 관리자 계정 시드 실패 (non-critical): {e}")
|
|
|
|
try:
|
|
async with AsyncSessionLocal() as session:
|
|
owner = await _get_legacy_owner(session)
|
|
if owner is None:
|
|
logger.info("[Bootstrap] 관리자 계정 없음 — legacy 자격증명 이관/백필 스킵")
|
|
return
|
|
await _seed_legacy_kis_credential(session, owner)
|
|
await _backfill_legacy_owner_ids(session, owner.id)
|
|
except Exception as e:
|
|
logger.error(f"[Bootstrap] legacy 자격증명 이관/백필 실패 (non-critical): {e}")
|