feat: dcy-003/004 토큰 surface 개편 및 daemon lifecycle 정책 구현 (BAT-006/007)
BAT-006 (REQ-016/017/018): - client token 발급 경로 제거 (issue_client_token, POST /auth/tokens, 관련 스키마/테스트) - service-token rotate unique index revoked_at IS NULL 조건 추가 (Alembic CONCURRENTLY 마이그레이션) - POST /auth/service-tokens body daemon_id forward 누락 보정 (1-line fix) BAT-007 (REQ-022/023): - daemon deactivate 시 바인딩 service token 자동 revoke (CLI --force 옵션 + revoke_tokens_by_daemon_id) - NULL daemon_id legacy token 진단 CLI (migrate-null-daemon --dry-run) 거버넌스 문서: dcy-003/004 Discovery, REQ-016~023/025~032 신규, BAT-006/007 전체 산출물 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+2
-22
@@ -10,15 +10,13 @@ from app.core.auth import AuthContext, require_admin, require_read
|
||||
from app.domain.models import AuthToken, User
|
||||
from app.schemas.auth import (
|
||||
AuthTokenResponse,
|
||||
CreateClientTokenRequest,
|
||||
IssuedClientTokenResponse,
|
||||
IssueServiceTokenRequest,
|
||||
IssueServiceTokenApiResponse,
|
||||
LoginRequest,
|
||||
TokenResponse,
|
||||
)
|
||||
from app.schemas.user import UserResponse
|
||||
from app.services.auth_service import AuthService, IssuedClientToken, LoginResult, get_auth_service
|
||||
from app.services.auth_service import AuthService, LoginResult, get_auth_service
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
@@ -60,13 +58,6 @@ def _to_login_response(result: LoginResult) -> TokenResponse:
|
||||
)
|
||||
|
||||
|
||||
def _to_issued_token_response(result: IssuedClientToken) -> IssuedClientTokenResponse:
|
||||
return IssuedClientTokenResponse(
|
||||
token=result.token,
|
||||
auth_token=_to_auth_token_response(result.auth_token),
|
||||
)
|
||||
|
||||
|
||||
def _raise_auth_error(exc: ValueError) -> NoReturn:
|
||||
detail = str(exc)
|
||||
if "잘못된 사용자명 또는 비밀번호" in detail:
|
||||
@@ -97,18 +88,6 @@ def list_tokens(
|
||||
_raise_auth_error(exc)
|
||||
|
||||
|
||||
@router.post("/tokens", response_model=IssuedClientTokenResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_read)])
|
||||
def create_token(
|
||||
payload: CreateClientTokenRequest,
|
||||
auth_context: AuthContext = Depends(require_read),
|
||||
service: AuthService = Depends(get_auth_service),
|
||||
) -> IssuedClientTokenResponse:
|
||||
try:
|
||||
return _to_issued_token_response(service.issue_client_token(auth_context, payload))
|
||||
except ValueError as exc:
|
||||
_raise_auth_error(exc)
|
||||
|
||||
|
||||
@router.delete("/tokens/{token_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(require_read)])
|
||||
def revoke_token(
|
||||
token_id: str,
|
||||
@@ -134,6 +113,7 @@ def issue_service_token(
|
||||
permission=payload.permission,
|
||||
expires_in_days=payload.expires_in_days,
|
||||
no_expiry=payload.no_expiry,
|
||||
daemon_id=payload.daemon_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
_raise_auth_error(exc)
|
||||
|
||||
@@ -66,8 +66,14 @@ def update_daemon(
|
||||
display_name: Optional[str] = typer.Option(None, "--display-name", help="New display name."),
|
||||
deactivate: bool = typer.Option(False, "--deactivate", help="Mark daemon as inactive."),
|
||||
activate: bool = typer.Option(False, "--activate", help="Mark daemon as active."),
|
||||
force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation when deactivating."),
|
||||
) -> None:
|
||||
"""Update a daemon registry entry."""
|
||||
if deactivate and not force:
|
||||
confirmed = typer.confirm(f"Daemon {daemon_id}을(를) 비활성화하면 바인딩된 service token이 즉시 revoke됩니다. 계속하시겠습니까?")
|
||||
if not confirmed:
|
||||
raise typer.Exit(code=0)
|
||||
|
||||
def _update(repo, app_context):
|
||||
is_active: bool | None = None
|
||||
if deactivate and activate:
|
||||
@@ -76,7 +82,11 @@ def update_daemon(
|
||||
is_active = False
|
||||
elif activate:
|
||||
is_active = True
|
||||
return repo.update_daemon(daemon_id, display_name=display_name, is_active=is_active)
|
||||
result = repo.update_daemon(daemon_id, display_name=display_name, is_active=is_active)
|
||||
if deactivate:
|
||||
revoked_count = repo.revoke_tokens_by_daemon_id(daemon_id)
|
||||
app_context.console.print(f"Revoked {revoked_count} service token(s) bound to daemon {daemon_id}.")
|
||||
return result
|
||||
|
||||
result = _with_service(ctx, _update)
|
||||
render_output(ctx.obj.console, ctx.obj.output_format, result)
|
||||
|
||||
@@ -162,3 +162,36 @@ def revoke_service_token(
|
||||
revoked_at=revoked_at,
|
||||
)
|
||||
render_service_token_result(ctx.obj.console, ctx.obj.output_format, response)
|
||||
|
||||
|
||||
@token_app.command("migrate-null-daemon")
|
||||
def migrate_null_daemon(
|
||||
ctx: typer.Context,
|
||||
dry_run: bool = typer.Option(False, "--dry-run", help="Inspect NULL daemon tokens without making changes."),
|
||||
) -> None:
|
||||
"""Diagnose and report active service tokens with no daemon binding (NULL daemon_id)."""
|
||||
if not dry_run:
|
||||
ctx.obj.console.print(
|
||||
"[red]자동 변경은 지원하지 않습니다.[/red] "
|
||||
"먼저 --dry-run으로 inventory를 확인한 후 "
|
||||
"token별로 `pfhub service-token rebind NAME --daemon-id ID` 또는 "
|
||||
"`pfhub service-token revoke NAME`을 수동 실행하세요."
|
||||
)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
def _inspect(service: AuthService, app_context):
|
||||
tokens = service.list_null_daemon_service_tokens()
|
||||
if not tokens:
|
||||
app_context.console.print("no NULL daemon tokens found.")
|
||||
return
|
||||
|
||||
for token in tokens:
|
||||
candidates = service.find_candidate_daemons_for_user(token.user_id)
|
||||
candidate_ids = [d.id for d in candidates]
|
||||
match_note = f"candidates={candidate_ids}" if candidate_ids else "[yellow]no candidate daemons for this user[/yellow]"
|
||||
app_context.console.print(
|
||||
f"id={token.id} user_id={token.user_id} name={token.name} "
|
||||
f"runtime_id={token.runtime_id} created_at={token.created_at} {match_note}"
|
||||
)
|
||||
|
||||
_with_service(ctx, _inspect)
|
||||
|
||||
@@ -110,6 +110,10 @@ class PortfolioRepository(Protocol):
|
||||
is_active: bool | None = None,
|
||||
) -> Daemon: ...
|
||||
|
||||
def revoke_tokens_by_daemon_id(self, daemon_id: str) -> int: ...
|
||||
|
||||
def list_service_tokens_with_null_daemon(self) -> list[AuthToken]: ...
|
||||
|
||||
def get(self, portfolio_id: str) -> Portfolio: ...
|
||||
|
||||
def get_portfolio_by_name_and_user(self, owner_user_id: str, name: str) -> Portfolio | None: ...
|
||||
|
||||
@@ -188,7 +188,7 @@ class PostgresPortfolioRepository:
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_auth_tokens_service_name_unique
|
||||
ON auth_tokens (name)
|
||||
WHERE token_type = 'service'
|
||||
WHERE token_type = 'service' AND revoked_at IS NULL
|
||||
"""
|
||||
)
|
||||
cur.execute(
|
||||
@@ -1952,6 +1952,26 @@ class PostgresPortfolioRepository:
|
||||
row = cur.fetchone()
|
||||
return self._row_to_daemon(row)
|
||||
|
||||
def revoke_tokens_by_daemon_id(self, daemon_id: str) -> int:
|
||||
self.ensure_schema()
|
||||
with self._connect().cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE auth_tokens SET revoked_at = NOW() WHERE daemon_id = %s AND revoked_at IS NULL",
|
||||
(daemon_id,),
|
||||
)
|
||||
return cur.rowcount
|
||||
|
||||
def list_service_tokens_with_null_daemon(self) -> list[AuthToken]:
|
||||
self.ensure_schema()
|
||||
with self._connect().cursor() as cur:
|
||||
cur.execute(
|
||||
_SELECT_AUTH_TOKEN
|
||||
+ "WHERE token_type = 'service' AND daemon_id IS NULL AND revoked_at IS NULL "
|
||||
+ "ORDER BY created_at ASC",
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
return [self._row_to_auth_token(row) for row in rows]
|
||||
|
||||
|
||||
def database_exists(config: PortfolioDBConfig, *, maintenance_db: str = "postgres") -> bool:
|
||||
with psycopg.connect(
|
||||
|
||||
@@ -31,20 +31,6 @@ class TokenResponse(BaseModel):
|
||||
user: UserResponse
|
||||
|
||||
|
||||
class CreateClientTokenRequest(BaseModel):
|
||||
name: str = Field(min_length=1)
|
||||
permission: Literal["read", "trade-write", "admin"] | None = None
|
||||
expires_in_days: int | None = Field(default=None, ge=1, le=3650)
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def normalize_name(cls, value: str) -> str:
|
||||
normalized = value.strip()
|
||||
if not normalized:
|
||||
raise ValueError("name은 비어 있을 수 없습니다")
|
||||
return normalized
|
||||
|
||||
|
||||
class AuthTokenResponse(BaseModel):
|
||||
id: str
|
||||
user_id: str
|
||||
@@ -59,12 +45,6 @@ class AuthTokenResponse(BaseModel):
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
class IssuedClientTokenResponse(BaseModel):
|
||||
token: str
|
||||
token_type: Literal["bearer"] = "bearer"
|
||||
auth_token: AuthTokenResponse
|
||||
|
||||
|
||||
class IssuedServiceToken(BaseModel):
|
||||
token: str
|
||||
token_type: Literal["bearer"] = "bearer"
|
||||
|
||||
@@ -18,7 +18,6 @@ from app.domain.models import AuthToken, User
|
||||
from app.repositories.factory import get_portfolio_repository_from_settings
|
||||
from app.repositories.portfolio_repository import PortfolioRepository
|
||||
from app.schemas.auth import (
|
||||
CreateClientTokenRequest,
|
||||
LoginRequest,
|
||||
)
|
||||
|
||||
@@ -30,12 +29,6 @@ class LoginResult:
|
||||
user: User
|
||||
|
||||
|
||||
@dataclass
|
||||
class IssuedClientToken:
|
||||
token: str
|
||||
auth_token: AuthToken
|
||||
|
||||
|
||||
@dataclass
|
||||
class IssuedServiceToken:
|
||||
token: str
|
||||
@@ -71,30 +64,6 @@ class AuthService:
|
||||
refreshed_user = self._repository.get_user(user.id)
|
||||
return LoginResult(token=raw_token, auth_token=auth_token, user=refreshed_user)
|
||||
|
||||
def issue_client_token(self, auth_context: AuthContext, payload: CreateClientTokenRequest) -> IssuedClientToken:
|
||||
if auth_context.token_type == "service":
|
||||
raise ValueError("서비스 토큰으로는 사용자 클라이언트 토큰을 발급할 수 없습니다")
|
||||
if auth_context.user_id is None:
|
||||
raise ValueError("DB 사용자 컨텍스트에서만 클라이언트 토큰을 발급할 수 있습니다")
|
||||
|
||||
requested = Permission(payload.permission or auth_context.permission.value)
|
||||
if not _has_permission(auth_context.permission, requested):
|
||||
raise ValueError("요청한 토큰 권한이 현재 권한을 초과합니다")
|
||||
|
||||
raw_token = generate_token()
|
||||
expires_at = self._build_expiration(payload.expires_in_days, self._settings.client_token_default_ttl_days)
|
||||
|
||||
auth_token = self._repository.create_auth_token(
|
||||
auth_context.user_id,
|
||||
name=payload.name,
|
||||
token_hash=hash_token(raw_token),
|
||||
token_prefix=token_prefix(raw_token),
|
||||
permission=requested.value,
|
||||
token_type="client",
|
||||
expires_at=expires_at,
|
||||
)
|
||||
return IssuedClientToken(token=raw_token, auth_token=auth_token)
|
||||
|
||||
def list_tokens(self, auth_context: AuthContext) -> list[AuthToken]:
|
||||
if auth_context.token_type == "service":
|
||||
raise ValueError("서비스 토큰으로는 사용자 토큰 목록을 조회할 수 없습니다")
|
||||
@@ -183,6 +152,15 @@ class AuthService:
|
||||
self._repository.revoke_auth_token(existing.user_id, existing.id)
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
def revoke_tokens_for_daemon(self, daemon_id: str) -> int:
|
||||
return self._repository.revoke_tokens_by_daemon_id(daemon_id)
|
||||
|
||||
def list_null_daemon_service_tokens(self) -> list[AuthToken]:
|
||||
return self._repository.list_service_tokens_with_null_daemon()
|
||||
|
||||
def find_candidate_daemons_for_user(self, user_id: str) -> list:
|
||||
return self._repository.list_daemons_for_user(user_id)
|
||||
|
||||
def list_service_tokens(
|
||||
self,
|
||||
username: str | None = None,
|
||||
@@ -197,12 +175,6 @@ class AuthService:
|
||||
user_id = user.id
|
||||
return self._repository.list_service_tokens(user_id, include_revoked=include_revoked)
|
||||
|
||||
@staticmethod
|
||||
def _build_expiration(expires_in_days: int | None, default_days: int) -> datetime:
|
||||
days = normalize_expiry_days(expires_in_days, default_days=default_days)
|
||||
return datetime.now(timezone.utc) + timedelta(days=days)
|
||||
|
||||
|
||||
def get_auth_service(
|
||||
settings: Settings = Depends(get_settings),
|
||||
repository: PortfolioRepository = Depends(get_auth_service_repository),
|
||||
|
||||
Reference in New Issue
Block a user