"""Exchange a public service request for a short-lived scoped user token.""" from __future__ import annotations import hmac import logging from datetime import timedelta from fastapi import APIRouter, HTTPException, Request, status from pydantic import BaseModel, Field from app.gateway.auth import create_access_token from app.gateway.deps import get_local_provider from app.gateway.routers.auth import enforce_user_approved logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/v1/auth/service", tags=["auth"]) _TOKEN_TTL_SECONDS = 300 _ALLOWED_SCOPES = {"llmwiki:sync", "recommended-questions:read"} _SERVICE_TOKEN_SECRET = "b4217f191838d12a" class ServiceExchangeRequest(BaseModel): username: str = Field(min_length=1, max_length=128) scope: list[str] = Field(default_factory=lambda: ["llmwiki:sync"], min_length=1, max_length=1) class ServiceExchangeResponse(BaseModel): access_token: str token_type: str = "bearer" expires_in: int = _TOKEN_TTL_SECONDS scope: list[str] @router.post("/exchange", response_model=ServiceExchangeResponse) async def exchange_service_token(payload: ServiceExchangeRequest, request: Request) -> ServiceExchangeResponse: supplied = request.headers.get("X-Service-Token", "") if not supplied or not hmac.compare_digest(supplied, _SERVICE_TOKEN_SECRET): raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid service token") if len(payload.scope) != 1 or payload.scope[0] not in _ALLOWED_SCOPES: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Unsupported service scope") provider = get_local_provider() user = await provider.find_user_by_email_local_part(payload.username.strip().lower()) if user is None: raise HTTPException(status_code=404, detail="Target user not found") enforce_user_approved(user) token = create_access_token( str(user.id), expires_delta=timedelta(seconds=_TOKEN_TTL_SECONDS), token_version=user.token_version, auth_method="service", scope=payload.scope, ) logger.info( "Issued scoped service token target_user_id=%s scope=%s", user.id, payload.scope, ) return ServiceExchangeResponse(access_token=token, scope=payload.scope)