feat(bat-053): 그날-시작 KIS 인증정보 fetch + fail-safe 로드 (REQ-112~115)
REQ-112: BrokerCredentialPayload/TradingContext 데이터클래스 + PortfolioHubReadPort.fetch_broker_credential() 포트 메서드 + hub_read 어댑터(_fetch_user_info 헬퍼 추출) + stub_read 결정론 stub REQ-113: DaemonInstanceConfig/DaemonConfig.credential_fetch_enabled opt-in(기본 False) + TOML 파싱 + break-glass(TREX_KIS_BROKER_BREAK_GLASS) 감지 REQ-114: SnapshotScheduler._maybe_fetch_credential() — fail-closed 3조건(unavailable/broker-null/trading_disabled) + CRITICAL 알람 DAY_START_LOAD_FAILED + IntentService entry_allowed_fn 게이트(BuyIntent 차단, SellIntent 통과) REQ-115: 그날 고정 캐시(_cached_credential/_credential_date) — 동일 날짜 재fetch 방지 + app_secret 메모리 한정(Redis 미기록) 스텁 기반 구현: 실 portfolio-hub/네트워크 없이 AC 전부 단위 테스트. 회귀: credential_fetch_enabled=False(기본) 경로 byte-for-byte 보존. 745 passed, 47 skipped (0 failed). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
This commit is contained in:
@@ -20,10 +20,12 @@ from typing import Optional
|
||||
import httpx
|
||||
|
||||
from trex_core.application.portfolio import (
|
||||
BrokerCredentialPayload,
|
||||
PortfolioHubUnavailableError,
|
||||
PortfolioItem,
|
||||
RealizedPnlItem,
|
||||
RealizedPnlResult,
|
||||
TradingContext,
|
||||
)
|
||||
|
||||
|
||||
@@ -57,7 +59,12 @@ class PortfolioHubReadAdapter:
|
||||
return httpx.get(url, params=params, headers=self._headers(),
|
||||
timeout=self._timeout)
|
||||
|
||||
def whoami(self) -> str:
|
||||
def _fetch_user_info(self) -> dict:
|
||||
"""Internal helper: GET /v1/user_info and return parsed JSON body.
|
||||
|
||||
Raises PortfolioHubUnavailableError on network error, non-2xx, or parse
|
||||
failure. Shared by whoami() and fetch_broker_credential() (REQ-112).
|
||||
"""
|
||||
url = f"{self._base_url}/v1/user_info"
|
||||
try:
|
||||
resp = self._get(url)
|
||||
@@ -73,11 +80,52 @@ class PortfolioHubReadAdapter:
|
||||
body = resp.json()
|
||||
except ValueError as exc:
|
||||
raise PortfolioHubUnavailableError("user_info response not JSON") from exc
|
||||
did = body.get("daemon_id") if isinstance(body, dict) else None
|
||||
if not isinstance(body, dict):
|
||||
raise PortfolioHubUnavailableError("user_info response not a JSON object")
|
||||
return body
|
||||
|
||||
def whoami(self) -> str:
|
||||
body = self._fetch_user_info()
|
||||
did = body.get("daemon_id")
|
||||
if not did:
|
||||
raise PortfolioHubUnavailableError("user_info missing daemon_id")
|
||||
return str(did)
|
||||
|
||||
def fetch_broker_credential(self) -> TradingContext:
|
||||
"""GET /v1/user_info — broker credential + trading_enabled (REQ-112).
|
||||
|
||||
Returns TradingContext. broker=None when broker field is null or
|
||||
credential_payload is null (decryption failure — treated as absent).
|
||||
NFR-2: app_secret is never logged in plaintext here.
|
||||
Raises PortfolioHubUnavailableError on network/non-2xx/403/parse errors.
|
||||
"""
|
||||
body = self._fetch_user_info()
|
||||
trading_enabled: bool = bool(body.get("trading_enabled", False))
|
||||
broker_raw = body.get("broker")
|
||||
if not isinstance(broker_raw, dict):
|
||||
# broker: null — no credential assigned for this daemon
|
||||
return TradingContext(broker=None, trading_enabled=trading_enabled)
|
||||
|
||||
credential_payload = broker_raw.get("credential_payload")
|
||||
if not isinstance(credential_payload, dict):
|
||||
# credential_payload: null — decryption failure; treat as absent
|
||||
return TradingContext(broker=None, trading_enabled=trading_enabled)
|
||||
|
||||
app_key = credential_payload.get("app_key") or ""
|
||||
app_secret = credential_payload.get("app_secret") or ""
|
||||
account_ref = broker_raw.get("account_ref") or ""
|
||||
raw_ver = broker_raw.get("credential_version")
|
||||
credential_version = int(raw_ver) if raw_ver is not None else None
|
||||
|
||||
payload = BrokerCredentialPayload(
|
||||
account_ref=str(account_ref),
|
||||
app_key=str(app_key),
|
||||
app_secret=str(app_secret),
|
||||
credential_version=credential_version,
|
||||
)
|
||||
# NFR-2: do NOT log app_secret. Log only account_ref + app_key prefix.
|
||||
return TradingContext(broker=payload, trading_enabled=trading_enabled)
|
||||
|
||||
def get_portfolios(self, daemon_id: str) -> list[PortfolioItem]:
|
||||
url = f"{self._base_url}/v1/portfolios"
|
||||
try:
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
"""Deterministic stub for PortfolioHubReadPort (REQ-027 AC-2; REQ-109 stub)."""
|
||||
"""Deterministic stub for PortfolioHubReadPort (REQ-027 AC-2; REQ-109 stub;
|
||||
REQ-112 broker credential stub)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from trex_core.application.portfolio import (
|
||||
BrokerCredentialPayload,
|
||||
PortfolioHubUnavailableError,
|
||||
PortfolioItem,
|
||||
RealizedPnlItem,
|
||||
RealizedPnlResult,
|
||||
TradingContext,
|
||||
)
|
||||
|
||||
|
||||
@@ -18,6 +22,10 @@ class StubPortfolioRead:
|
||||
|
||||
REQ-109: `get_realized_pnl` returns a deterministic fixed RealizedPnlResult.
|
||||
Tests can override `self.realized_pnl_result` to inject custom fixtures.
|
||||
|
||||
REQ-112: `fetch_broker_credential` returns a deterministic TradingContext.
|
||||
Tests can override `self.trading_context` or set `self.fetch_broker_raises`
|
||||
to simulate failure scenarios without network.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -25,6 +33,8 @@ class StubPortfolioRead:
|
||||
daemon_id: str = "stub-daemon",
|
||||
items: list[PortfolioItem] | None = None,
|
||||
realized_pnl_result: Optional[RealizedPnlResult] = None,
|
||||
trading_context: Optional[TradingContext] = None,
|
||||
fetch_broker_raises: bool = False,
|
||||
) -> None:
|
||||
self._daemon_id = daemon_id
|
||||
self.items: list[PortfolioItem] = list(items or [
|
||||
@@ -61,6 +71,19 @@ class StubPortfolioRead:
|
||||
data_completeness_warning=False,
|
||||
total_realized_pnl=50_000.0,
|
||||
)
|
||||
# REQ-112: fixed TradingContext for tests (overridable).
|
||||
# Default: valid credential + trading_enabled=True (happy path).
|
||||
self.trading_context: TradingContext = trading_context or TradingContext(
|
||||
broker=BrokerCredentialPayload(
|
||||
account_ref="stub-account",
|
||||
app_key="stub-app-key",
|
||||
app_secret="stub-app-secret",
|
||||
credential_version=1,
|
||||
),
|
||||
trading_enabled=True,
|
||||
)
|
||||
# REQ-112 AC-4 scenario: set True to simulate PortfolioHubUnavailableError.
|
||||
self.fetch_broker_raises: bool = fetch_broker_raises
|
||||
|
||||
def get_portfolios(self, daemon_id: str) -> list[PortfolioItem]:
|
||||
# Stub does not filter by daemon_id — every test universe is scoped.
|
||||
@@ -79,3 +102,13 @@ class StubPortfolioRead:
|
||||
) -> RealizedPnlResult:
|
||||
"""REQ-109 AC-4: deterministic fixed result, no network required."""
|
||||
return self.realized_pnl_result
|
||||
|
||||
def fetch_broker_credential(self) -> TradingContext:
|
||||
"""REQ-112 AC-6: deterministic fixed TradingContext, no network required.
|
||||
|
||||
Override self.trading_context to inject custom test fixtures.
|
||||
Set self.fetch_broker_raises = True to simulate PortfolioHubUnavailableError.
|
||||
"""
|
||||
if self.fetch_broker_raises:
|
||||
raise PortfolioHubUnavailableError("stub: simulated broker credential fetch failure")
|
||||
return self.trading_context
|
||||
|
||||
Reference in New Issue
Block a user