Download src/core/security/__init__.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/security/__init__.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/security/__init__.py
-
curl -L -o __init__.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/security/__init__.py
15.9 kB
| """ | |
| YAZ Care Platform - Unified Security Middleware | |
| Single source of truth for all security headers, CORS, and CSP | |
| Eliminates duplicate security configurations and ensures HIPAA compliance | |
| """ | |
| import os | |
| import secrets | |
| import base64 | |
| import structlog | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Dict, List, Optional, Callable | |
| from functools import lru_cache | |
| # Import FastAPI components with fallback for testing | |
| try: | |
| from fastapi import FastAPI, Request, Response | |
| from fastapi.middleware.base import BaseHTTPMiddleware | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.middleware.trustedhost import TrustedHostMiddleware | |
| from starlette.types import ASGIApp | |
| FASTAPI_AVAILABLE = True | |
| except ImportError: | |
| # Fallback for testing without FastAPI | |
| FastAPI = None # type: ignore[abstract, assignment, attr-defined, dict-item, misc, type-var, union-attr] | |
| Request = None # type: ignore[abstract, assignment, attr-defined, dict-item, misc, type-var, union-attr] | |
| Response = None # type: ignore[abstract, assignment, attr-defined, dict-item, misc, type-var, union-attr] | |
| BaseHTTPMiddleware = None | |
| CORSMiddleware = None # type: ignore[abstract, assignment, attr-defined, dict-item, misc, type-var, union-attr] | |
| TrustedHostMiddleware = None # type: ignore[abstract, assignment, attr-defined, dict-item, misc, type-var, union-attr] | |
| ASGIApp = None # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| FASTAPI_AVAILABLE = False | |
| from core.config import get_settings | |
| # Import RBAC system | |
| from core.security.rbac import ( | |
| RBACManager, | |
| get_rbac_manager, | |
| Permission, | |
| AccessContext, | |
| AccessDecision, | |
| Module, | |
| Action, | |
| DataSensitivity, | |
| ) | |
| logger = structlog.get_logger(__name__) | |
| settings = get_settings() | |
| # ============================================== | |
| # SECURITY CONFIGURATION | |
| # ============================================== | |
| class SecurityConfig: | |
| """Unified security configuration""" | |
| def __init__(self): | |
| self.environment = settings.environment.value | |
| self.is_production = settings.is_production() | |
| self.is_development = settings.is_development() | |
| self.is_clinical = settings.is_clinical() | |
| # Nonce management | |
| self.nonce_cache: Dict[str, datetime] = {} | |
| self.cleanup_interval = timedelta(hours=1) | |
| self.last_cleanup = datetime.now(timezone.utc) | |
| def generate_nonce(self) -> str: | |
| """Generate cryptographically secure nonce""" | |
| nonce_bytes = secrets.token_bytes(16) | |
| nonce = base64.b64encode(nonce_bytes).decode("utf-8") | |
| # Store with timestamp for cleanup | |
| self.nonce_cache[nonce] = datetime.now(timezone.utc) | |
| # Periodic cleanup | |
| self._cleanup_nonces() | |
| return nonce | |
| def _cleanup_nonces(self): | |
| """Remove expired nonces""" | |
| now = datetime.now(timezone.utc) | |
| if now - self.last_cleanup > self.cleanup_interval: | |
| cutoff = now - timedelta(hours=2) | |
| expired = [n for n, t in self.nonce_cache.items() if t < cutoff] | |
| for nonce in expired: | |
| del self.nonce_cache[nonce] | |
| self.last_cleanup = now | |
| def get_cors_config(self) -> Dict: | |
| """Get CORS configuration""" | |
| return { | |
| "allow_origins": settings.get_cors_origins(), | |
| "allow_credentials": settings.security.cors_credentials, | |
| "allow_methods": settings.security.cors_methods, | |
| "allow_headers": settings.security.cors_headers, | |
| "expose_headers": ["X-Total-Count", "X-Page-Count", "X-Request-ID"], | |
| } | |
| def get_trusted_hosts(self) -> List[str]: | |
| """Get trusted hosts configuration""" | |
| if self.is_development: | |
| return ["localhost", "127.0.0.1", "testserver"] | |
| else: | |
| return ["*.yaz.care", "*.yourhospital.com", "localhost"] | |
| def build_csp_policy(self, nonce: str) -> str: | |
| """Build Content Security Policy""" | |
| policies = [ | |
| "default-src 'self'", | |
| f"script-src 'self' 'nonce-{nonce}'", | |
| # TODO S1: 'unsafe-inline' in style-src accepted until M6 (inline style audit) | |
| # and M7 (DOMPurify htmx:beforeSwap) are complete. 'unsafe-eval' already removed. | |
| "style-src 'self' 'unsafe-inline'", | |
| "font-src 'self' data:", | |
| "img-src 'self' data: https: blob:", | |
| "connect-src 'self'", | |
| "media-src 'self'", | |
| "object-src 'none'", | |
| "form-action 'self'", | |
| "frame-ancestors 'self' https://*.hf.space https://huggingface.co", | |
| "base-uri 'self'", | |
| ] | |
| # Healthcare-specific adjustments | |
| if self.is_clinical: | |
| # Allow medical device connections | |
| policies.append( | |
| "connect-src 'self' https://unpkg.com wss: ws: https://api.yaz.care https://medical-devices.yaz.care" | |
| ) | |
| # Development adjustments | |
| if self.is_development: | |
| # Allow localhost connections | |
| for i, policy in enumerate(policies): | |
| if policy.startswith("connect-src"): | |
| policies[i] += " localhost:* 127.0.0.1:*" | |
| return "; ".join(policies) | |
| def build_permissions_policy(self) -> str: | |
| """Build Permissions Policy for healthcare compliance""" | |
| policies = [ | |
| "camera=()", | |
| "microphone=()", | |
| "geolocation=()", | |
| "accelerometer=()", | |
| "gyroscope=()", | |
| "magnetometer=()", | |
| "usb=()", | |
| "serial=()", | |
| "bluetooth=()", | |
| ] | |
| # Allow camera/microphone in clinical environments for telemedicine | |
| if self.is_clinical: | |
| policies[0] = "camera=(self)" # Allow camera in clinical | |
| policies[1] = "microphone=(self)" # Allow microphone in clinical | |
| return ", ".join(policies) | |
| def get_security_headers(self, nonce: str, request: Request) -> Dict[str, str]: | |
| """Get comprehensive security headers""" | |
| headers = {} | |
| # Content Security Policy | |
| headers["Content-Security-Policy"] = self.build_csp_policy(nonce) | |
| # HTTPS Security (HSTS) | |
| if self.is_production: | |
| headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains; preload" | |
| # Frame protection (SAMEORIGIN for HF Spaces embedding) | |
| headers["X-Frame-Options"] = "SAMEORIGIN" | |
| # Content type protection | |
| headers["X-Content-Type-Options"] = "nosniff" | |
| # XSS Protection (legacy support) | |
| headers["X-XSS-Protection"] = "1; mode=block" | |
| # Referrer Policy | |
| headers["Referrer-Policy"] = "strict-origin-when-cross-origin" | |
| # Permissions Policy | |
| headers["Permissions-Policy"] = self.build_permissions_policy() | |
| # Cross-Origin Policies | |
| # NOTE: Using credentialless instead of require-corp because we load | |
| # external CDN resources (Chart.js, Google Fonts, HTMX from unpkg) | |
| # that do not send Cross-Origin-Resource-Policy headers. | |
| headers["Cross-Origin-Embedder-Policy"] = "credentialless" | |
| headers["Cross-Origin-Opener-Policy"] = "same-origin" | |
| headers["Cross-Origin-Resource-Policy"] = "cross-origin" | |
| # HIPAA Compliance headers | |
| if self.is_clinical: | |
| headers["X-Healthcare-Privacy"] = "HIPAA-Compliant" | |
| headers["X-Content-Security"] = "Healthcare-Grade" | |
| # Cache Control for sensitive data | |
| if self._is_sensitive_endpoint(request.url.path): | |
| headers["Cache-Control"] = "no-store, no-cache, must-revalidate, proxy-revalidate" | |
| headers["Pragma"] = "no-cache" | |
| headers["Expires"] = "0" | |
| else: | |
| headers["Cache-Control"] = "public, max-age=300" | |
| # PWA-specific headers | |
| if request.url.path in ["/", "/manifest.json", "/sw.js"]: | |
| headers["X-PWA-Enabled"] = "true" | |
| # Security timestamps and nonce | |
| headers["X-Security-Timestamp"] = datetime.now(timezone.utc).isoformat() | |
| headers["X-Content-Security-Nonce"] = nonce | |
| headers["X-YAZ-Version"] = settings.app.version | |
| # Remove server identification | |
| return headers | |
| def _is_sensitive_endpoint(self, path: str) -> bool: | |
| """Check if endpoint contains sensitive data""" | |
| sensitive_patterns = [ | |
| "/api/patients", | |
| "/api/users", | |
| "/api/auth", | |
| "/api/clinical", | |
| "/api/insurance", | |
| "/admin", | |
| ] | |
| return any(pattern in path for pattern in sensitive_patterns) | |
| # ============================================== | |
| # MIDDLEWARE CLASSES | |
| # ============================================== | |
| class UnifiedSecurityMiddleware: | |
| """Unified security middleware for all security features""" | |
| def __init__(self, app=None): | |
| if FASTAPI_AVAILABLE and BaseHTTPMiddleware and app: | |
| # Initialize as proper middleware when FastAPI is available | |
| super().__init__(app) # type: ignore[call-arg, call-overload, no-redef] | |
| self.config = SecurityConfig() | |
| logger.info("✓ Unified security middleware initialized") | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| # Generate unique nonce for this request | |
| nonce = self.config.generate_nonce() | |
| request.state.security_nonce = nonce | |
| # Add request ID for tracing | |
| request_id = request.headers.get("X-Request-ID", secrets.token_hex(8)) | |
| request.state.request_id = request_id | |
| # Process request | |
| response = await call_next(request) | |
| # Apply security headers | |
| security_headers = self.config.get_security_headers(nonce, request) | |
| for name, value in security_headers.items(): | |
| response.headers[name] = value | |
| # Add request tracking | |
| response.headers["X-Request-ID"] = request_id | |
| # Remove server identification | |
| if "Server" in response.headers: | |
| del response.headers["Server"] | |
| return response | |
| class RateLimitMiddleware: | |
| """Rate limiting middleware for API protection""" | |
| def __init__(self, app=None, redis_url: Optional[str] = None, default_limit: int = 100): | |
| if FASTAPI_AVAILABLE and BaseHTTPMiddleware and app: | |
| # Initialize as proper middleware when FastAPI is available | |
| super().__init__(app) # type: ignore[call-arg, call-overload, no-redef] | |
| self.default_limit = default_limit | |
| self.redis_url = redis_url | |
| # Simple in-memory rate limiting as fallback | |
| self.request_counts: Dict[str, Dict[str, int]] = {} | |
| self.reset_time = datetime.now(timezone.utc) + timedelta(minutes=1) | |
| logger.info("✓ Rate limiting middleware initialized") | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| if not settings.security.rate_limit_enabled: | |
| return await call_next(request) | |
| client_ip = request.client.host if request.client else "unknown" | |
| current_minute = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M") | |
| # Simple in-memory rate limiting | |
| if current_minute not in self.request_counts: | |
| self.request_counts = {current_minute: {}} | |
| if client_ip not in self.request_counts[current_minute]: | |
| self.request_counts[current_minute][client_ip] = 0 | |
| self.request_counts[current_minute][client_ip] += 1 | |
| if self.request_counts[current_minute][client_ip] > settings.security.rate_limit_per_minute: | |
| return Response( | |
| content="Rate limit exceeded", status_code=429, headers={"Retry-After": "60"} | |
| ) | |
| return await call_next(request) | |
| # ============================================== | |
| # SETUP FUNCTIONS | |
| # ============================================== | |
| def setup_security_middleware(app): | |
| """Setup all security middleware in correct order""" | |
| if not FASTAPI_AVAILABLE or not app: | |
| logger.warning("FastAPI not available, security middleware setup skipped") | |
| return | |
| logger.info("Setting up unified security middleware...") | |
| # 1. Trusted Host Middleware (first layer) | |
| config = SecurityConfig() | |
| trusted_hosts = config.get_trusted_hosts() | |
| app.add_middleware(TrustedHostMiddleware, allowed_hosts=trusted_hosts) | |
| logger.info(f"✓ Trusted hosts: {trusted_hosts}") | |
| # 2. CORS Middleware (before security headers) | |
| cors_config = config.get_cors_config() | |
| app.add_middleware(CORSMiddleware, **cors_config) | |
| logger.info(f"✓ CORS configured for: {cors_config['allow_origins']}") | |
| # 3. Rate Limiting Middleware | |
| if settings.security.rate_limit_enabled: | |
| app.add_middleware( | |
| RateLimitMiddleware, | |
| redis_url=settings.redis.url if settings.redis.enabled else None, | |
| default_limit=settings.security.rate_limit_per_minute, | |
| ) | |
| logger.info(f"✓ Rate limiting: {settings.security.rate_limit_per_minute}/min") | |
| # 4. Unified Security Headers Middleware (last) | |
| app.add_middleware(UnifiedSecurityMiddleware) | |
| logger.info("✓ Security headers middleware enabled") | |
| logger.info("✅ Unified security middleware stack configured") | |
| def get_security_config() -> SecurityConfig: | |
| """Get cached security configuration""" | |
| return SecurityConfig() | |
| def validate_security_requirements(): | |
| """Validate security configuration for production""" | |
| if settings.is_production(): | |
| errors = [] | |
| # Check JWT secrets | |
| if settings.security.jwt_secret_key.startswith("dev-"): | |
| errors.append("Production JWT secret must be set") | |
| if settings.security.secret_key.startswith("dev-"): | |
| errors.append("Production secret key must be set") | |
| # Check HTTPS requirements | |
| cors_origins = settings.get_cors_origins() | |
| if any(origin.startswith("http://") for origin in cors_origins): | |
| errors.append("Production CORS origins must use HTTPS") | |
| if errors: | |
| raise ValueError(f"Security validation failed: {'; '.join(errors)}") | |
| logger.info("✅ Security configuration validated for production") | |
| # ============================================== | |
| # BACKWARD COMPATIBILITY | |
| # ============================================== | |
| # Aliases for backward compatibility | |
| SecurityMiddleware = UnifiedSecurityMiddleware | |
| RateLimiter = RateLimitMiddleware | |
| def create_security_middleware(app: FastAPI): | |
| """Backward compatibility function""" | |
| return setup_security_middleware(app) | |
| def is_production() -> bool: | |
| """Backward compatibility function""" | |
| return settings.is_production() | |
| def is_development() -> bool: | |
| """Backward compatibility function""" | |
| return settings.is_development() | |
| def get_cors_origins() -> List[str]: | |
| """Backward compatibility function""" | |
| return settings.get_cors_origins() | |
| def get_security_headers_config() -> Dict: | |
| """Backward compatibility function""" | |
| config = SecurityConfig() | |
| return { | |
| "csp_policy": config.build_csp_policy("dummy-nonce"), | |
| "permissions_policy": config.build_permissions_policy(), | |
| "cors_origins": settings.get_cors_origins(), | |
| } | |
| # ============================================== | |
| # EXPORTS | |
| # ============================================== | |
| __all__ = [ | |
| "SecurityConfig", | |
| "UnifiedSecurityMiddleware", | |
| "RateLimitMiddleware", | |
| "setup_security_middleware", | |
| "get_security_config", | |
| "validate_security_requirements", | |
| # Backward compatibility | |
| "SecurityMiddleware", | |
| "RateLimiter", | |
| "create_security_middleware", | |
| "is_production", | |
| "is_development", | |
| "get_cors_origins", | |
| "get_security_headers_config", | |
| ] | |