# Portfolio Hub Interface Contract - Baseline Mode: observed - Baseline Seed: .stagepilot/bootstrap/baseline.yaml - Status: confirmed - Owner: repository-maintainers - Last Updated (KST): 2026-05-21 00:00 - Source Discovery / Batch: bootstrap-baseline, bat-001, bat-006, bat-008, bat-010, bat-003, bat-004, bat-005, BAT-006(dcy-004), BAT-007(dcy-004), BAT-008(dcy-004) - Primary Runtime: mixed ## Project Summary - PortfolioHub exposes portfolio management and trading ledger workflows through a FastAPI service and a companion CLI. ## Primary Domain - Portfolio management and trading ledger services. ## Purpose - This document captures the approved external and cross-boundary interface contracts for the project. - It is a cross-cutting reference for REQ drafting, batch design, implementation, verification, and handoff. ## Scope - Covers externally visible APIs, CLI surfaces, events, files, or batch I/O contracts. - Does not duplicate full business requirements already owned by REQ documents. - Does not replace low-level code references or generated API artifacts. ## Interface Summary - Primary HTTP API :: manage authentication, portfolios, strategy sets, and users over JSON HTTP endpoints - PortfolioHub CLI :: provide command-line access to health checks, database setup, users, portfolios, strategies, and service tokens ## Interface: `Primary HTTP API` - Type: http-api - Consumers / Producers: authenticated clients, operators, and downstream services - Purpose: manage authentication, portfolios, strategy sets, and users over JSON HTTP endpoints - Stability: internal ### Inputs - Authorization: Bearer :: required for protected routes and mapped to read, trade-write, or admin permissions - JSON request bodies :: carry login, token issuance, user CRUD, strategy-set CRUD, portfolio mutations, comments, and tags - Route and query parameters :: select users, tokens, portfolios, filters, recent history windows, comments, and tags ### Outputs - JSON response models :: responses are shaped by app/schemas/auth.py, app/schemas/user.py, and app/schemas/portfolio.py - HTTP 201, 200, and 204 status codes :: create, read or update, and delete semantics respectively - GET /health payload :: returns `{"status": "ok", "service": "portfolio-hub", "version": "", "checked_at": "", "db_enabled": }` for readiness checks. `db_enabled` exposes the `PORTFOLIOHUB_DB_ENABLED` setting value (not an actual DB connectivity ping); see `docs/runtime-flows.md` for the readiness semantics (REQ-035, dcy-005). ### Error Contract - 401 Unauthorized :: invalid credentials, invalid token, or missing token on protected routes - 403 Forbidden :: insufficient permission or token issuance policy violation - 404 Not Found :: missing user, token, portfolio, comment, tag, or strategy set - 422 Unprocessable Entity :: FastAPI or Pydantic request validation failure ### Compatibility Rules - Route prefixes `/health`, `/auth`, `/users`, and `/portfolios` define the unversioned internal API surface. The legacy `/strategy-sets` routes are removed; strategy catalog consumers use `/v1/strategies` and admins use `/v1/admin/strategies`. - Permission semantics read, trade-write, and admin must stay aligned across auth guards and token metadata. - Breaking route or schema changes require REQ and Batch documentation updates before release. ## Interface: `PortfolioHub CLI` - Type: cli - Consumers / Producers: operators and automation - Purpose: provide command-line access to health checks, database setup, users, portfolios, strategies, and service tokens - Stability: internal ### Inputs - pfhub subcommands :: include user, portfolio, strategy, tag, service-token, daemon, credential, health-check, init-db, and migrate-db command families - `service-token` subcommands: `issue`, `rotate`, `rebind` (BAT-007: `--daemon-id` 변경), `revoke`, `list`, `migrate-null-daemon --dry-run` (BAT-007: NULL daemon_id 진단 CLI) - `daemon` subcommands: `create`, `list`, `update` (BAT-007: `--deactivate --force` 시 바인딩 service token 자동 revoke) - Flags and options :: include --format table|json, --force confirmations, and operation-specific mutation arguments - Environment configuration :: app/core/config.py resolves PORTFOLIOHUB_* and TIMESCALEDB_* values before command execution - Portfolio identification (bat-006) :: all portfolio mutation commands accept `` (positional) + `--user ` instead of raw portfolio_id; `comment` sub-commands accept portfolio_id (UUID) directly - Tag commands (bat-005) :: `pfhub tag create/list/deactivate/apply/remove` operate on the tags master table; `pfhub portfolio tag add/list/remove` has been removed (breaking change) - Portfolio strategy selection :: `pfhub portfolio create` requires `--strategy-id`; `portfolio update` accepts optional `--strategy-id`. Strategy names/configs are not accepted on portfolio mutations. - Strategy catalog commands :: `pfhub strategy list/create/update/delete`; list and mutation output includes `status` and `revision`, update preserves the strategy ID, and referenced strategies cannot be deleted. ### Outputs - Table or JSON console rendering :: read flows emit structured operator output suitable for manual review or automation - One-time token reveal :: issued client or service tokens are shown once and then only masked metadata remains - Process exit status :: command success or failure is communicated through standard CLI exit behavior ### Error Contract - Typer validation errors :: invalid arguments or missing required options stop the command before execution - Confirmation refusal :: write commands abort unless the operator confirms or passes --force - Persistence and auth failures :: disabled DB mode, connectivity issues, or permission problems surface as command errors ### Compatibility Rules - Command names and primary flags should remain stable for internal automation. - Write commands require explicit confirmation unless --force is present. - JSON output should remain machine-readable across additive command evolution. ## Interface: `v1 Consumer API (trex-basic)` - Type: http-api - Consumers / Producers: trex-basic service (Consumer-Driven Contract, dcy-002, dcy-006) - Purpose: provide daemon-scoped asset listing, user info with daemon_id diagnostic, and daemon-assignment-authorized trade ledger recording - Stability: internal (versioned under /v1) ### Authentication - All /v1 endpoints require `Authorization: Bearer ` header. - Token must be DB-issued (`token_source="db"`); env tokens are rejected with HTTP 403. - Admin catalog endpoints (`POST /v1/assets`, `PATCH /v1/assets/{id}`, `PATCH /v1/assets/{id}/deactivate`) require admin permission. - POST /v1/portfolios/{portfolio_id}/ledger/trades additionally requires `trade-write` permission and a DB service token with non-NULL `daemon_id`. ### Token Type Branching - `token_type="service"`: daemon-scoped endpoints. `daemon_id` must be non-NULL (NULL → HTTP 403 fail-closed). - `token_type="session"`: user-scoped (login token). Endpoints return owner's own data. - `token_type="client"`: **Deprecated/Removed** (REQ-016/BAT-006). 발급 경로 제거. 잔존 DB row는 읽을 수 있으나 신규 발급 불가. v1 API 호출 시 HTTP 403 fail-closed. - env token (token_source="env"): admin-scoped. May query other users' data via `?user_id=` param. DB /v1 endpoints에서는 HTTP 403 (DB token만 허용). ### Daemon Authorization Model - Service tokens are bound to a daemon at issuance via `daemon_id` field. Legacy/unbound tokens have `daemon_id=NULL`. - GET /v1/assets (service token) and POST /v1/portfolios/{portfolio_id}/ledger/trades are daemon-scoped. NULL token `daemon_id` → HTTP 403 (fail-closed). - GET /v1/user_info is available to any service token; returns `daemon_id: null` as diagnostic for unbound tokens. - Each asset (portfolio) may be assigned to exactly one daemon via `portfolios.managed_by_daemon_id`. Mismatch or unassigned asset → HTTP 403 on ledger writes. - **Token rebind** (BAT-007/REQ-023): `pfhub service-token rebind --daemon-id ` — daemon_id 변경, runtime_id 불변. 대상 daemon은 active이어야 하고 token 소유 user와 일치해야 한다. - **Daemon deactivation** (BAT-007/REQ-022): `pfhub daemon update --deactivate --force` — daemon is_active=false + 바인딩된 모든 service token 즉시 revoke. - **Admin daemon owner transfer**: `PATCH /v1/admin/daemons/{daemon_id}` with a changed `owner_user_id` is allowed only for an unassigned daemon. A referenced daemon returns HTTP 409; no daemon owner, portfolio assignment, or broker credential is changed. Owner transfer locks the daemon row `FOR UPDATE`, while portfolio assignment locks it `FOR SHARE`, so a concurrent operation either transfers first and rejects the old owner's assignment as HTTP 404 or assigns first and rejects the transfer as HTTP 409. - **NULL daemon migration CLI** (BAT-007/REQ-023): `pfhub service-token migrate-null-daemon --dry-run` — NULL daemon_id active service token inventory 출력 + user별 candidate daemon 목록. `--dry-run` 없이 실행 시 exit code 1 + 수동 안내. ### Endpoint: `GET /v1/assets` - Auth: DB token required; behavior branches by `token_type` - `service`: returns portfolios where `managed_by_daemon_id = token.daemon_id`; NULL daemon_id → 403 - `user`: returns caller's own portfolios (`owner_user_id = token.user_id`) - `admin`: returns caller's own portfolios; `?user_id=` overrides to specified user - Query Params: `?status=` (optional portfolio status filter), `?market=` (optional market code filter), `?user_id=` (admin only) - Response: HTTP 200 ``` { "total": , "assets": [ { "asset_id": "", // portfolio.portfolio_id "symbol": "", "status": "", "cash": , "quantity": , "broker_type": "", "strategy_id": "", "strategy_type": "", "strategy_params": {}, "updated_at": "", "name": "", "price": , "profit_buffer": , "tags": []|null, "owner_user_id": "", "created_at": "", "last_trade_at": "" } ] } ``` - Error: HTTP 401 if no token; HTTP 403 if env token or (service token with daemon_id NULL) ### Endpoint: `POST /v1/assets` (Admin Catalog) - Auth: admin token required - Body: `{"symbol": "", "markets": [], "display_name": "", "status": "active"}` - Response: HTTP 201 `AssetCatalogResponse` ``` { "asset_id": "", "symbol": "", "markets": [], "display_name": "", "status": "", "created_at": "", "updated_at": "" } ``` - Error: HTTP 403 if not admin ### Endpoint: `PATCH /v1/assets/{asset_id}` (Admin Catalog Update) - Auth: admin token required - Body: `{"markets": []|null, "display_name": "", "status": ""}` - Response: HTTP 200 `AssetCatalogResponse` - Error: HTTP 403 if not admin ### Endpoint: `PATCH /v1/assets/{asset_id}/deactivate` (Admin Catalog Deactivate) - Auth: admin token required - Body: none - Response: HTTP 200 `AssetCatalogResponse` with `status="inactive"` - Error: HTTP 403 if not admin ### Endpoint: `GET /v1/user_info` - Auth: service-token bearer (read); available to all service tokens including unbound (daemon_id=NULL) - Response: HTTP 200 ``` { "runtime_id": "", // null for tokens without runtime_id (diagnostic) "daemon_id": "", // null for unbound/legacy tokens (diagnostic) "trading_enabled": , // mapped from users.is_active "disabled_reason": "", // "account_inactive" when trading_enabled=false "brokers": [ { "broker": "", "account_ref": "", "credential_payload": {}|null, // Fernet-decrypted {app_key, app_secret} "credential_version": , "last_rotated_at": "" } ], "user_id": "", "username": "", "email": "", "permission": "" } ``` - Error: HTTP 401 if no token; HTTP 403 if not a service token ### Endpoint: `POST /v1/assets/{asset_id}/ledger/trades` - Auth: service-token bearer (trade-write); token must have `daemon_id` bound; asset must be assigned to that daemon - Path Param: `asset_id` — must be a valid UUID portfolio_id - Authorization: `portfolios.managed_by_daemon_id` must equal `token.daemon_id`; NULL token → 403; unassigned asset → 403; mismatch → 403 - Request Body: ``` { "order_id": "", // required, min_length=1 "execution_id": "", // required, min_length=1 "side": "buy"|"sell", "quantity": , // > 0 "price": , // > 0 "fee_amount": , // >= 0, default 0 "tax_amount": , // >= 0, default 0 "executed_at": "" } ``` - Response HTTP 201 (new record): ``` { "ledger_entry_id": , "asset_id": "", "order_id": "", "execution_id": "", "side": "", "quantity": , "price": , "fee_amount": , "tax_amount": , "executed_at": "", "recorded_at": "", "status": "new" } ``` - Response HTTP 200 (idempotent duplicate with identical payload): same body with `"status": "duplicate"` - Error: HTTP 401 if no token; HTTP 403 if not service token, daemon_id NULL, asset unassigned, or daemon mismatch; HTTP 404 if asset_id not found; HTTP 409 if duplicate key with different payload ### Idempotency Contract - Deduplication key: `(asset_id, order_id, execution_id)` — enforced by `uq_ledger_trades_idempotency` DB unique constraint - Identical payload re-send → HTTP 200 + `status="duplicate"`, no new row created - Same key, different payload → HTTP 409 Conflict ### Deployment Constraint (bat-006) - trex-basic and portfolio-hub must be deployed simultaneously when BAT-006 is released. - After BAT-006, all `asset_id` values in GET /v1/assets responses change from TEXT to UUID format. - trex-basic consumers must handle UUID-format asset_id before the coordinated deployment is completed. ## Interface: `v1 Portfolio API (BAT-009/010)` - Type: http-api - Consumers / Producers: authenticated users and admin services - Purpose: CRUD for user-owned portfolios; tag and comment sub-resources; ownership and disabled-state enforcement - Stability: internal (versioned under /v1) ### Authentication - All /v1/portfolios endpoints require `Authorization: Bearer ` header. - `token_type ∈ {service, client}` → HTTP 403 fail-closed for all write operations and GET sub-resources. - `permission='admin'` → access to all portfolios. `permission ∈ {read, trade-write}` → own portfolios only. - Comment and portfolio CRUD routes: DB token or env token; POST/PATCH/DELETE require user or admin token type. - Tag POST/DELETE routes additionally require `token_source="db"` (DB token). ### Endpoint: `POST /v1/portfolios` - Auth: any valid token; service/client → HTTP 403 - Body: `{"asset_id": "", "broker": "", "name": "", "cash_balance": , "asset_quantity": , "asset_price": , "profit_buffer": , "strategy_id": "", "managed_by_daemon_id": "", "user_id": " (admin only)"}` - Response: HTTP 201 `PortfolioItem {"portfolio_id": "", ..., "active_strategy_id": "", "strategy_name": "", "strategy_params": {}, "strategy_revision": , ...}` - Note: `symbol` is populated from the server-side joined asset row (`portfolios.asset_id -> assets.asset_id -> assets.symbol`), not from client-side catalog reconstruction. - Note: a non-null `managed_by_daemon_id` must be a daemon server-generated UUID that exists, is active, and is owned by the target portfolio owner (admin `user_id` override uses the final target owner, not the calling admin). Daemon validation and the portfolio write share one atomic transaction (`FOR SHARE` daemon lock); a selected daemon that is deactivated concurrently is rejected rather than committed. - Error: HTTP 403 if service/client token; HTTP 404 if `strategy_id` is unknown or the daemon does not exist/is not owned by the portfolio owner; HTTP 409 if the strategy is inactive or the daemon is inactive; HTTP 422 for a missing/invalid `strategy_id`, an unknown/inactive asset, or a non-UUID `managed_by_daemon_id` ### Endpoint: `PATCH /v1/portfolios/{portfolio_id}` - Auth: any valid token; service/client → HTTP 403; ownership required - Body: `{"broker": "", "status": "", "name": "", "strategy_id": "", "asset_price": , "managed_by_daemon_id": ""}` - Response: HTTP 200 `PortfolioItem {"portfolio_id": "", ..., "active_strategy_id": "", "strategy_name": "", "strategy_params": {}, "strategy_revision": , ...}` - Note: response `symbol` is emitted from the joined asset row referenced by `asset_id`. - Note: a non-null `managed_by_daemon_id` assignment/reassignment follows the same daemon validation contract as create: it must be a UUID that exists, is active, and is owned by the portfolio owner. The daemon `FOR SHARE` lock and the portfolio UPDATE share one atomic transaction, so a concurrently deactivated daemon is rejected with HTTP 409. - Error: HTTP 403 if service/client or ownership mismatch; HTTP 404 if portfolio, strategy, or daemon is not found (foreign daemon is hidden as 404); HTTP 409 if the portfolio is disabled for the mutation, the selected strategy is inactive, or the daemon is inactive; HTTP 422 for an invalid request body or a non-UUID `managed_by_daemon_id` ## Interface: `v1 Strategy Catalog API` - `GET /v1/strategies` and `GET /v1/strategies/{strategy_id}` require read permission and expose active strategies only. - `GET /v1/admin/strategies[/{strategy_id}]` and admin `POST`, `PATCH`, `DELETE` require admin permission and expose both active and inactive entries. - Create body: `{"name": "", "config": {}, "status": "active|inactive"}`; response is `StrategyResponse {strategy_id, name, config, status, revision, created_at, updated_at}`. - Patch accepts at least one of `name`, `config`, or `status`. An effective no-op preserves `revision`; a real mutation increments it while preserving `strategy_id` and keeping the derived `nick` consistent with name/config. - Strategy PATCH locks the catalog row (`FOR UPDATE`) through the mutation transaction. Concurrent partial PATCH requests therefore serialize and derive `nick` from the latest committed name/config pair. - Inactive strategies remain readable to admins and remain attached to existing portfolios, but cannot be selected for new or updated portfolio assignments. - New portfolio selection takes a `FOR SHARE` lock on the active strategy in the same transaction as the portfolio INSERT/UPDATE. PATCH/DELETE take `FOR UPDATE`, preventing concurrent inactivation/deletion from racing the selection; DELETE also checks both reference forms and deletes in that transaction. - Delete returns HTTP 409 while any portfolio references the strategy. Unknown IDs return HTTP 404; schema validation returns HTTP 422; conflicts return HTTP 409. ### Endpoint: `DELETE /v1/portfolios/{portfolio_id}` (Soft Delete) - Auth: any valid token; service/client → HTTP 403; ownership required - Body: none - Response: HTTP 200 `PortfolioItem` with `status="disabled"`, `managed_by_daemon_id=null`, `symbol=""` - Note: soft delete does not break the asset join; `symbol` remains the linked `assets.symbol` value in the HTTP 200 response. - Dependent data: portfolio_comments and tag_ids are preserved on soft delete; only status and daemon assignment change - Error: HTTP 403 if service/client or ownership mismatch; HTTP 404 if not found ### Endpoint: `GET /v1/portfolios` - Auth: any valid token; client → HTTP 403 - Query Params: `?include_disabled=true` (default false); `?market=`; `?user_id=` (admin only) - Branching by token type: - `service`: returns portfolios where `managed_by_daemon_id = token.daemon_id`; NULL daemon_id → HTTP 403 - `user/admin`: returns owner's own portfolios; admin may override with `?user_id=` - Response: HTTP 200 `PortfolioListResponse {"portfolios": [{"portfolio_id": "", "asset_id": "", "symbol": "", "net_contributed_capital": , "cumulative_profit_withdrawn": , ...}], "total": }` - Note: list items are serialized from the server-side `portfolios JOIN assets` result; `symbol` must equal the joined `assets.symbol` for each returned `asset_id`. - Ledger aggregate fields: - `total_invested` (**총투자원금**, summary response) = source와 무관한 유효 `INVEST`의 gross 합계. - `total_withdrawn` (**총회수원금**, summary response) = source와 무관한 유효 `WITHDRAW` 합계. - `net_contributed_capital` (**순투자원금**) = `total_invested - total_withdrawn`. `PROFIT`는 원금 계산에서 제외한다. - `cumulative_profit_withdrawn` (**누적 수익 인출액**) = source와 무관한 유효 `PROFIT` 합계. 원금 또는 매매상 실현손익 전체가 아니다. - 동일 portfolio에서 matching `REVERSAL.target_ledger_entry_id`로 참조된 `INVEST`, `WITHDRAW`, `PROFIT` 원거래는 original과 reversal의 source와 무관하게 제외하며 `REVERSAL` 자체는 금액 action으로 합산하지 않는다. - `buffer_out` 등 `INVEST`/`WITHDRAW`/`PROFIT` 이외 side는 원금·수익 aggregate에 포함하거나 `INVEST`로 재해석하지 않는다. - 목록에 반환될 portfolio ID 집합만 한 번의 grouped aggregate로 조회한다. 해당 유효 ledger가 없는 항목은 aggregate field가 `0.0`이다. - 이 필드들은 portfolio-hub가 소유한 ledger 집계값이다. 소비자는 ledger event를 재해석하지 않는다. ### Endpoint: `GET /v1/portfolios/{portfolio_id}/tags` - Auth: DB or env token; service/client → HTTP 403; ownership required - Response: HTTP 200 `PortfolioTagListResponse {"tags": [TagItem], "total": }` - Note: disabled portfolio GET is allowed - Error: HTTP 403 if service/client or ownership mismatch; HTTP 404 if portfolio not found ### Endpoint: `POST /v1/portfolios/{portfolio_id}/tags` - Auth: DB token required; trade-write or admin; service/client → HTTP 403; ownership required - Body: `{"tag_id": ""}` - Response: HTTP 200 `TagApplyResponse {"tag_id": "", "status": "applied"}` - Policy: tag must be is_active=true; non-admin must use own or admin tag; disabled portfolio → HTTP 409 - Error: HTTP 403 if policy violation, service/client, or ownership mismatch; HTTP 404 if portfolio or tag not found; HTTP 409 if disabled portfolio ### Endpoint: `DELETE /v1/portfolios/{portfolio_id}/tags/{tag_id}` - Auth: DB token required; trade-write or admin; service/client → HTTP 403; ownership required - Response: HTTP 200 `TagApplyResponse {"tag_id": "", "status": "removed"}` - Error: HTTP 403 if service/client or ownership mismatch; HTTP 404 if portfolio not found; HTTP 409 if disabled portfolio ### Endpoint: `POST /v1/portfolios/{portfolio_id}/comments` - Auth: any valid token; service/client → HTTP 403; ownership required - Body: `{"content": ""}` (min_length=1) - Response: HTTP 201 `PortfolioCommentItem {"comment_id": "", "portfolio_id": "", "content": "", "created_at": "", "updated_at": ""}` - Error: HTTP 403 if service/client or ownership mismatch; HTTP 404 if portfolio not found; HTTP 409 if disabled portfolio ### Endpoint: `GET /v1/portfolios/{portfolio_id}/comments` - Auth: any valid token; service/client → HTTP 403; ownership required - Response: HTTP 200 `PortfolioCommentListResponse {"comments": [PortfolioCommentItem], "total": }` (created_at desc from repo) - Note: disabled portfolio GET is allowed - Error: HTTP 403 if service/client or ownership mismatch; HTTP 404 if portfolio not found ### Endpoint: `PATCH /v1/portfolios/{portfolio_id}/comments/{comment_id}` - Auth: any valid token; service/client → HTTP 403; portfolio ownership required (no per-comment author check) - Body: `{"content": ""}` (min_length=1) - Response: HTTP 200 `PortfolioCommentItem` - Error: HTTP 403 if service/client or ownership mismatch; HTTP 404 if portfolio or comment not found; HTTP 409 if disabled portfolio ### Endpoint: `DELETE /v1/portfolios/{portfolio_id}/comments/{comment_id}` - Auth: any valid token; service/client → HTTP 403; portfolio ownership required - Response: HTTP 204 (no content) - Error: HTTP 403 if service/client or ownership mismatch; HTTP 404 if portfolio or comment not found; HTTP 409 if disabled portfolio ### Endpoint: `POST /v1/portfolios/{portfolio_id}/ledger/trades` (REQ-029, BAT-011; REQ-033 column rename BAT-015) - Auth: DB service token with `trade-write` permission; `daemon_id IS NULL` → HTTP 403 fail-closed - Request: `LedgerTradeRequest` — `order_id`, `execution_id`, `side` (buy|sell), `quantity`, `price`, `fee_amount`, `tax_amount`, `executed_at` - Response: HTTP 201 + `LedgerTradeResponse` with `status="new"`; HTTP 200 + `status="duplicate"` for idempotent replay; HTTP 409 for conflicting payload - `LedgerTradeResponse` fields: `ledger_entry_id`, `portfolio_id` (renamed from `asset_id` by REQ-033 / dcy-005 — schema and DB column now match in meaning), `order_id`, `execution_id`, `side`, `quantity`, `price`, `fee_amount`, `tax_amount`, `executed_at`, `recorded_at`, `status` - Error: HTTP 403 (no daemon_id on token, portfolio unassigned, daemon mismatch); HTTP 404 (non-existent portfolio); HTTP 409 (disabled portfolio or payload conflict) - Idempotency key: `(portfolio_id, order_id, execution_id)` — reuses `uq_ledger_trades_idempotency` constraint - **구 path `POST /v1/assets/{asset_id}/ledger/trades`**: BAT-011에서 제거됨. 호출 시 HTTP 404. ### Endpoint: `POST /v1/portfolios/{portfolio_id}/ledger/manual` (REQ-056, BAT-024) - Auth: DB user/session token with portfolio ownership. Service/client tokens and env tokens are HTTP 403 fail-closed. - Purpose: trex-web/user 수동 장부 append. Existing `/ledger/trades` remains daemon/service-token broker execution write only. - Body: `ManualLedgerRequest` with `action` enum `INVEST|BUFFER_OUT|BUFFER_IN|BUY|SELL|WITHDRAW|PROFIT|REVERSAL`. - `INVEST`, `BUFFER_OUT`, `BUFFER_IN`, `WITHDRAW`, `PROFIT` require `amount`. - `BUY`, `SELL` require `quantity` and `price`; optional `fee`, `tax` default 0. - `REVERSAL` requires `target_ledger_entry_id`; direct mutation/delete of prior rows is not supported. - `QUANTITY_ADJUSTMENT` is not part of this API. - Response: HTTP 201 `ManualLedgerResponse` with `ledger_entry_id`, `portfolio_id`, `action`, `source=manual`, `cash_balance_after`, `asset_quantity_after`, `profit_buffer_after`, `total_value_after`, `target_ledger_entry_id`, `confirmation_evidence`. - Validation/conflict policy: - disabled portfolio → HTTP 409 `PORTFOLIO_DISABLED`. - daemon-managed portfolio without `confirm_daemon_managed_manual_write=true` → HTTP 409 `MANUAL_WRITE_REQUIRES_CONFIRMATION`. - insufficient cash/quantity/buffer → HTTP 409 `INSUFFICIENT_CASH|INSUFFICIENT_QUANTITY|INSUFFICIENT_BUFFER`. - duplicate reversal target → HTTP 409 `LEDGER_ENTRY_ALREADY_REVERSED`. - Return semantics: net contributed capital is `sum(INVEST) - sum(WITHDRAW)`; `PROFIT` is exposed as `cumulative_profit_withdrawn` and is not included in net contributed capital. ### Endpoint: `GET /v1/portfolios/{portfolio_id}/ledger/manual` (REQ-056, BAT-024) - Auth: same owner-scoped user/session token policy as manual write. - Query: `limit` 1..200, default 50. - Response: `ManualLedgerHistoryResponse {"items": [ManualLedgerResponse], "total": }` ordered newest first. ### Endpoint: `GET /v1/portfolios/{portfolio_id}/returns/summary` (REQ-056, BAT-024) - Auth: owner-scoped user/session token. - Response: `PortfolioReturnSummaryResponse` with `total_invested`, `total_withdrawn`, `net_contributed_capital`, and `cumulative_profit_withdrawn`. - Aggregate semantics: `total_invested`는 source-independent valid `INVEST`의 gross 합계, `total_withdrawn`은 valid `WITHDRAW` 합계, `net_contributed_capital`은 두 값의 차이며 `PROFIT`는 원금에서 제외하고 `cumulative_profit_withdrawn`으로만 노출한다. - Reversal semantics: 동일 portfolio의 matching `REVERSAL.target_ledger_entry_id`는 original과 reversal의 source와 무관하게 original을 제외한다. `buffer_out` 등 다른 side는 집계하지 않는다. - Consistency: `GET /v1/portfolios`와 동일한 grouped repository aggregate를 portfolio ID 하나에 위임한다. ## Interface: `Tag Management API (BAT-004)` - Type: http-api - Consumers / Producers: authenticated operators and admin services - Purpose: manage tag master records and apply/remove tags on assets and portfolios - Stability: internal (versioned under /v1) ### Authentication - All /v1/tags, /v1/assets/{id}/tags, /v1/portfolios/{id}/tags endpoints require `Authorization: Bearer `. - Token must be DB-issued (`token_source="db"`); env tokens rejected with HTTP 403. ### Endpoint: `POST /v1/tags` - Auth: DB token required; trade-write or admin permission - Body: `{"name": ""}` (min_length=1; normalized to lowercase + stripped) - Response: HTTP 201 `TagItem` `{"tag_id": "", "name": "", "is_admin_tag": , "is_active": true, "created_at": ""}` - is_admin_tag is set to true when caller has admin permission; false for trade-write - Error: HTTP 409 if tag name already exists; HTTP 403 if env token ### Endpoint: `GET /v1/tags` - Auth: DB token required; read permission - Query Params: `?include_inactive=true` (default false — returns only active tags) - Response: HTTP 200 `TagListResponse` `{"tags": [TagItem], "total": }` - Error: HTTP 403 if env token ### Endpoint: `PATCH /v1/tags/{tag_id}/deactivate` - Auth: DB token required; read permission (admin or tag creator) - Path Param: `tag_id` — must be a valid tag UUID - Body: none - Response: HTTP 200 `TagItem` with `is_active=false`; idempotent (already-inactive returns 200 immediately) - Error: HTTP 404 if tag not found; HTTP 403 if caller is not admin and not tag creator ### Endpoint: `POST /v1/assets/{asset_id}/tags` - Auth: DB token required; admin permission - Path Param: `asset_id` — maps to portfolio_id (v1 convention: asset_id = portfolio_id) - Body: `{"tag_id": ""}` - Response: HTTP 200 `TagApplyResponse` `{"tag_id": "", "status": "applied"}` - Policy: tag must have is_admin_tag=true AND is_active=true; non-admin-tag → HTTP 403; inactive → HTTP 403 - Error: HTTP 404 if asset or tag not found; HTTP 403 if policy violation or env token ### Endpoint: `DELETE /v1/assets/{asset_id}/tags/{tag_id}` - Auth: DB token required; admin permission - Body: none - Response: HTTP 200 `TagApplyResponse` `{"tag_id": "", "status": "removed"}` - Error: HTTP 404 if asset not found; HTTP 403 if not admin or env token ### Endpoint: `POST /v1/portfolios/{portfolio_id}/tags` - Auth: DB token required; trade-write or admin permission - Body: `{"tag_id": ""}` - Response: HTTP 200 `TagApplyResponse` `{"tag_id": "", "status": "applied"}` - Policy: tag must have is_active=true; caller must be portfolio owner or admin; non-admin non-owner-created tag → HTTP 403 - Error: HTTP 404 if portfolio or tag not found; HTTP 403 if policy violation or env token ### Endpoint: `DELETE /v1/portfolios/{portfolio_id}/tags/{tag_id}` - Auth: DB token required; trade-write or admin permission - Body: none - Response: HTTP 200 `TagApplyResponse` `{"tag_id": "", "status": "removed"}` - Error: HTTP 404 if portfolio not found; HTTP 403 if caller is not owner or admin ## Deprecated Endpoints ### `POST /auth/tokens` (Client Token Issuance) — Removed - **Status**: Removed as of BAT-006/REQ-016 (2026-05-20). - Route `POST /auth/tokens` 및 `CreateClientTokenRequest` / `IssuedClientTokenResponse` 스키마 제거. 호출 시 HTTP 404 또는 405. - `token_type="client"` 발급 경로는 코드에서 완전히 제거됨. 잔존 client token row는 DB에 읽기 전용으로 남을 수 있음. ### `POST /auth/service-tokens` Body — daemon_id 추가 (BAT-006/REQ-018) - Body `daemon_id` 필드가 서비스 토큰 발급 시 라우트 핸들러로 정상 forwarding됨. (이전: 누락으로 인해 daemon_id가 항상 NULL로 저장) - Body: `{"name": "", "username": "", "permission": "read|trade-write", "expires_in_days": , "no_expiry": , "daemon_id": ""}` - Response: HTTP 201 `{"token": "", "runtime_id": "", "daemon_id": "", ...}` ## Token Issuance Authorization Matrix (REQ-020/BAT-008 — dcy-004 FR-5, NFR-4) 매트릭스 위반 호출 → HTTP 403 fail-closed (모든 권한 미충족 케이스). | Token Type | Verb | admin | trade-write | read | 비고 | |------------|------|-------|-------------|------|------| | session | issue (POST /auth/login) | ✓ | ✓ | ✓ | 유효 credential 필요 | | session | revoke (DELETE /auth/tokens/{id}) | ✓ 본인 | ✓ 본인 | ✓ 본인 | 타 user token 폐기 불가 | | session | list (GET /auth/tokens) | ✓ 본인 | ✓ 본인 | ✓ 본인 | — | | service | issue (POST /auth/service-tokens) | ✓ | ✗ | ✗ | admin만 발급 가능 | | service | rotate (pfhub service-token rotate) | ✓ | ✗ | ✗ | CLI only | | service | rebind (pfhub service-token rebind) | ✓ | ✗ | ✗ | CLI only | | service | revoke (pfhub service-token revoke) | ✓ | ✗ | ✗ | CLI only | | service | list (pfhub service-token list) | ✓ | ✗ | ✗ | CLI only | | env | issued/managed | infra operator | ✗ | ✗ | PORTFOLIOHUB_ADMIN_TOKENS 환경 변수 직접 편집 | | client | — | ✗ | ✗ | ✗ | **폐지됨** (REQ-016/BAT-006) | **Admin 자기 발급 정책 (dcy-004 OQ-4)**: admin은 본인 user_id 대상으로 daemon-bound 또는 unbound service token 발급 가능. 관행상 최소 권한 원칙에 따라 운영 daemon 대상 발급을 권장. **코드 매핑**: `require_admin` → admin 전용 게이트. `require_read` → read 이상 허용. `AuthService.issue_service_token()` → admin 권한 필요 (라우트에서 `require_admin` 의존성). 불일치 발견 시 별도 follow-up REQ로 분리. ## Shared Constraints - Token permission levels gate both HTTP and CLI mutations consistently. - DB-backed endpoints and commands require PORTFOLIOHUB_DB_ENABLED=true plus valid TimescaleDB settings. - Secret and token values are only revealed once at issuance time and are masked afterwards. ## Current Gaps / Planned Changes - External consumer versioning policy is still implicit and not published as a separate contract artifact. - Service-token lifecycle and ownership rules may continue to evolve as authorization requirements mature. - OpenAPI publication and CLI reference generation are not yet automated. ## Update Triggers - Update this document when an externally visible API, event, CLI, or file contract changes. - Update this document when a batch changes compatibility, validation, or error behavior. - Update this document when a new external consumer or producer is introduced. ## Change Log - 2026-08-19 KST: Issue #28 — portfolio return aggregate를 manual-only에서 source-independent semantics로 교정; gross `total_invested`, `INVEST-WITHDRAW` net, separate `PROFIT`, cross-source reversal과 non-capital side 제외를 명시. - 2026-07-14 KST: BAT-024 (REQ-056) — added owner-scoped manual ledger API, manual history, and return summary contracts; clarified PROFIT vs WITHDRAW return semantics and service-token separation from `/ledger/trades`. - 2026-05-21 KST: BAT-011 (REQ-029) — ledger path migration: "POST /v1/assets/{asset_id}/ledger/trades" 명세 → "POST /v1/portfolios/{portfolio_id}/ledger/trades"로 교체; auth 섹션 + daemon authorization 갱신; 구 path HTTP 404 명시. - 2026-05-21 KST: BAT-010 (REQ-032) — v1 portfolio surface baseline 회복: "v1 Portfolio API" 섹션 신규 추가 (REQ-025~028 CRUD + REQ-030 tag 서브 라우트 + REQ-031 comment CRUD); POST/DELETE /v1/portfolios/{id}/tags에 disabled 보호(409) 및 service/client 403 명세 추가; GET /v1/portfolios/{id}/tags 신설; ledger path "pending REQ-029" 마킹; Source Discovery/Batch 헤더 갱신. - 2026-05-21 KST: BAT-008 (REQ-019/020) — 토큰 surface 정합성 회복 + 권한 매트릭스: service-token rebind/migrate-null-daemon CLI 명세 추가; POST /auth/tokens 제거 명시(REQ-016); POST /auth/service-tokens daemon_id forward 명세 추가(REQ-018); Token Type Branching 갱신(client→Removed, session/env 명시); Daemon Authorization Model에 rebind/deactivate/null-daemon CLI 추가; "Token Issuance Authorization Matrix" 섹션 신규 추가(REQ-020). - 2026-05-20 KST: bat-005 — REQ-008 AC-2: added Tag Management API section (POST/GET/PATCH /v1/tags, POST/DELETE /v1/assets/{id}/tags, POST/DELETE /v1/portfolios/{id}/tags); updated CLI surface (pfhub tag, removed pfhub portfolio tag); updated CLI inputs. - 2026-05-19 KST: bat-002 — REQ-010/012/013/015: added admin catalog endpoints (POST/PATCH /v1/assets, PATCH /v1/assets/{id}/deactivate); rewrote GET /v1/assets authentication to support service/user/admin token branching; added market filter param; removed market field from AssetItem; added AssetCatalogResponse schema. - 2026-05-13 KST: bat-010 — REQ-006/007/008/011/023: added daemon authorization model section; updated GET /v1/assets (daemon-scoped filter, NULL 403); updated GET /v1/user_info (daemon_id field, NULL runtime_id → 200+null diagnostic); updated POST /v1/assets/{asset_id}/ledger/trades (daemon assignment authorization, fail-closed policy); added daemon CLI subcommand to CLI surface; updated v1 purpose and source discovery. - 2026-05-11 KST: bat-008 — REQ-011 AC-1: expanded v1 Consumer API section with authentication contract, detailed request/response schemas for GET /v1/assets, GET /v1/user_info, POST /v1/assets/{asset_id}/ledger/trades; updated GET /health response schema (REQ-004); added idempotency contract. - 2026-05-11 KST: bat-006 — Added v1 consumer API interface section (trex-basic); noted asset_id UUID change and simultaneous deployment constraint; updated CLI portfolio inputs to reflect name+user identification. - 2026-04-30 KST: Bootstrap baseline created from repository observation for initial StagePilot adoption.