Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /GRID-INTELLIGENCE_GRID /src /application /mothership /routers /auth.py
| """ | |
| Authentication and token management endpoints. | |
| Provides JWT token generation, refresh, validation, and user registration endpoints. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import os | |
| from typing import Any | |
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from pydantic import BaseModel, EmailStr, Field | |
| from application.mothership.dependencies import ( | |
| Auth, | |
| PublicRateLimited, | |
| RateLimited, | |
| RequestContext, | |
| Settings, | |
| get_optional_authentication, | |
| ) | |
| from application.mothership.schemas import ApiResponse, ResponseMeta | |
| from application.mothership.security.credential_validation import validate_production_credentials | |
| from application.mothership.security.jwt import get_jwt_manager | |
| from application.mothership.security.rbac import Role, get_permissions_for_role | |
| from application.mothership.security.token_revocation import get_token_validator | |
| from grid.organization.models import UserRole | |
| logger = logging.getLogger(__name__) | |
| _USER_ROLE_TO_RBAC: dict[UserRole, Role] = { | |
| UserRole.ADMIN: Role.ADMIN, | |
| UserRole.MANAGER: Role.WRITER, | |
| UserRole.DEVELOPER: Role.WRITER, | |
| UserRole.ANALYST: Role.READER, | |
| UserRole.VIEWER: Role.READER, | |
| UserRole.GUEST: Role.ANONYMOUS, | |
| } | |
| router = APIRouter(prefix="/auth", tags=["authentication"]) | |
| class LoginRequest(BaseModel): | |
| """Login request payload.""" | |
| username: str = Field(..., description="Username or email", min_length=1, max_length=255) | |
| password: str = Field(..., description="User password", min_length=1, max_length=255) | |
| scopes: list[str] = Field(default_factory=lambda: ["read", "write"], description="Requested scopes") | |
| class TokenResponse(BaseModel): | |
| """Token response.""" | |
| access_token: str = Field(..., description="JWT access token") | |
| refresh_token: str = Field(..., description="JWT refresh token") | |
| token_type: str = Field(default="bearer", description="Token type") | |
| expires_in: int = Field(..., description="Token expiration in seconds") | |
| scopes: list[str] = Field(default_factory=list, description="Granted scopes") | |
| class RefreshRequest(BaseModel): | |
| """Token refresh request.""" | |
| refresh_token: str = Field(..., description="Valid refresh token") | |
| class RefreshResponse(BaseModel): | |
| """Token refresh response.""" | |
| access_token: str = Field(..., description="New access token") | |
| token_type: str = Field(default="bearer", description="Token type") | |
| expires_in: int = Field(..., description="Token expiration in seconds") | |
| class ValidateResponse(BaseModel): | |
| """Token validation response.""" | |
| valid: bool = Field(..., description="Whether token is valid") | |
| user_id: str | None = Field(None, description="User ID from token") | |
| email: str | None = Field(None, description="Email from token") | |
| scopes: list[str] = Field(default_factory=list, description="Token scopes") | |
| expires_at: int | None = Field(None, description="Token expiration timestamp") | |
| class UserResponse(BaseModel): | |
| """Current user response.""" | |
| id: str = Field(..., description="User ID") | |
| username: str = Field(..., description="Username") | |
| email: str = Field(..., description="Email address") | |
| full_name: str | None = Field(None, description="Full name") | |
| trust_tier: str = Field(default="standard", description="Trust tier") | |
| is_active: bool = Field(default=True, description="Whether user is active") | |
| scopes: list[str] = Field(default_factory=list, description="User scopes") | |
| class RegisterRequest(BaseModel): | |
| """User registration request.""" | |
| username: str = Field(..., description="Username", min_length=3, max_length=50) | |
| email: EmailStr = Field(..., description="Email address") | |
| password: str = Field(..., description="Password", min_length=8, max_length=255) | |
| full_name: str | None = Field(None, description="Full name", max_length=255) | |
| async def register_user( | |
| request: RegisterRequest, | |
| _: PublicRateLimited, | |
| request_context: RequestContext, | |
| ) -> ApiResponse[UserResponse]: | |
| """ | |
| Register a new user account. | |
| Creates a new user with BASIC trust tier. In development mode, | |
| this creates the user without external dependencies. In production, | |
| this would integrate with the user store. | |
| Args: | |
| request: Registration details | |
| _: Rate limiting enforcement | |
| request_context: Request context | |
| Returns: | |
| API response with created user details | |
| Raises: | |
| HTTPException: If registration fails (e.g., user already exists) | |
| """ | |
| request_id = request_context.get("request_id", "unknown") | |
| # Generate unique user ID | |
| import uuid | |
| user_id = str(uuid.uuid4()) | |
| # In a real implementation, this would: | |
| # 1. Check if email/username already exists | |
| # 2. Hash the password securely | |
| # 3. Store user in database | |
| # 4. Potentially send verification email | |
| # For now, we simulate successful registration | |
| logger.info("User registered: %s (%s) (request_id=%s)", request.username, request.email, request_id) | |
| response_data = UserResponse( | |
| id=user_id, | |
| username=request.username, | |
| email=request.email, | |
| full_name=request.full_name, | |
| trust_tier="BASIC", # New users start with BASIC tier | |
| is_active=True, | |
| scopes=["read"], # New users get read-only by default | |
| ) | |
| return ApiResponse( | |
| success=True, | |
| data=response_data, | |
| meta=ResponseMeta(request_id=request_id), | |
| ) | |
| async def login( | |
| request: LoginRequest, | |
| _: PublicRateLimited, | |
| settings: Settings, | |
| request_context: RequestContext, | |
| ) -> ApiResponse[TokenResponse]: | |
| """ | |
| Authenticate user and generate JWT tokens. | |
| **Development / Testing Mode:** | |
| - Any username/password combination is accepted | |
| - Tokens are generated for testing purposes | |
| **Production Mode:** | |
| - Credentials are validated against user store | |
| - Secure password hashing verification | |
| - Failed attempts are logged and rate-limited | |
| Args: | |
| request: Login credentials | |
| _: Rate limiting enforcement | |
| settings: Application settings | |
| request_context: Request context | |
| Returns: | |
| API response with token pair | |
| Raises: | |
| HTTPException: If authentication fails | |
| """ | |
| request_id = request_context.get("request_id", "unknown") | |
| auth_result = None | |
| # CRIT-2: Require explicit ALLOW_DEV_LOGIN_BYPASS=1; never set in production. | |
| allow_test_credential_bypass = (settings.is_development or settings.is_testing) and os.getenv( | |
| "ALLOW_DEV_LOGIN_BYPASS", "" | |
| ).strip() == "1" | |
| if allow_test_credential_bypass: | |
| logger.warning( | |
| "DEV LOGIN BYPASS: credentials not validated (username=%s, request_id=%s). Set ALLOW_DEV_LOGIN_BYPASS=0 to enforce.", | |
| request.username, | |
| request_id, | |
| ) | |
| # Only production-like environments enforce credential validation. | |
| if not allow_test_credential_bypass: | |
| auth_result = await validate_production_credentials(request.username, request.password) | |
| if not auth_result.success: | |
| logger.warning( | |
| "Authentication failed for user: %s, reason: %s (request_id=%s)", | |
| request.username, | |
| auth_result.error_code, | |
| request_id, | |
| ) | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail=auth_result.error_message or "Authentication failed", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Generate JWT token pair | |
| # Convert empty string to None to allow env var fallback | |
| secret_key_param = ( | |
| settings.security.secret_key if settings.security.secret_key and settings.security.secret_key.strip() else None | |
| ) | |
| jwt_manager = get_jwt_manager( | |
| secret_key=secret_key_param, | |
| environment=settings.environment.value, | |
| algorithm=settings.security.algorithm, | |
| access_token_expire_minutes=settings.security.access_token_expire_minutes, | |
| refresh_token_expire_days=settings.security.refresh_token_expire_days, | |
| ) | |
| # Server-resolved permissions — client scopes ignored to prevent escalation. | |
| # The user's organizational role is expanded to granular RBAC permissions and | |
| # embedded as scopes in the token. verify_jwt_token reads them back directly. | |
| if not allow_test_credential_bypass and auth_result and auth_result.user: | |
| user_id = auth_result.user.user_id | |
| email = auth_result.user.email or f"{request.username}@example.com" | |
| rbac_role = _USER_ROLE_TO_RBAC.get(auth_result.user.role, Role.READER) | |
| granted_scopes = sorted(get_permissions_for_role(rbac_role)) | |
| else: | |
| user_id = f"user_{request.username}" | |
| email = f"{request.username}@example.com" if "@" not in request.username else request.username | |
| granted_scopes = sorted(get_permissions_for_role(Role.WRITER)) | |
| try: | |
| token_pair = jwt_manager.create_token_pair( | |
| subject=request.username, | |
| scopes=granted_scopes, | |
| user_id=user_id, | |
| email=email, | |
| metadata={ | |
| "login_method": "password", | |
| "request_id": request_id, | |
| }, | |
| ) | |
| response_data = TokenResponse( | |
| access_token=token_pair.access_token, | |
| refresh_token=token_pair.refresh_token, | |
| token_type=token_pair.token_type, | |
| expires_in=token_pair.expires_in, | |
| scopes=granted_scopes, | |
| ) | |
| logger.info("User authenticated successfully: %s (request_id=%s)", request.username, request_id) | |
| return ApiResponse( | |
| success=True, | |
| data=response_data, | |
| meta=ResponseMeta(request_id=request_id), | |
| ) | |
| except Exception as e: | |
| logger.exception("Token generation failed for user: %s", request.username) | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail="Authentication failed - unable to generate tokens", | |
| ) from e | |
| async def refresh_token( | |
| request: RefreshRequest, | |
| _: PublicRateLimited, | |
| settings: Settings, | |
| request_context: RequestContext, | |
| ) -> ApiResponse[RefreshResponse]: | |
| """ | |
| Refresh an access token using a valid refresh token. | |
| Args: | |
| request: Refresh token | |
| _: Rate limiting enforcement | |
| settings: Application settings | |
| request_context: Request context | |
| Returns: | |
| API response with new access token | |
| Raises: | |
| HTTPException: If refresh token is invalid or expired | |
| """ | |
| request_id = request_context.get("request_id", "unknown") | |
| # Convert empty string to None to allow env var fallback (matches login endpoint) | |
| secret_key_param = ( | |
| settings.security.secret_key if settings.security.secret_key and settings.security.secret_key.strip() else None | |
| ) | |
| jwt_manager = get_jwt_manager( | |
| secret_key=secret_key_param, | |
| environment=settings.environment.value, | |
| algorithm=settings.security.algorithm, | |
| access_token_expire_minutes=settings.security.access_token_expire_minutes, | |
| refresh_token_expire_days=settings.security.refresh_token_expire_days, | |
| ) | |
| try: | |
| # Generate new access token from refresh token. | |
| # CRIT-3: revocation check (JTI-keyed) is performed inside refresh_access_token(). | |
| new_access_token = await jwt_manager.refresh_access_token(request.refresh_token) | |
| response_data = RefreshResponse( | |
| access_token=new_access_token, | |
| token_type="bearer", | |
| expires_in=settings.security.access_token_expire_minutes * 60, | |
| ) | |
| logger.info("Token refreshed successfully (request_id=%s)", request_id) | |
| return ApiResponse( | |
| success=True, | |
| data=response_data, | |
| meta=ResponseMeta(request_id=request_id), | |
| ) | |
| except Exception as e: | |
| logger.warning("Token refresh failed: %s (request_id=%s)", str(e), request_id) | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired refresh token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) from e | |
| async def validate_token( | |
| request_context: RequestContext, | |
| auth: dict[str, Any] = Depends(get_optional_authentication), | |
| ) -> ApiResponse[ValidateResponse]: | |
| """ | |
| Validate the current authentication token. | |
| Callable without a token; returns 200 with valid=False when unauthenticated. | |
| Use to check whether the current request is authenticated. | |
| """ | |
| request_id = request_context.get("request_id", "unknown") | |
| token_payload = auth.get("token_payload", {}) | |
| permissions = auth.get("permissions") or set() | |
| scopes = list(token_payload.get("scopes")) if token_payload.get("scopes") is not None else list(permissions) | |
| response_data = ValidateResponse( | |
| valid=auth.get("authenticated", False), | |
| user_id=auth.get("user_id"), | |
| email=auth.get("email"), | |
| scopes=scopes, | |
| expires_at=token_payload.get("exp"), | |
| ) | |
| return ApiResponse( | |
| success=True, | |
| data=response_data, | |
| meta=ResponseMeta(request_id=request_id), | |
| ) | |
| async def get_current_user( | |
| auth: Auth, | |
| request_context: RequestContext, | |
| ) -> ApiResponse[UserResponse]: | |
| """ | |
| Get current authenticated user information. | |
| Returns details about the currently authenticated user based on the JWT token. | |
| Args: | |
| auth: Authentication context (automatically validated) | |
| request_context: Request context | |
| Returns: | |
| API response with current user details | |
| """ | |
| request_id = request_context.get("request_id", "unknown") | |
| token_payload = auth.get("token_payload", {}) | |
| # Extract user info from auth context | |
| user_id = auth.get("user_id", "unknown") | |
| email = auth.get("email", "") | |
| username = token_payload.get("sub", "") | |
| scopes = list( | |
| token_payload.get("scopes") if token_payload.get("scopes") is not None else auth.get("permissions", []) | |
| ) | |
| response_data = UserResponse( | |
| id=user_id, | |
| username=username, | |
| email=email, | |
| full_name=None, # Could be populated from user store in production | |
| trust_tier="standard", # Default tier, could be from user store | |
| is_active=True, | |
| scopes=scopes, | |
| ) | |
| return ApiResponse( | |
| success=True, | |
| data=response_data, | |
| meta=ResponseMeta(request_id=request_id), | |
| ) | |
| async def logout( | |
| auth: Auth, | |
| request_context: RequestContext, | |
| ) -> ApiResponse[dict[str, Any]]: | |
| """ | |
| Logout and invalidate current session. | |
| Revokes the current JWT token by adding it to the revocation list. | |
| The token will be invalid for future requests after logout. | |
| Args: | |
| auth: Authentication context | |
| request_context: Request context | |
| Returns: | |
| API response with logout confirmation | |
| """ | |
| request_id = request_context.get("request_id", "unknown") | |
| user_id = auth.get("user_id", "unknown") | |
| token_payload = auth.get("token_payload", {}) | |
| # Revoke the token | |
| revoked = False | |
| if token_payload: | |
| validator = get_token_validator() | |
| revoked = await validator.revoke_token(token_payload, reason="logout") | |
| if revoked: | |
| logger.info("Token revoked for user: %s (request_id=%s)", user_id, request_id) | |
| else: | |
| logger.warning("Failed to revoke token for user: %s (request_id=%s)", user_id, request_id) | |
| logger.info("User logged out: %s (request_id=%s)", user_id, request_id) | |
| return ApiResponse( | |
| success=True, | |
| data={ | |
| "message": "Logged out successfully", | |
| "user_id": user_id, | |
| "token_revoked": revoked, | |
| }, | |
| meta=ResponseMeta(request_id=request_id), | |
| ) | |
| # Rebuild models for Pydantic v2 | |
| LoginRequest.model_rebuild() | |
| TokenResponse.model_rebuild() | |
| RefreshRequest.model_rebuild() | |
| RefreshResponse.model_rebuild() | |
| ValidateResponse.model_rebuild() | |
| UserResponse.model_rebuild() | |
| RegisterRequest.model_rebuild() | |
Xet Storage Details
- Size:
- 16.6 kB
- Xet hash:
- 0734d1679094803cc1a01d1b421847f8da6ff85ce8ca7a503aa72d23b5447378
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.