feat(REQ-005): implement TrEx Basic V1 API contract with auth, assets, ledger, and user endpoints

- Add V1 API routes for assets, ledger, and user info with complete CRUD operations
- Implement authentication scopes and request validation via auth_routes.py
- Extend schemas with V1-specific models for accounts, holdings, and positions
- Add database queries and aggregations for P&L, performance, and account data
- Include comprehensive test coverage for all V1 endpoints and integration flows
- Update batch and release documentation with implementation and verification evidence
- Sync project structure and runtime flows per V1 API contract requirements

Closes implementation phase of BAT-001 (TrEx Basic V1 API Contract)
This commit is contained in:
2026-05-02 11:37:42 +00:00
parent ce63c75c9c
commit 3509606c7e
17 changed files with 1159 additions and 124 deletions
+25 -1
View File
@@ -12,6 +12,8 @@ from app.schemas.auth import (
AuthTokenResponse,
CreateClientTokenRequest,
IssuedClientTokenResponse,
IssueServiceTokenRequest,
IssueServiceTokenApiResponse,
LoginRequest,
TokenResponse,
)
@@ -117,4 +119,26 @@ def revoke_token(
service.revoke_token(auth_context, token_id)
except ValueError as exc:
_raise_auth_error(exc)
return Response(status_code=status.HTTP_204_NO_CONTENT)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.post("/service-tokens", response_model=IssueServiceTokenApiResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_admin)])
def issue_service_token(
payload: IssueServiceTokenRequest,
service: AuthService = Depends(get_auth_service),
) -> IssueServiceTokenApiResponse:
try:
result = service.issue_service_token(
payload.name,
payload.username,
permission=payload.permission,
expires_in_days=payload.expires_in_days,
no_expiry=payload.no_expiry,
)
except ValueError as exc:
_raise_auth_error(exc)
return IssueServiceTokenApiResponse(
token=result.token,
runtime_id=result.auth_token.runtime_id,
auth_token=_to_auth_token_response(result.auth_token),
)
+58 -24
View File
@@ -2,13 +2,17 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, status
import json
import logging
from fastapi import APIRouter, Depends, HTTPException, Query, 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
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/v1", tags=["v1"])
@@ -21,8 +25,21 @@ def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthCon
return auth
def _parse_strategy_params(strategy_set_config: str | None) -> dict:
if not strategy_set_config:
return {}
try:
parsed = json.loads(strategy_set_config)
return parsed if isinstance(parsed, dict) else {}
except (json.JSONDecodeError, TypeError):
return {}
@router.get("/assets", response_model=AssetsResponse)
def list_assets(auth: AuthContext = Depends(_require_service_token)) -> AssetsResponse:
def list_assets(
status_filter: str | None = Query(default=None, alias="status"),
auth: AuthContext = Depends(_require_service_token),
) -> AssetsResponse:
from app.core.config import get_settings
settings = get_settings()
@@ -32,30 +49,47 @@ def list_assets(auth: AuthContext = Depends(_require_service_token)) -> AssetsRe
owner_user_id=None,
include_disabled=False,
)
# Fetch strategy_params per portfolio
items = []
for p in portfolios:
# Optional status filter
if status_filter is not None and p.status != status_filter:
continue
strategy_params: dict = {}
if p.active_strategy_id:
try:
ss = repo.get_strategy_set(p.active_strategy_id)
if ss is not None:
strategy_params = _parse_strategy_params(ss.config)
except Exception:
logger.warning("strategy_set lookup failed for %s", p.active_strategy_id)
strategy_params = {}
items.append(
AssetItem(
asset_id=p.portfolio_id,
symbol=p.symbol,
market=p.market,
status=p.status,
cash=p.cash_balance,
quantity=p.asset_quantity,
broker_type=p.broker,
strategy_id=p.active_strategy_id,
strategy_params=strategy_params,
updated_at=p.updated_at,
name=p.name,
price=p.price,
profit_buffer=p.profit_buffer,
tags=p.tags,
owner_user_id=p.owner_user_id,
created_at=p.created_at,
last_trade_at=p.last_trade_at,
)
)
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))
+38 -2
View File
@@ -2,7 +2,9 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, status
from decimal import Decimal
from fastapi import APIRouter, Depends, HTTPException, Response, status
from app.core.auth import AuthContext, require_read
from app.repositories.factory import get_portfolio_repository_from_settings
@@ -20,6 +22,17 @@ def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthCon
return auth
def _payloads_match(existing, body: LedgerTradeRequest) -> bool:
"""Return True when the existing trade's payload matches the request body."""
return (
existing.side == body.side
and abs(existing.quantity - float(body.quantity)) < 1e-9
and abs(existing.price - float(body.price)) < 1e-9
and abs(existing.fee_amount - float(body.fee_amount)) < 1e-9
and abs(existing.tax_amount - float(body.tax_amount)) < 1e-9
)
@router.post(
"/assets/{asset_id}/ledger/trades",
response_model=LedgerTradeResponse,
@@ -28,6 +41,7 @@ def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthCon
def record_ledger_trade(
asset_id: str,
body: LedgerTradeRequest,
response: Response,
auth: AuthContext = Depends(_require_service_token),
) -> LedgerTradeResponse:
from app.core.config import get_settings
@@ -35,6 +49,15 @@ def record_ledger_trade(
settings = get_settings()
repo = get_portfolio_repository_from_settings(settings)
try:
# B-9: Validate asset_id (portfolio) existence
try:
repo.get(asset_id)
except Exception:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Asset not found: {asset_id}",
)
trade, created = repo.insert_ledger_trade(
asset_id=asset_id,
order_id=body.order_id,
@@ -50,6 +73,19 @@ def record_ledger_trade(
if callable(getattr(type(repo), "close", None)):
repo.close()
if not created:
# B-8: Check payload conflict → 409
if not _payloads_match(trade, body):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="Duplicate key with different payload",
)
# B-7: Same payload duplicate → 200 + status="duplicate"
response.status_code = status.HTTP_200_OK
trade_status = "duplicate"
else:
trade_status = "new"
return LedgerTradeResponse(
ledger_entry_id=trade.ledger_entry_id,
asset_id=trade.asset_id,
@@ -62,5 +98,5 @@ def record_ledger_trade(
tax_amount=trade.tax_amount,
executed_at=trade.executed_at,
recorded_at=trade.recorded_at,
created=created,
status=trade_status,
)
+41 -8
View File
@@ -2,12 +2,18 @@
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 UserInfoResponse
from app.schemas.v1 import BrokerItem, UserInfoResponse
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/v1", tags=["v1"])
@@ -21,19 +27,45 @@ def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthCon
@router.get("/user_info", response_model=UserInfoResponse)
def get_user_info(auth: AuthContext = Depends(_require_service_token)) -> UserInfoResponse:
def get_user_info(
auth: AuthContext = Depends(_require_service_token),
settings: Settings = Depends(get_settings),
) -> 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]
# 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
finally:
if callable(getattr(type(repo), "close", None)):
repo.close()
@@ -43,11 +75,12 @@ def get_user_info(auth: AuthContext = Depends(_require_service_token)) -> UserIn
disabled_reason = "account_inactive"
return UserInfoResponse(
runtime_id=auth.runtime_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,
is_active=user.is_active,
disabled_reason=disabled_reason,
runtime_id=auth.runtime_id,
)
+2
View File
@@ -53,6 +53,8 @@ def create_app(
@asynccontextmanager
async def lifespan(_: FastAPI):
_bootstrap_initial_user(settings, repository_factory)
if settings.db_enabled:
settings.require_credential_encryption_key()
yield
app = FastAPI(
+14
View File
@@ -1334,6 +1334,20 @@ class PostgresPortfolioRepository:
return None
return self._row_to_broker_credential(row)
def list_broker_credentials(self, user_id: str) -> list[BrokerCredential]:
with self._connect().cursor() as cur:
cur.execute(
"""
SELECT user_id, broker, account_ref, encrypted_payload, credential_version, last_rotated_at
FROM broker_credentials
WHERE user_id = %s
ORDER BY broker ASC
""",
(user_id,),
)
rows = cur.fetchall()
return [self._row_to_broker_credential(row) for row in rows]
def upsert_broker_credential(
self,
user_id: str,
+15
View File
@@ -70,6 +70,21 @@ class IssuedServiceToken(BaseModel):
auth_token: AuthTokenResponse
class IssueServiceTokenRequest(BaseModel):
name: str = Field(min_length=1)
username: str = Field(min_length=1)
permission: Literal["read", "trade-write", "admin"] = "read"
expires_in_days: int | None = Field(default=None, ge=1, le=3650)
no_expiry: bool = False
class IssueServiceTokenApiResponse(BaseModel):
token: str
token_type: Literal["bearer"] = "bearer"
runtime_id: str | None = None
auth_token: AuthTokenResponse
class ServiceTokenIssueCliResponse(BaseModel):
token_id: str
name: str
+26 -15
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Literal
from typing import Any, Literal
from pydantic import BaseModel, Field
@@ -15,21 +15,22 @@ from pydantic import BaseModel, Field
class AssetItem(BaseModel):
asset_id: str
broker: str
market: str | None = None
symbol: str
name: str
market: str | None = None
status: str
cash_balance: float
asset_quantity: float
price: float
profit_buffer: float
active_strategy_id: str | None = None
available_strategies: list[str] | None = None
cash: float
quantity: float
broker_type: str
strategy_id: str | None = None
strategy_params: dict[str, Any] = {}
updated_at: datetime | None = None
# Additional informational fields
name: str | None = None
price: float | None = None
profit_buffer: float | None = None
tags: list[str] | None = None
owner_user_id: str | None = None
created_at: datetime | None = None
updated_at: datetime | None = None
last_trade_at: datetime | None = None
@@ -42,14 +43,24 @@ class AssetsResponse(BaseModel):
# GET /v1/user_info
# ---------------------------------------------------------------------------
class BrokerItem(BaseModel):
broker: str
account_ref: str
credential_payload: dict[str, Any] | None = None
credential_version: int = 1
last_rotated_at: datetime | None = None
class UserInfoResponse(BaseModel):
runtime_id: str
trading_enabled: bool
disabled_reason: str | None = None
brokers: list[BrokerItem] = []
# Additional informational fields
user_id: str
username: str
email: str | None = None
permission: str
is_active: bool
disabled_reason: str | None = None
runtime_id: str
# ---------------------------------------------------------------------------
@@ -79,4 +90,4 @@ class LedgerTradeResponse(BaseModel):
tax_amount: float
executed_at: datetime
recorded_at: datetime | None = None
created: bool
status: Literal["new", "duplicate"] = "new"