Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /stateset_stateset-agents /stateset_agents /api /auth.py
| """ | |
| API Authentication Module | |
| Secure authentication and authorization for API services. | |
| """ | |
| import hmac | |
| import logging | |
| import secrets | |
| import time | |
| from datetime import datetime | |
| from typing import Any | |
| from fastapi import Request | |
| from fastapi.security import HTTPBearer | |
| from pydantic import BaseModel, Field | |
| from stateset_agents.utils.credentials import credential_fingerprint | |
| from .config import get_config | |
| from .errors import ForbiddenError, UnauthorizedError | |
| logger = logging.getLogger(__name__) | |
| # Security scheme for OpenAPI docs | |
| security_scheme = HTTPBearer(auto_error=False) | |
| # ============================================================================ | |
| # Models | |
| # ============================================================================ | |
| class TokenPayload(BaseModel): | |
| """JWT token payload.""" | |
| sub: str = Field(..., description="Subject (user ID)") | |
| roles: list[str] = Field(default_factory=list, description="User roles") | |
| exp: int = Field(..., description="Expiration timestamp") | |
| iat: int = Field(..., description="Issued at timestamp") | |
| jti: str = Field(..., description="JWT ID for revocation") | |
| class AuthenticatedUser(BaseModel): | |
| """Authenticated user context.""" | |
| user_id: str = Field(..., description="User identifier") | |
| roles: list[str] = Field(default_factory=list, description="User roles") | |
| api_key: str | None = Field(None, description="API key used (masked)") | |
| auth_method: str = Field("none", description="Authentication method used") | |
| email: str | None = Field(None, description="User email address") | |
| name: str | None = Field(None, description="User display name") | |
| metadata: dict[str, Any] | None = Field(None, description="Extra user metadata") | |
| def from_dict(cls, data: dict[str, Any]) -> "AuthenticatedUser": | |
| """Create AuthenticatedUser from dictionary.""" | |
| known = {f.alias or name for name, f in cls.model_fields.items()} | |
| extra = {k: v for k, v in data.items() if k not in known and k != "sub"} | |
| return cls( | |
| user_id=data.get("user_id", data.get("sub", "anonymous")), | |
| roles=data.get("roles", []), | |
| api_key=data.get("api_key"), | |
| auth_method=data.get("auth_method", "none"), | |
| email=data.get("email"), | |
| name=data.get("name"), | |
| metadata=extra or None, | |
| ) | |
| # ============================================================================ | |
| # JWT implementation | |
| # ============================================================================ | |
| class JWTHandler: | |
| """JWT handler backed by PyJWT's verified algorithm implementation.""" | |
| def __init__(self, secret: str, algorithm: str = "HS256"): | |
| self.secret = secret | |
| self.algorithm = algorithm | |
| def encode(self, payload: dict[str, Any]) -> str: | |
| """Encode a JWT token.""" | |
| import jwt | |
| return str(jwt.encode(payload, self.secret, algorithm=self.algorithm)) | |
| def decode(self, token: str) -> dict[str, Any] | None: | |
| """Decode and verify a JWT token.""" | |
| import jwt | |
| try: | |
| return dict(jwt.decode(token, self.secret, algorithms=[self.algorithm])) | |
| except jwt.ExpiredSignatureError: | |
| logger.warning("JWT token expired") | |
| return None | |
| except jwt.PyJWTError: | |
| logger.warning("JWT verification failed") | |
| return None | |
| # Global JWT handler (initialized lazily) | |
| _jwt_handler: JWTHandler | None = None | |
| _jwt_handler_config: tuple[str, str] | None = None | |
| def get_jwt_handler() -> JWTHandler: | |
| """Get the global JWT handler.""" | |
| global _jwt_handler, _jwt_handler_config | |
| config = get_config() | |
| jwt_secret = config.security.jwt_secret | |
| jwt_algorithm = config.security.jwt_algorithm | |
| if not jwt_secret: | |
| raise RuntimeError("JWT secret not configured") | |
| handler_config = (jwt_secret, jwt_algorithm) | |
| if _jwt_handler is None or _jwt_handler_config != handler_config: | |
| _jwt_handler = JWTHandler(jwt_secret, jwt_algorithm) | |
| _jwt_handler_config = handler_config | |
| return _jwt_handler | |
| # ============================================================================ | |
| # Token Generation | |
| # ============================================================================ | |
| def generate_token( | |
| user_id: str, | |
| roles: list[str], | |
| expiry_hours: int | None = None, | |
| ) -> str: | |
| """Generate a JWT token for a user.""" | |
| config = get_config() | |
| jwt = get_jwt_handler() | |
| now = int(time.time()) | |
| expiry = expiry_hours or config.security.jwt_expiry_hours | |
| payload = { | |
| "sub": user_id, | |
| "roles": roles, | |
| "iat": now, | |
| "exp": now + (expiry * 3600), | |
| "jti": secrets.token_urlsafe(16), | |
| } | |
| return jwt.encode(payload) | |
| def generate_api_key() -> str: | |
| """Generate a secure API key.""" | |
| return secrets.token_urlsafe(32) | |
| # ============================================================================ | |
| # Authentication Functions | |
| # ============================================================================ | |
| def _derive_api_user_id(api_key: str) -> str: | |
| """Derive a stable user id from API key material.""" | |
| return f"api_key:{credential_fingerprint(api_key)}" | |
| def _extract_bearer_token(request: Request) -> str | None: | |
| """Extract bearer token from Authorization header.""" | |
| auth_header = request.headers.get("Authorization", "") | |
| if auth_header.lower().startswith("bearer "): | |
| return str(auth_header.split(" ", 1)[1].strip()) | |
| return None | |
| def _extract_api_key(request: Request) -> str | None: | |
| """Extract API key from headers.""" | |
| # Check X-API-Key header first | |
| api_key = request.headers.get("X-API-Key") | |
| if api_key: | |
| return str(api_key.strip()) | |
| # Fall back to Authorization header | |
| return _extract_bearer_token(request) | |
| def authenticate_request( | |
| request: Request, *, force_auth: bool = False | |
| ) -> AuthenticatedUser: | |
| """ | |
| Authenticate a request using API key or JWT token. | |
| Returns: | |
| AuthenticatedUser with user information | |
| Raises: | |
| UnauthorizedError if authentication fails | |
| """ | |
| config = get_config() | |
| # Skip auth if not required | |
| if not config.security.require_auth and not force_auth: | |
| return AuthenticatedUser( | |
| user_id="anonymous", | |
| roles=["anonymous"], | |
| auth_method="none", | |
| ) | |
| # Try API key authentication first | |
| api_key = _extract_api_key(request) | |
| if api_key: | |
| matched_key = next( | |
| ( | |
| stored_key | |
| for stored_key in config.security.api_keys | |
| if hmac.compare_digest(stored_key, api_key) | |
| ), | |
| None, | |
| ) | |
| if matched_key is not None: | |
| roles = config.security.api_keys[matched_key] | |
| provided_user_id = request.headers.get("X-User-ID") | |
| if provided_user_id: | |
| logger.debug( | |
| "Ignoring untrusted X-User-ID header for API-key authenticated request", | |
| extra={ | |
| "client_ip": ( | |
| request.client.host if request.client else "unknown" | |
| ), | |
| "path": str(request.url.path), | |
| "provided_user_id": provided_user_id, | |
| }, | |
| ) | |
| user_id = _derive_api_user_id(api_key) | |
| return AuthenticatedUser( | |
| user_id=user_id, | |
| roles=roles, | |
| auth_method="api_key", | |
| ) | |
| # Try JWT token | |
| jwt = get_jwt_handler() | |
| payload = jwt.decode(api_key) | |
| if payload: | |
| return AuthenticatedUser( | |
| user_id=payload.get("sub", "unknown"), | |
| roles=payload.get("roles", []), | |
| auth_method="jwt", | |
| ) | |
| # Invalid credentials | |
| logger.warning( | |
| "Authentication failed: invalid API key or token", | |
| extra={ | |
| "client_ip": request.client.host if request.client else "unknown", | |
| "path": request.url.path, | |
| }, | |
| ) | |
| raise UnauthorizedError("Invalid API key or token") | |
| # No credentials provided | |
| raise UnauthorizedError( | |
| "Authentication required. Provide an API key or bearer token." | |
| ) | |
| def require_roles(*required_roles: str): | |
| """ | |
| Dependency that requires the user to have specific roles. | |
| Usage: | |
| @app.get("/admin") | |
| async def admin_endpoint(user: AuthenticatedUser = Depends(require_roles("admin"))): | |
| ... | |
| """ | |
| async def role_checker(request: Request) -> AuthenticatedUser: | |
| user = authenticate_request(request) | |
| # Check if user has any of the required roles | |
| if not any(role in user.roles for role in required_roles): | |
| logger.warning( | |
| "Authorization failed: insufficient roles", | |
| extra={ | |
| "user_id": user.user_id, | |
| "user_roles": user.roles, | |
| "required_roles": required_roles, | |
| "path": request.url.path, | |
| }, | |
| ) | |
| raise ForbiddenError( | |
| f"Insufficient permissions. Required role: {' or '.join(required_roles)}" | |
| ) | |
| return user | |
| return role_checker | |
| # ============================================================================ | |
| # FastAPI Dependencies | |
| # ============================================================================ | |
| async def get_current_user(request: Request) -> AuthenticatedUser: | |
| """ | |
| FastAPI dependency to get the current authenticated user. | |
| Usage: | |
| @app.get("/profile") | |
| async def get_profile(user: AuthenticatedUser = Depends(get_current_user)): | |
| return {"user_id": user.user_id} | |
| """ | |
| # Delegate to the shared dependency implementation so lockouts and | |
| # auth-failure tracking behave consistently across all routers. | |
| from .dependencies import get_current_user as _get_current_user | |
| return await _get_current_user(request) | |
| async def get_optional_user(request: Request) -> AuthenticatedUser | None: | |
| """ | |
| FastAPI dependency for optional authentication. | |
| Returns None if not authenticated instead of raising an error. | |
| Usage: | |
| @app.get("/public") | |
| async def public_endpoint(user: Optional[AuthenticatedUser] = Depends(get_optional_user)): | |
| if user: | |
| return {"message": f"Hello, {user.user_id}"} | |
| return {"message": "Hello, anonymous"} | |
| """ | |
| from .dependencies import get_optional_user as _get_optional_user | |
| return await _get_optional_user(request) | |
| # Commonly used role dependencies | |
| require_admin = require_roles("admin") | |
| require_trainer = require_roles("admin", "trainer") | |
| require_user = require_roles("admin", "trainer", "user") | |
| # ============================================================================ | |
| # Request Context | |
| # ============================================================================ | |
| class RequestContext(BaseModel): | |
| """Full request context including auth and tracing.""" | |
| request_id: str | |
| user: AuthenticatedUser | |
| client_ip: str | |
| timestamp: datetime = Field(default_factory=datetime.utcnow) | |
| async def get_request_context(request: Request) -> RequestContext: | |
| """ | |
| Get full request context including authentication. | |
| Usage: | |
| @app.post("/api/train") | |
| async def train(ctx: RequestContext = Depends(get_request_context)): | |
| logger.info(f"Training started by {ctx.user.user_id}") | |
| """ | |
| user = await get_current_user(request) | |
| request_id = getattr(request.state, "request_id", "unknown") | |
| client_ip = request.client.host if request.client else "unknown" | |
| return RequestContext( | |
| request_id=request_id, | |
| user=user, | |
| client_ip=client_ip, | |
| ) | |
Xet Storage Details
- Size:
- 12 kB
- Xet hash:
- e8e78da444d99bb632361e9154a296610c536372ef7adc43df78084d3475b3f1
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.