""" API Key Management Endpoints Provides REST API for managing API keys """ from typing import Optional, List from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, Request from sqlmodel import Session from pydantic import BaseModel, ConfigDict, ConfigDict, Field from apps.auth.services.api_key_service import APIKeyService from apps.auth.models.api_key import APIKey, APIKeyStatus from apps.auth.models.user import AuthUser from core.database import get_db_session from apps.auth.api.dependencies import get_current_user router = APIRouter(prefix="/api/v1/auth/api-keys", tags=["API Keys"]) # ======================================================================== # Request/Response Models # ======================================================================== class CreateAPIKeyRequest(BaseModel): """Request model for creating an API key.""" name: str = Field( ..., min_length=1, max_length=100, description="Descriptive name for the API key" ) scopes: List[str] = Field(default=["read"], description="Scopes: read, write, admin") expires_days: Optional[int] = Field( None, gt=0, description="Days until expiration (None = no expiration)" ) allowed_ips: Optional[List[str]] = Field( None, description="Allowed IP addresses (None = any IP)" ) rate_limit_override: Optional[int] = Field( None, gt=0, description="Custom rate limit (requests per hour)" ) class APIKeyResponse(BaseModel): """Response model for API key (without full key).""" id: int name: str key_prefix: str user_id: int status: APIKeyStatus expires_at: Optional[datetime] scopes: str allowed_ips: Optional[str] rate_limit_override: Optional[int] last_used_at: Optional[datetime] request_count: int created_at: datetime revoked_at: Optional[datetime] revoked_by: Optional[str] revoke_reason: Optional[str] model_config = ConfigDict(from_attributes=True) class CreateAPIKeyResponse(BaseModel): """Response when creating a new API key (includes full key ONCE).""" api_key: str = Field(..., description="Full API key - SAVE THIS! It won't be shown again.") key_info: APIKeyResponse class RevokeAPIKeyRequest(BaseModel): """Request model for revoking an API key.""" reason: Optional[str] = Field(None, max_length=500, description="Reason for revocation") class UsageStatsResponse(BaseModel): """Response model for API key usage statistics.""" total_requests: int date_range_days: int endpoints: dict status_codes: dict avg_response_time_ms: float # ======================================================================== # Endpoints # ======================================================================== @router.post("", response_model=CreateAPIKeyResponse, status_code=201) def create_api_key( request: CreateAPIKeyRequest, current_user: AuthUser = Depends(get_current_user), session: Session = Depends(get_db_session), ): """ Create a new API key for the current user. The full API key is returned ONCE in the response and cannot be retrieved again. Store it securely - if lost, you'll need to generate a new key. """ service = APIKeyService(session) # Validate scopes valid_scopes = {"read", "write", "admin"} invalid_scopes = set(request.scopes) - valid_scopes if invalid_scopes: raise HTTPException( status_code=400, detail=f"Invalid scopes: {invalid_scopes}. Valid scopes: {valid_scopes}", ) # Admin users can create admin-scoped keys if "admin" in request.scopes and not current_user.is_admin: raise HTTPException( status_code=403, detail="Only admin users can create API keys with admin scope" ) # Generate API key full_key, api_key = service.generate_api_key( user=current_user, name=request.name, scopes=request.scopes, expires_days=request.expires_days, allowed_ips=request.allowed_ips, rate_limit_override=request.rate_limit_override, ) return CreateAPIKeyResponse(api_key=full_key, key_info=APIKeyResponse.model_validate(api_key)) @router.get("", response_model=List[APIKeyResponse]) def list_api_keys( include_revoked: bool = False, current_user: AuthUser = Depends(get_current_user), session: Session = Depends(get_db_session), ): """ List all API keys for the current user. By default, only active keys are returned. Use include_revoked=true to also see revoked keys. """ service = APIKeyService(session) keys = service.list_user_keys(current_user.id, include_revoked=include_revoked) return [APIKeyResponse.model_validate(key) for key in keys] @router.get("/{key_id}", response_model=APIKeyResponse) def get_api_key( key_id: int, current_user: AuthUser = Depends(get_current_user), session: Session = Depends(get_db_session), ): """ Get details for a specific API key. Users can only access their own keys. """ api_key = session.get(APIKey, key_id) if not api_key: raise HTTPException(status_code=404, detail="API key not found") # Authorization check if api_key.user_id != current_user.id and not current_user.is_admin: raise HTTPException(status_code=403, detail="Access denied") return APIKeyResponse.model_validate(api_key) @router.delete("/{key_id}", response_model=APIKeyResponse) def revoke_api_key( key_id: int, revoke_request: RevokeAPIKeyRequest, current_user: AuthUser = Depends(get_current_user), session: Session = Depends(get_db_session), ): """ Revoke an API key. Once revoked, the key can no longer be used for authentication. Users can only revoke their own keys. """ api_key = session.get(APIKey, key_id) if not api_key: raise HTTPException(status_code=404, detail="API key not found") # Authorization check if api_key.user_id != current_user.id and not current_user.is_admin: raise HTTPException(status_code=403, detail="Access denied") service = APIKeyService(session) revoked_key = service.revoke_api_key( api_key_id=key_id, revoked_by=current_user.username, reason=revoke_request.reason ) if not revoked_key: raise HTTPException(status_code=404, detail="API key not found") return APIKeyResponse.model_validate(revoked_key) @router.post("/{key_id}/rotate", response_model=CreateAPIKeyResponse) def rotate_api_key( key_id: int, current_user: AuthUser = Depends(get_current_user), session: Session = Depends(get_db_session), ): """ Rotate an API key (generate new key with same settings, revoke old one). The new full API key is returned ONCE in the response. Store it securely - if lost, you'll need to rotate again. """ api_key = session.get(APIKey, key_id) if not api_key: raise HTTPException(status_code=404, detail="API key not found") # Authorization check if api_key.user_id != current_user.id and not current_user.is_admin: raise HTTPException(status_code=403, detail="Access denied") service = APIKeyService(session) try: new_key, new_api_key = service.rotate_api_key( old_key_id=key_id, revoked_by=current_user.username ) except ValueError as e: raise HTTPException(status_code=404, detail=str(e)) return CreateAPIKeyResponse( api_key=new_key, key_info=APIKeyResponse.model_validate(new_api_key) ) @router.get("/{key_id}/usage", response_model=UsageStatsResponse) def get_api_key_usage( key_id: int, days: int = 30, current_user: AuthUser = Depends(get_current_user), session: Session = Depends(get_db_session), ): """ Get usage statistics for an API key. Returns request counts, endpoints accessed, status codes, and average response time for the specified time period. """ api_key = session.get(APIKey, key_id) if not api_key: raise HTTPException(status_code=404, detail="API key not found") # Authorization check if api_key.user_id != current_user.id and not current_user.is_admin: raise HTTPException(status_code=403, detail="Access denied") service = APIKeyService(session) stats = service.get_usage_stats(api_key_id=key_id, days=days) return UsageStatsResponse(**stats)