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:
2026-06-28 11:00:18 +09:00
co-authored by Claude Sonnet 4.6
parent f9c4fb4eba
commit e4e5c70422
16 changed files with 1175 additions and 21 deletions
+140 -2
View File
@@ -1,11 +1,17 @@
"""PortfolioHubReadAdapter HTTP contract tests (REQ-027 AC-1/AC-4)."""
"""PortfolioHubReadAdapter HTTP contract tests (REQ-027 AC-1/AC-4; REQ-112 AC-1~7)."""
from __future__ import annotations
import logging
import httpx
import pytest
from trex_core.adapters.portfolio.hub_read import PortfolioHubReadAdapter
from trex_core.application.portfolio import PortfolioHubUnavailableError
from trex_core.application.portfolio import (
BrokerCredentialPayload,
PortfolioHubUnavailableError,
TradingContext,
)
def _client(handler):
@@ -242,3 +248,135 @@ def test_get_realized_pnl_fallback_total_from_items_sum():
adapter = PortfolioHubReadAdapter("https://pf.test", client=_client(handler))
result = adapter.get_realized_pnl("pf-1", "2026-06-26", "2026-06-26")
assert abs(result.total_realized_pnl - (95.0 + 198.0)) < 1e-6
# ---------------------------------------------------------------------------
# REQ-112: fetch_broker_credential
# ---------------------------------------------------------------------------
_UNSET = object() # sentinel for "use default"
def _user_info_with_broker(trading_enabled=True, credential_payload=_UNSET):
"""Build a /v1/user_info response with broker field.
credential_payload defaults to a valid dict.
Pass credential_payload=None explicitly to produce null in JSON (AC-3).
"""
cp = (
{"app_key": "PSAK...", "app_secret": "secret-value"}
if credential_payload is _UNSET
else credential_payload # None → null in JSON
)
return {
"daemon_id": "d-7",
"trading_enabled": trading_enabled,
"broker": {
"account_ref": "12345678-01",
"credential_payload": cp,
"credential_version": 3,
},
}
def test_fetch_broker_credential_returns_trading_context(caplog):
"""REQ-112 AC-1: 유효한 broker + trading_enabled=True → TradingContext 반환."""
def handler(req: httpx.Request) -> httpx.Response:
return httpx.Response(200, json=_user_info_with_broker(trading_enabled=True))
adapter = PortfolioHubReadAdapter("https://pf.test", token="tok",
client=_client(handler))
ctx = adapter.fetch_broker_credential()
assert isinstance(ctx, TradingContext)
assert ctx.trading_enabled is True
assert ctx.broker is not None
assert isinstance(ctx.broker, BrokerCredentialPayload)
assert ctx.broker.account_ref == "12345678-01"
assert ctx.broker.app_key == "PSAK..."
assert ctx.broker.app_secret == "secret-value"
assert ctx.broker.credential_version == 3
def test_fetch_broker_credential_broker_null_returns_none_broker():
"""REQ-112 AC-2: broker: null → TradingContext(broker=None, trading_enabled=값)."""
def handler(req: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={
"daemon_id": "d-7",
"trading_enabled": False,
"broker": None,
})
adapter = PortfolioHubReadAdapter("https://pf.test", client=_client(handler))
ctx = adapter.fetch_broker_credential()
assert ctx.broker is None
assert ctx.trading_enabled is False
def test_fetch_broker_credential_credential_payload_null_returns_none_broker():
"""REQ-112 AC-3: credential_payload: null → TradingContext(broker=None)."""
def handler(req: httpx.Request) -> httpx.Response:
return httpx.Response(200, json=_user_info_with_broker(
trading_enabled=True, credential_payload=None,
))
adapter = PortfolioHubReadAdapter("https://pf.test", client=_client(handler))
ctx = adapter.fetch_broker_credential()
assert ctx.broker is None
assert ctx.trading_enabled is True
def test_fetch_broker_credential_network_error_raises_unavailable():
"""REQ-112 AC-4: 네트워크 오류 → PortfolioHubUnavailableError."""
def handler(req):
raise httpx.ConnectError("no route")
adapter = PortfolioHubReadAdapter("https://pf.test", client=_client(handler))
with pytest.raises(PortfolioHubUnavailableError):
adapter.fetch_broker_credential()
def test_fetch_broker_credential_403_raises_unavailable():
"""REQ-112 AC-4: 403 → PortfolioHubUnavailableError."""
def handler(req):
return httpx.Response(403, text="Forbidden")
adapter = PortfolioHubReadAdapter("https://pf.test", client=_client(handler))
with pytest.raises(PortfolioHubUnavailableError):
adapter.fetch_broker_credential()
def test_fetch_broker_credential_500_raises_unavailable():
"""REQ-112 AC-4: 500 → PortfolioHubUnavailableError."""
def handler(req):
return httpx.Response(500, text="Internal Server Error")
adapter = PortfolioHubReadAdapter("https://pf.test", client=_client(handler))
with pytest.raises(PortfolioHubUnavailableError):
adapter.fetch_broker_credential()
def test_fetch_broker_credential_whoami_still_works():
"""REQ-112 AC-5: fetch_broker_credential 추가 후 whoami() 계약 불변."""
def handler(req: httpx.Request) -> httpx.Response:
return httpx.Response(200, json=_user_info_with_broker())
adapter = PortfolioHubReadAdapter("https://pf.test", token="tok",
client=_client(handler))
# whoami should still work and return daemon_id
did = adapter.whoami()
assert did == "d-7"
def test_fetch_broker_credential_app_secret_not_in_logs(caplog):
"""REQ-112 AC-7: app_secret 평문이 로그에 노출되지 않는다 (NFR-2)."""
def handler(req: httpx.Request) -> httpx.Response:
return httpx.Response(200, json=_user_info_with_broker())
adapter = PortfolioHubReadAdapter("https://pf.test", token="tok",
client=_client(handler))
with caplog.at_level(logging.DEBUG):
adapter.fetch_broker_credential()
full_log = caplog.text
# app_secret value must not appear in any log output
assert "secret-value" not in full_log
+43 -2
View File
@@ -1,8 +1,16 @@
"""StubPortfolioRead tests (REQ-027 AC-2; REQ-109 AC-4 stub)."""
"""StubPortfolioRead tests (REQ-027 AC-2; REQ-109 AC-4 stub; REQ-112 AC-6 stub)."""
from __future__ import annotations
import pytest
from trex_core.adapters.portfolio.stub_read import StubPortfolioRead
from trex_core.application.portfolio import PortfolioItem, RealizedPnlResult
from trex_core.application.portfolio import (
BrokerCredentialPayload,
PortfolioHubUnavailableError,
PortfolioItem,
RealizedPnlResult,
TradingContext,
)
def test_stub_returns_fixed_universe_without_network():
@@ -72,3 +80,36 @@ def test_stub_realized_pnl_result_overridable():
assert result.total_realized_pnl == 12345.0
assert result.data_completeness_warning is True
assert result.items[0].symbol == "000660"
# ---------------------------------------------------------------------------
# REQ-112 AC-6: fetch_broker_credential stub — 무네트워크 고정반환
# ---------------------------------------------------------------------------
def test_stub_fetch_broker_credential_default_happy_path():
"""REQ-112 AC-6: 기본 stub은 유효한 TradingContext를 네트워크 없이 반환."""
stub = StubPortfolioRead()
ctx = stub.fetch_broker_credential()
assert isinstance(ctx, TradingContext)
assert ctx.trading_enabled is True
assert ctx.broker is not None
assert isinstance(ctx.broker, BrokerCredentialPayload)
assert ctx.broker.account_ref == "stub-account"
assert ctx.broker.app_key == "stub-app-key"
assert ctx.broker.app_secret == "stub-app-secret"
def test_stub_fetch_broker_credential_overridable_context():
"""REQ-112 AC-6: trading_context 교체 가능 — broker=None 시나리오."""
custom = TradingContext(broker=None, trading_enabled=False)
stub = StubPortfolioRead(trading_context=custom)
ctx = stub.fetch_broker_credential()
assert ctx.broker is None
assert ctx.trading_enabled is False
def test_stub_fetch_broker_credential_raises_when_configured():
"""REQ-112 AC-4 stub: fetch_broker_raises=True → PortfolioHubUnavailableError."""
stub = StubPortfolioRead(fetch_broker_raises=True)
with pytest.raises(PortfolioHubUnavailableError):
stub.fetch_broker_credential()