Buckets:

download
raw
23.7 kB
"""
Mothership Cockpit FastAPI Dependencies.
Dependency injection functions for FastAPI endpoints providing
access to services, configuration, and authentication.
"""
from __future__ import annotations
import logging
import os
from typing import Annotated, Any
from fastapi import Depends, Header, HTTPException, Query, Request, status
try:
from apiguard import BucketRegistry
_HAS_APIGUARD = True
except ModuleNotFoundError: # pragma: no cover
_HAS_APIGUARD = False
BucketRegistry = None # type: ignore[assignment,misc]
from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer
from .config import MothershipSettings, get_settings
from .exceptions import ResourceNotFoundError
from .models import Session
from .repositories import StateStore, get_state_store, get_unit_of_work
from .repositories.db import DbUnitOfWork
from .services import CockpitService
logger = logging.getLogger(__name__)
# =============================================================================
# Security Schemes
# =============================================================================
api_key_header = APIKeyHeader(
name="X-API-Key",
auto_error=False,
description="API key for authentication",
)
bearer_scheme = HTTPBearer(
auto_error=False,
description="JWT Bearer token",
)
# =============================================================================
# Configuration Dependencies
# =============================================================================
def get_config() -> MothershipSettings:
"""
Get application configuration.
Returns:
MothershipSettings instance
"""
return get_settings()
Settings = Annotated[MothershipSettings, Depends(get_config)]
# =============================================================================
# State & Repository Dependencies
# =============================================================================
# Cached persistence mode to avoid os.getenv on every request
_persistence_mode: str | None = None
def _get_persistence_mode() -> str:
"""Return MOTHERSHIP_PERSISTENCE_MODE (cached for performance)."""
global _persistence_mode
if _persistence_mode is None:
_persistence_mode = os.getenv("MOTHERSHIP_PERSISTENCE_MODE", "memory").lower().strip()
return _persistence_mode
def reset_persistence_mode_cache() -> None:
"""Clear cached persistence mode (for tests that change env)."""
global _persistence_mode
_persistence_mode = None
async def get_store() -> StateStore:
"""
Get the state store instance.
Returns:
StateStore singleton instance
"""
return get_state_store()
Store = Annotated[StateStore, Depends(get_store)]
async def get_uow() -> Any:
"""
Get a Unit of Work instance for repository access.
Returns:
UnitOfWork instance
"""
if _get_persistence_mode() == "db":
return DbUnitOfWork()
return get_unit_of_work()
UoW = Annotated[Any, Depends(get_uow)]
# =============================================================================
# Service Dependencies
# =============================================================================
# Global service instance (singleton pattern)
_cockpit_service: CockpitService | None = None
def get_cockpit_service() -> CockpitService:
"""
Get the cockpit service instance.
Uses singleton pattern to ensure consistent state across requests.
Returns:
CockpitService instance
"""
global _cockpit_service
if _cockpit_service is None:
settings = get_settings()
_cockpit_service = CockpitService(
session_ttl_minutes=settings.cockpit.session_timeout_minutes,
max_sessions=settings.cockpit.max_concurrent_sessions,
max_concurrent_operations=settings.cockpit.task_queue_size,
)
_cockpit_service.start()
return _cockpit_service
def reset_cockpit_service() -> None:
"""Reset the cockpit service (for testing)."""
global _cockpit_service
if _cockpit_service:
_cockpit_service.shutdown()
_cockpit_service = None
Cockpit = Annotated[CockpitService, Depends(get_cockpit_service)]
# =============================================================================
# Authentication Dependencies
# =============================================================================
async def get_api_key(
api_key: str | None = Depends(api_key_header),
settings: MothershipSettings = Depends(get_config),
) -> str | None:
"""
Extract and validate API key from request headers.
Args:
api_key: API key from header
settings: Application settings
Returns:
Validated API key or None
"""
if api_key is None:
return None
# In production, validate against stored keys
# For now, accept any non-empty key in development
if settings.is_development:
return api_key
# Production validation would go here
# Example: Check against database or secrets manager
return api_key
async def get_bearer_token(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
) -> str | None:
"""
Extract JWT token from Authorization header.
Args:
credentials: Bearer credentials
Returns:
JWT token string or None
"""
if credentials is None:
return None
return credentials.credentials
from .security.auth import verify_api_key, verify_jwt_token
from .security.merit_standing import (
ActionClass,
get_merit_engine,
)
from .security.rbac import has_permission
# CRIT-1: Literal dev-test-token must never grant access in production; gate behind ENABLE_DEV_TOKEN.
DEV_TEST_TOKEN_LITERAL = "dev-test-token"
async def verify_authentication(
api_key: str | None = Depends(get_api_key),
bearer_token: str | None = Depends(get_bearer_token),
settings: MothershipSettings = Depends(get_config),
) -> dict[str, Any]:
"""
Verify request authentication using centralized security logic.
Supports both API key and JWT authentication with RBAC integration.
"""
# CRIT-1: Literal dev-test-token only when ENABLE_DEV_TOKEN=1 and not production
if bearer_token and bearer_token.strip() == DEV_TEST_TOKEN_LITERAL:
allow_dev_token = os.getenv("ENABLE_DEV_TOKEN", "").strip().lower() in ("1", "true", "yes")
is_production = getattr(settings, "environment", None) == "production"
if not allow_dev_token or is_production:
logger.warning("Rejected bearer token 'dev-test-token' (ENABLE_DEV_TOKEN not set or production)")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
) from None
# Explicitly allowed: return test auth context (do not try JWT decode). method=dev_bypass so require_authentication allows.
from application.mothership.security.rbac import Role, get_permissions_for_role
return {
"authenticated": False,
"method": "dev_bypass",
"permissions": get_permissions_for_role(Role.ADMIN),
"token_payload": {},
"user_id": "test_user",
"email": "test@local.dev",
}
# 1. Try JWT authentication (Highest Priority)
if bearer_token:
try:
return await verify_jwt_token(bearer_token, require_valid=True)
except Exception as e:
logger.warning(f"JWT verification failed: {e}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=str(e) if settings.is_development else "Invalid or expired authentication token",
headers={"WWW-Authenticate": "Bearer"},
) from e
# 2. API Key authentication
if api_key:
try:
return verify_api_key(api_key, require_valid=True)
except Exception as e:
logger.warning(f"API Key verification failed: {e}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=str(e) if settings.is_development else "Invalid API Key",
) from e
# 3. Deny-by-default — no credentials means no access
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
)
Auth = Annotated[dict[str, Any], Depends(verify_authentication)]
async def get_optional_authentication(
api_key: str | None = Depends(get_api_key),
bearer_token: str | None = Depends(get_bearer_token),
settings: MothershipSettings = Depends(get_config),
) -> dict[str, Any]:
"""
Resolve authentication context for endpoints that may be accessed anonymously.
Public endpoints still benefit from auth context when valid credentials are
present, but missing credentials must not trigger a 401 before the route body
executes.
"""
anonymous_context = {
"authenticated": False,
"method": "anonymous",
"permissions": set(),
"token_payload": {},
"user_id": None,
"email": None,
}
if bearer_token:
try:
return await verify_jwt_token(bearer_token, require_valid=True)
except Exception as e:
logger.warning(f"Optional JWT verification failed: {e}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=str(e) if settings.is_development else "Invalid or expired authentication token",
headers={"WWW-Authenticate": "Bearer"},
) from e
if api_key:
try:
return verify_api_key(api_key, require_valid=True)
except Exception as e:
logger.warning(f"Optional API key verification failed: {e}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=str(e) if settings.is_development else "Invalid API Key",
) from e
# CRIT-7: Anonymous must never have admin or elevated permissions.
return {
"authenticated": False,
"method": "anonymous",
"permissions": set(),
"token_payload": {},
"user_id": None,
"email": None,
}
async def require_authentication(
auth: Auth,
) -> dict[str, Any]:
"""
Require authentication for an endpoint.
"""
if not auth.get("authenticated", False) and auth.get("method") != "dev_bypass":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
)
return auth
RequiredAuth = Annotated[dict[str, Any], Depends(require_authentication)]
async def require_permission(
permission: str,
auth: Auth,
request: Request | None = None,
) -> dict[str, Any]:
"""
Require a specific permission using RBAC + Merit Standing system.
Enforces access by role + scope + merit badge (threshold badges), not role alone.
"""
# First check RBAC permission
permissions = auth.get("permissions", set())
if not has_permission(permissions, permission):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Operation requires '{permission}' permission",
)
# Then check merit standing
entity_id = auth.get("user_id") or auth.get("email", "anonymous")
engine = get_merit_engine()
# Map permission to action class
action_class = _map_permission_to_action_class(permission)
allowed, details = engine.check_permission(entity_id, action_class)
if not allowed:
logger.warning(
"merit_permission_denied entity=%s permission=%s required_badge=%s actual_badge=%s",
entity_id,
permission,
details.get("required_badge"),
details.get("actual_badge"),
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Insufficient merit standing for '{permission}'. "
f"Required: {details.get('required_badge')}, "
f"Current: {details.get('actual_badge')}",
)
return auth
def _map_permission_to_action_class(permission: str) -> ActionClass:
"""Map RBAC permission to Merit action class."""
permission_lower = permission.lower()
if "admin" in permission_lower or "control" in permission_lower:
return ActionClass.CONTROL_ADMIN
if "write" in permission_lower or "create" in permission_lower or "delete" in permission_lower:
return ActionClass.ACTION_WRITE
if "read" in permission_lower or "view" in permission_lower or "analysis" in permission_lower:
return ActionClass.ANALYSIS_READ
return ActionClass.PUBLIC_BASIC
async def require_admin(auth: dict[str, Any] = Depends(require_authentication)) -> dict[str, Any]:
"""Require admin permission."""
return await require_permission("admin", auth)
async def require_write(auth: dict[str, Any] = Depends(require_authentication)) -> dict[str, Any]:
"""Require write permission."""
return await require_permission("write", auth)
AdminAuth = Annotated[dict[str, Any], Depends(require_admin)]
WriteAuth = Annotated[dict[str, Any], Depends(require_write)]
# =============================================================================
# Session Dependencies
# =============================================================================
async def get_session_id(
x_session_id: str | None = Header(None, alias="X-Session-ID"),
session_id: str | None = Query(None, alias="session_id"),
) -> str | None:
"""
Extract session ID from headers or query params.
Args:
x_session_id: Session ID from header
session_id: Session ID from query param
Returns:
Session ID or None
"""
return x_session_id or session_id
SessionId = Annotated[str | None, Depends(get_session_id)]
async def get_current_session(
session_id: SessionId,
cockpit: Cockpit,
) -> Session | None:
"""
Get the current session if session ID is provided.
Args:
session_id: Session ID
cockpit: Cockpit service
Returns:
Session object or None
"""
if not session_id:
return None
try:
return cockpit.sessions.get_session(session_id)
except ResourceNotFoundError:
return None
CurrentSession = Annotated[Session | None, Depends(get_current_session)]
async def require_session(
session: CurrentSession,
) -> Session:
"""
Require a valid session.
Args:
session: Current session
Returns:
Validated session
Raises:
HTTPException: If no valid session
"""
if session is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Valid session required",
headers={"X-Session-ID": "required"},
)
if not session.is_active():
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Session has expired",
)
return session
RequiredSession = Annotated[Session, Depends(require_session)]
# =============================================================================
# Request Context Dependencies
# =============================================================================
async def get_request_context(
request: Request,
auth: Annotated[dict[str, Any], Depends(get_optional_authentication)],
session: CurrentSession,
settings: Settings,
) -> dict[str, Any]:
"""
Build request context with all relevant information.
Args:
request: FastAPI request object
auth: Authentication context
session: Current session if any
settings: Application settings
Returns:
Request context dictionary
"""
return {
"request_id": request.headers.get("X-Request-ID"),
"correlation_id": request.headers.get("X-Correlation-ID"),
"client_ip": request.client.host if request.client else None,
"user_agent": request.headers.get("User-Agent"),
"auth": auth,
"session_id": session.id if session else None,
"user_id": auth.get("user_id"),
"environment": settings.environment.value,
}
RequestContext = Annotated[dict[str, Any], Depends(get_request_context)]
# =============================================================================
# Pagination Dependencies
# =============================================================================
async def get_pagination(
page: int = Query(1, ge=1, le=10000, description="Page number"),
page_size: int = Query(20, ge=1, le=100, description="Items per page"),
sort_by: str | None = Query(None, description="Field to sort by"),
sort_order: str = Query("desc", pattern="^(asc|desc)$", description="Sort order"),
) -> dict[str, Any]:
"""
Extract pagination parameters from query string.
Args:
page: Page number (1-indexed)
page_size: Number of items per page
sort_by: Field to sort by
sort_order: Sort direction (asc/desc)
Returns:
Pagination parameters dictionary
"""
return {
"page": page,
"page_size": page_size,
"offset": (page - 1) * page_size,
"limit": page_size,
"sort_by": sort_by,
"sort_order": sort_order,
}
Pagination = Annotated[dict[str, Any], Depends(get_pagination)]
# =============================================================================
# Health Check Dependencies
# =============================================================================
async def check_system_ready(
cockpit: Cockpit,
settings: Settings,
) -> bool:
"""
Check if system is ready to handle requests.
Args:
cockpit: Cockpit service
settings: Application settings
Returns:
True if system is ready
Raises:
HTTPException: If system not ready
"""
if not cockpit.is_healthy:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="System not ready",
)
return True
SystemReady = Annotated[bool, Depends(check_system_ready)]
# =============================================================================
# Rate Limiting Dependencies
# =============================================================================
# APIGuard-backed dependency rate limit registries
_authenticated_rate_limit_registry: Any = None
_public_rate_limit_registry: Any = None
# Lightweight fallback for when apiguard is not installed
_fallback_counters: dict[str, int] = {}
# Alias exposed for test isolation (clear between tests)
_rate_limit_store = _fallback_counters
def reset_rate_limit_state() -> None:
"""Reset all rate-limit state. Use in test fixtures for isolation."""
global _authenticated_rate_limit_registry, _public_rate_limit_registry
_fallback_counters.clear()
_authenticated_rate_limit_registry = None
_public_rate_limit_registry = None
def _get_rate_limit_registry(settings: MothershipSettings, *, public: bool) -> Any:
global _authenticated_rate_limit_registry, _public_rate_limit_registry
if not _HAS_APIGUARD:
return None # signal to use fallback path
target = _public_rate_limit_registry if public else _authenticated_rate_limit_registry
refill_rate = max(
settings.security.rate_limit_requests / max(settings.security.rate_limit_window_seconds, 1),
1.0 / max(settings.security.rate_limit_window_seconds, 1),
)
if target is None:
target = BucketRegistry(
default_capacity=settings.security.rate_limit_requests,
default_refill_rate=refill_rate,
)
if public:
_public_rate_limit_registry = target
else:
_authenticated_rate_limit_registry = target
return target
def _consume_rate_limit(key: str, settings: MothershipSettings, *, public: bool = False) -> bool:
"""Track a rate-limited request for the given key."""
if not settings.security.rate_limit_enabled:
return True
registry = _get_rate_limit_registry(settings, public=public)
if registry is None:
# Fallback: simple counter-based limiter (no apiguard)
count = _fallback_counters.get(key, 0) + 1
_fallback_counters[key] = count
if count > settings.security.rate_limit_requests:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Rate limit exceeded",
headers={"Retry-After": str(settings.security.rate_limit_window_seconds)},
)
return True
bucket = registry.get_bucket(key)
if not bucket.acquire():
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Rate limit exceeded",
headers={"Retry-After": str(settings.security.rate_limit_window_seconds)},
)
return True
async def check_rate_limit(
request: Request,
auth: Auth,
settings: Settings,
) -> bool:
"""
Check rate limiting for the request.
Args:
request: FastAPI request
auth: Authentication context
settings: Application settings
Returns:
True if within rate limits
Raises:
HTTPException: If rate limit exceeded
"""
# Use user_id or IP for rate limiting
key = auth.get("user_id") or (request.client.host if request.client else "unknown")
return _consume_rate_limit(key, settings, public=False)
async def check_public_rate_limit(
request: Request,
settings: Settings,
) -> bool:
"""
Rate limit a public endpoint without requiring prior authentication.
Public auth entrypoints such as login and registration must be reachable
before a caller has a token, so they can only key on client identity.
"""
client_ip = request.client.host if request.client else "unknown"
return _consume_rate_limit(f"public:{client_ip}", settings, public=True)
RateLimited = Annotated[bool, Depends(check_rate_limit)]
PublicRateLimited = Annotated[bool, Depends(check_public_rate_limit)]
# =============================================================================
# Exports
# =============================================================================
__all__ = [
# Configuration
"get_config",
"Settings",
# State & Repository
"get_store",
"Store",
"get_uow",
"UoW",
# Services
"get_cockpit_service",
"reset_cockpit_service",
"Cockpit",
# Authentication
"get_api_key",
"get_bearer_token",
"verify_authentication",
"get_optional_authentication",
"require_authentication",
"require_permission",
"require_admin",
"require_write",
"Auth",
"RequiredAuth",
"AdminAuth",
"WriteAuth",
# Session
"get_session_id",
"get_current_session",
"require_session",
"SessionId",
"CurrentSession",
"RequiredSession",
# Request Context
"get_request_context",
"RequestContext",
# Pagination
"get_pagination",
"Pagination",
# Health
"check_system_ready",
"SystemReady",
# Rate Limiting
"check_rate_limit",
"check_public_rate_limit",
"RateLimited",
"PublicRateLimited",
"_rate_limit_store",
"reset_rate_limit_state",
]

Xet Storage Details

Size:
23.7 kB
·
Xet hash:
95cef08e5f4ade9cf6b790f7c75728dacbf27f6e2c5efa30877071790397cba8

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.