Files
portfolio-hub/app/api/v1_user_info.py
T
genichinandClaude Opus 4.8 6b812b6035 fix: GET /v1/user_info 500 on missing broker_credentials table (issue #9)
trex-core reported GET /v1/user_info returning 500 for valid service/daemon
tokens (whoami → daemon_id), degrading the daemon and holding new trades. The
reported hypothesis (service-token None deref) was a misdiagnosis. Root cause:

  app/api/v1_user_info.py: credentials = repo.list_broker_credentials(...)
  psycopg.errors.UndefinedTable: relation "broker_credentials" does not exist

The broker_credentials table was missing and the handler only caught
AttributeError, so the DB error propagated to a bare 500.

Two fixes:
1. Handler now degrades gracefully when broker-credential lookup fails — returns
   empty brokers and still serves daemon_id/user_id/permission, which do not
   depend on broker credentials. This is what trex-core's whoami needs.
2. ensure_schema() now also CREATE TABLE broker_credentials (same shape as
   migration 20260502_0014). ensure_schema-bootstrapped DBs were missing it,
   since previously only the alembic path created it.

Added tests/test_v1.py regression: broker-credential lookup raising a DB error
must yield HTTP 200 with daemon_id, not 500. Verified against the real DB
(was 500 → now 200 + daemon_id). Full suite 377 passed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-06 10:17:30 +09:00

89 lines
3.4 KiB
Python

"""GET /v1/user_info — service-token authenticated user info endpoint."""
from __future__ import annotations
import json
import logging
from fastapi import APIRouter, Depends, HTTPException, status
from app.core.auth import AuthContext, require_read
from app.core.config import Settings, get_settings
from app.core.encryption import InvalidToken, decrypt_payload
from app.repositories.factory import get_portfolio_repository_from_settings
from app.schemas.v1 import BrokerItem, UserInfoResponse
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/v1", tags=["v1"])
def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthContext:
if auth.token_source != "db" or auth.token_type != "service":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Service token required",
)
return auth
@router.get("/user_info", response_model=UserInfoResponse)
def get_user_info(
auth: AuthContext = Depends(_require_service_token),
settings: Settings = Depends(get_settings),
) -> UserInfoResponse:
repo = get_portfolio_repository_from_settings(settings)
try:
user = repo.get_user(auth.user_id) # type: ignore[arg-type]
# Fetch broker credentials and decrypt
brokers: list[BrokerItem] = []
try:
credentials = repo.list_broker_credentials(auth.user_id) # type: ignore[arg-type]
enc_key: str | None = None
for cred in credentials:
credential_payload = None
try:
if enc_key is None:
enc_key = settings.require_credential_encryption_key()
raw = decrypt_payload(enc_key, cred.encrypted_payload)
credential_payload = json.loads(raw)
except (InvalidToken, RuntimeError, Exception) as exc:
logger.warning("credential decryption failed for broker %s: %s", cred.broker, exc)
brokers.append(BrokerItem(
broker=cred.broker,
account_ref=cred.account_ref,
credential_payload=credential_payload,
credential_version=cred.credential_version,
last_rotated_at=cred.last_rotated_at,
))
except AttributeError:
# repo does not implement list_broker_credentials yet (mock or older impl)
pass
except Exception as exc: # pragma: no cover - defensive
# Broker credentials are supplementary. A failure here (e.g. missing
# broker_credentials table, DB error) must not crash /v1/user_info —
# the critical fields (daemon_id, user_id, permission) do not depend
# on broker credentials. Degrade gracefully with an empty broker list.
logger.warning("broker credential lookup failed; returning empty brokers: %s", exc)
brokers = []
finally:
if callable(getattr(type(repo), "close", None)):
repo.close()
disabled_reason: str | None = None
if not user.is_active:
disabled_reason = "account_inactive"
return UserInfoResponse(
runtime_id=auth.runtime_id,
daemon_id=auth.daemon_id,
trading_enabled=user.is_active,
disabled_reason=disabled_reason,
brokers=brokers,
user_id=user.id,
username=user.username,
email=user.email,
permission=user.permission,
)