Files
portfolio-hub/app/cli/commands/service_tokens.py
T
genichin e6b6a8715b feat: implement daemon model with registry and single-asset assignment (BAT-010, REQ-023/028)
Core Implementation (BAT-010):
- Add daemon registry schema and CRUD operations (req-023)
- Implement single-daemon asset assignment constraint (one asset per daemon)
- Add daemon_id field to service_token for daemon identification
- Add daemon.py CLI module for daemon management commands
- Add 20260513_0016_daemon_model.py migration for daemon tables

API Changes:
- GET /v1/assets: include daemon_id in AssetResponse
- POST /v1/assets/{asset_id}/ledger/trades: require daemon token binding
- GET /v1/user_info: include daemon metadata
- Enhanced service-token rotate to preserve daemon bindings

CLI Commands:
- pfhub daemon register --name <name> --runtime-id <runtime-id>
- pfhub daemon list
- pfhub daemon get <daemon-id>
- pfhub daemon revoke <daemon-id>

Requirements (REQ-023, REQ-028):
- REQ-023: Daemon Registry and Service Token Daemon Binding (Interface, Approved)
  * AC-1: daemon CRUD operations
  * AC-2: service token daemon binding for POST /v1/assets/{asset_id}/ledger/trades
  * AC-3: single daemon per asset (exact-one assignment model)
- REQ-028: README.md Daemon Provisioning Runbook update (Documentation, Approved)

Documentation:
- Add dcy-006 Discovery for daemon-id and single-daemon asset assignment
- Update README.md with Daemon Provisioning Runbook section
- Add BAT-010 batch documentation with planning, implementation, verification
- Update rel-006 release document (daemon model implementation)
- Update data-model.md with daemon and daemon_asset_assignment tables
- Update interface-contract.md with daemon registry APIs
- Update runtime-flows.md with daemon lifecycle flows

Breaking Changes:
- REQ-005~009, REQ-011~012 status reverted to Approved due to revised contract
  * daemon_id field addition and exact-one asset assignment requirement
  * Existing Implemented evidence invalidated by contract revision
  * BAT-001/002/008 re-verification required

Testing:
- Add test_daemon_registry.py for daemon CRUD operations
- Add test_daemon_assignment.py for single-asset assignment constraints
- Update test_auth.py, test_cli.py, test_v1.py for daemon support
- Verify daemon token binding in trade endpoint authorization

Impact:
- Database: 2 new tables (daemons, daemon_asset_assignments)
- Migration: 20260513_0016 creates daemon model schema
- CLI: 4 new daemon subcommands
- API: daemon_id propagation through v1 endpoints
- Verification: BAT-001/002/008 re-verification gates next release
2026-05-13 23:07:24 +00:00

140 lines
5.1 KiB
Python

"""Service token CLI commands."""
from __future__ import annotations
from typing import Optional
import typer
from app.cli.core.output import mask_token_text, render_service_token_result
from app.cli.core.utils import render_output
from app.schemas.auth import AuthTokenResponse, ServiceTokenIssueCliResponse, ServiceTokenRevokeCliResponse
from app.services.auth_service import AuthService
token_app = typer.Typer(help="Service token lifecycle commands.")
def _with_service(ctx: typer.Context, callback):
app_context = ctx.obj
repository = app_context.repository_factory(app_context.settings)
service = AuthService(repository, app_context.settings)
try:
from app.cli.core.utils import execute_command
return execute_command(app_context.console, callback=lambda: callback(service, app_context))
finally:
if callable(getattr(type(repository), "close", None)):
repository.close()
@token_app.command("list")
def list_service_tokens(
ctx: typer.Context,
user: Optional[str] = typer.Option(None, "--user", help="Filter by username."),
show_revoked: bool = typer.Option(False, "--show-revoked", help="Include revoked tokens."),
) -> None:
def _list(service: AuthService, app_context):
tokens = service.list_service_tokens(user, include_revoked=show_revoked)
return [
AuthTokenResponse(
id=t.id,
user_id=t.user_id,
name=t.name,
token_prefix=t.token_prefix,
permission=t.permission,
token_type=t.token_type,
expires_at=t.expires_at,
last_used_at=t.last_used_at,
revoked_at=t.revoked_at,
created_at=t.created_at,
)
for t in tokens
]
result = _with_service(ctx, _list)
render_output(ctx.obj.console, ctx.obj.output_format, result, empty_message="No service tokens found.")
@token_app.command("issue")
def issue_service_token(
ctx: typer.Context,
name: str = typer.Argument(..., help="Unique service token name."),
user: str = typer.Option(..., "--user", help="Username to associate with this service token."),
permission: str = typer.Option("read", "--permission", help="Token permission: read or trade-write."),
ttl_days: int | None = typer.Option(None, "--ttl-days", help="Token TTL in days. Default: 365."),
no_expiry: bool = typer.Option(False, "--no-expiry", help="Issue a token with no expiry."),
daemon_id: Optional[str] = typer.Option(None, "--daemon-id", help="Daemon ID to bind to this token."),
) -> None:
def _issue(service: AuthService, app_context):
return service.issue_service_token(
name,
user,
permission=permission,
expires_in_days=ttl_days,
no_expiry=no_expiry,
daemon_id=daemon_id,
)
issued = _with_service(ctx, _issue)
response = ServiceTokenIssueCliResponse(
token_id=issued.auth_token.id,
name=name,
expires_at=issued.auth_token.expires_at,
revoked=issued.auth_token.revoked_at is not None,
runtime_id=issued.auth_token.runtime_id,
daemon_id=issued.auth_token.daemon_id,
token=issued.token,
)
render_service_token_result(ctx.obj.console, ctx.obj.output_format, response)
if ctx.obj.output_format != "json":
ctx.obj.console.print(f"masked_token: {mask_token_text(issued.token)}")
@token_app.command("rotate")
def rotate_service_token(
ctx: typer.Context,
name: str = typer.Argument(..., help="Service token name to rotate."),
) -> None:
"""Rotate a service token: revoke old and issue new with same daemon_id binding."""
def _rotate(service: AuthService, app_context):
return service.rotate_service_token(name)
issued = _with_service(ctx, _rotate)
response = ServiceTokenIssueCliResponse(
token_id=issued.auth_token.id,
name=name,
expires_at=issued.auth_token.expires_at,
revoked=issued.auth_token.revoked_at is not None,
runtime_id=issued.auth_token.runtime_id,
daemon_id=issued.auth_token.daemon_id,
token=issued.token,
)
render_service_token_result(ctx.obj.console, ctx.obj.output_format, response)
if ctx.obj.output_format != "json":
ctx.obj.console.print(f"masked_token: {mask_token_text(issued.token)}")
@token_app.command("revoke")
def revoke_service_token(
ctx: typer.Context,
name: str = typer.Argument(..., help="Service token name to revoke."),
force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation prompt."),
) -> None:
if not force:
confirmed = typer.confirm(f"서비스 토큰 '{name}'을 폐기하시겠습니까?")
if not confirmed:
raise typer.Exit(code=0)
def _revoke(service: AuthService, app_context):
return service.revoke_service_token(name)
revoked_at = _with_service(ctx, _revoke)
response = ServiceTokenRevokeCliResponse(
token_id="",
name=name,
revoked=True,
revoked_at=revoked_at,
)
render_service_token_result(ctx.obj.console, ctx.obj.output_format, response)