feat(V1-API): implement TREX-Basic consumer API contract with encryption and persistence
- Add V1 API endpoints: assets, ledger, user-info - Implement Fernet-based credential payload encryption (req-010) - Extend health response schema with runtime info (req-004) - Add service token runtime ID issuance (req-005) - Implement database schema migration for V1 API (req-009) - Add comprehensive test coverage for V1 endpoints - Update SRS with 10 new requirements (REQ-004 through REQ-011) - Create batch planning, design, and verification for BAT-001 - Integrate review-discovery StagePilot skill - Update documentation indices and baseline specs
This commit is contained in:
+25
-3
@@ -1,10 +1,32 @@
|
||||
"""Health and readiness endpoints."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
_KST = timezone(timedelta(hours=9))
|
||||
|
||||
@router.get("/health")
|
||||
def healthcheck() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str
|
||||
service: str
|
||||
version: str
|
||||
checked_at: str
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse)
|
||||
def healthcheck() -> HealthResponse:
|
||||
settings = get_settings()
|
||||
return HealthResponse(
|
||||
status="ok",
|
||||
service="portfolio-hub",
|
||||
version=settings.app_version,
|
||||
checked_at=datetime.now(_KST).isoformat(),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""GET /v1/assets — service-token authenticated asset list endpoint."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.core.auth import AuthContext, require_read
|
||||
from app.repositories.factory import get_portfolio_repository_from_settings
|
||||
from app.repositories.portfolio_repository import PortfolioRepository
|
||||
from app.schemas.v1 import AssetItem, AssetsResponse
|
||||
|
||||
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("/assets", response_model=AssetsResponse)
|
||||
def list_assets(auth: AuthContext = Depends(_require_service_token)) -> AssetsResponse:
|
||||
from app.core.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
repo = get_portfolio_repository_from_settings(settings)
|
||||
try:
|
||||
portfolios = repo.list_portfolios_with_strategies(
|
||||
owner_user_id=None,
|
||||
include_disabled=False,
|
||||
)
|
||||
finally:
|
||||
if callable(getattr(type(repo), "close", None)):
|
||||
repo.close()
|
||||
|
||||
items = [
|
||||
AssetItem(
|
||||
asset_id=p.portfolio_id,
|
||||
broker=p.broker,
|
||||
market=p.market,
|
||||
symbol=p.symbol,
|
||||
name=p.name,
|
||||
status=p.status,
|
||||
cash_balance=p.cash_balance,
|
||||
asset_quantity=p.asset_quantity,
|
||||
price=p.price,
|
||||
profit_buffer=p.profit_buffer,
|
||||
active_strategy_id=p.active_strategy_id,
|
||||
available_strategies=p.avabile_strategies,
|
||||
tags=p.tags,
|
||||
owner_user_id=p.owner_user_id,
|
||||
created_at=p.created_at,
|
||||
updated_at=p.updated_at,
|
||||
last_trade_at=p.last_trade_at,
|
||||
)
|
||||
for p in portfolios
|
||||
]
|
||||
return AssetsResponse(assets=items, total=len(items))
|
||||
@@ -0,0 +1,66 @@
|
||||
"""POST /v1/assets/{asset_id}/ledger/trades — idempotent ledger trade recording."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.core.auth import AuthContext, require_read
|
||||
from app.repositories.factory import get_portfolio_repository_from_settings
|
||||
from app.schemas.v1 import LedgerTradeRequest, LedgerTradeResponse
|
||||
|
||||
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.post(
|
||||
"/assets/{asset_id}/ledger/trades",
|
||||
response_model=LedgerTradeResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def record_ledger_trade(
|
||||
asset_id: str,
|
||||
body: LedgerTradeRequest,
|
||||
auth: AuthContext = Depends(_require_service_token),
|
||||
) -> LedgerTradeResponse:
|
||||
from app.core.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
repo = get_portfolio_repository_from_settings(settings)
|
||||
try:
|
||||
trade, created = repo.insert_ledger_trade(
|
||||
asset_id=asset_id,
|
||||
order_id=body.order_id,
|
||||
execution_id=body.execution_id,
|
||||
side=body.side,
|
||||
quantity=float(body.quantity),
|
||||
price=float(body.price),
|
||||
executed_at=body.executed_at,
|
||||
fee_amount=float(body.fee_amount),
|
||||
tax_amount=float(body.tax_amount),
|
||||
)
|
||||
finally:
|
||||
if callable(getattr(type(repo), "close", None)):
|
||||
repo.close()
|
||||
|
||||
return LedgerTradeResponse(
|
||||
ledger_entry_id=trade.ledger_entry_id,
|
||||
asset_id=trade.asset_id,
|
||||
order_id=trade.order_id,
|
||||
execution_id=trade.execution_id,
|
||||
side=trade.side,
|
||||
quantity=trade.quantity,
|
||||
price=trade.price,
|
||||
fee_amount=trade.fee_amount,
|
||||
tax_amount=trade.tax_amount,
|
||||
executed_at=trade.executed_at,
|
||||
recorded_at=trade.recorded_at,
|
||||
created=created,
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""GET /v1/user_info — service-token authenticated user info endpoint."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.core.auth import AuthContext, require_read
|
||||
from app.repositories.factory import get_portfolio_repository_from_settings
|
||||
from app.schemas.v1 import UserInfoResponse
|
||||
|
||||
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)) -> UserInfoResponse:
|
||||
if not auth.runtime_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="runtime_id not assigned to this token",
|
||||
)
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
repo = get_portfolio_repository_from_settings(settings)
|
||||
try:
|
||||
user = repo.get_user(auth.user_id) # type: ignore[arg-type]
|
||||
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(
|
||||
user_id=user.id,
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
permission=user.permission,
|
||||
is_active=user.is_active,
|
||||
disabled_reason=disabled_reason,
|
||||
runtime_id=auth.runtime_id,
|
||||
)
|
||||
Reference in New Issue
Block a user