Download src/core/security/headers.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/security/headers.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/core/security/headers.py
-
curl -L -o headers.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/core/security/headers.py
11.5 kB
| """ | |
| YAZ Care Platform - Canonical Security Headers Middleware | |
| OWASP-compliant security headers for all HTTP responses | |
| This is the SINGLE source of truth for security headers. | |
| All 17 healthcare applications use this implementation. | |
| Standards: | |
| - OWASP Secure Headers Project | |
| - NIST Cybersecurity Framework | |
| - HIPAA Security Rule (§164.312) | |
| Previous Locations (CONSOLIDATED): | |
| - src/middleware/security_headers.py ❌ DELETED | |
| - src/middleware/api_gateway.py ❌ DELETED (extracted) | |
| - src/middleware/security.py ❌ DELETED (extracted) | |
| - src/api/security_middleware.py ❌ DELETED | |
| - src/api/middleware/security_advanced.py ❌ DELETED | |
| - src/api/middleware/optimization.py ❌ DELETED (extracted) | |
| - src/api/middleware/security.py ❌ DELETED | |
| - src/core/security/security_headers.py ❌ DELETED | |
| - src/core/common/middleware_stack.py ✅ USES THIS | |
| Migration: Import from here only: | |
| from core.security.headers import SecurityHeadersMiddleware | |
| """ | |
| import secrets | |
| from dataclasses import dataclass, field | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.requests import Request | |
| from starlette.responses import Response | |
| from typing import Callable, Optional, List | |
| import structlog | |
| logger = structlog.get_logger() | |
| class SecurityConfig: | |
| """ | |
| Security configuration for headers middleware. | |
| Standards: OWASP Secure Headers, HIPAA §164.312 | |
| """ | |
| enable_csp: bool = True | |
| enable_hsts: bool = True | |
| hsts_max_age: int = 31536000 # 1 year | |
| frame_options: str = "DENY" | |
| content_type_options: str = "nosniff" | |
| referrer_policy: str = "strict-origin-when-cross-origin" | |
| permissions_policy: str = "camera=(), microphone=(), geolocation=()" | |
| allowed_hosts: List[str] = field(default_factory=lambda: ["*"]) | |
| cors_origins: List[str] = field(default_factory=list) | |
| class SecurityHeadersMiddleware(BaseHTTPMiddleware): | |
| """ | |
| Add OWASP-compliant security headers to all responses | |
| Headers Added: | |
| - X-Frame-Options: Prevent clickjacking | |
| - X-Content-Type-Options: Prevent MIME sniffing | |
| - X-XSS-Protection: XSS filter (legacy browsers) | |
| - Content-Security-Policy: Restrict resource loading | |
| - Strict-Transport-Security: Force HTTPS | |
| - Permissions-Policy: Disable dangerous browser features | |
| - Referrer-Policy: Control referrer information | |
| Clinical Context: Protects PHI from XSS, clickjacking, and data exfiltration | |
| Performance: Adds ~0.5ms overhead per request (headers only) | |
| """ | |
| def __init__( | |
| self, | |
| app, | |
| enable_csp: bool = True, | |
| enable_hsts: bool = True, | |
| hsts_max_age: int = 31536000, # 1 year | |
| ): | |
| """ | |
| Initialize security headers middleware | |
| Args: | |
| app: ASGI application | |
| enable_csp: Enable Content Security Policy (strict) | |
| enable_hsts: Enable HTTP Strict Transport Security | |
| hsts_max_age: HSTS max-age in seconds (default: 1 year) | |
| """ | |
| super().__init__(app) | |
| self.enable_csp = enable_csp | |
| self.enable_hsts = enable_hsts | |
| self.hsts_max_age = hsts_max_age | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| """ | |
| Add security headers to response | |
| Args: | |
| request: Incoming HTTP request | |
| call_next: Next middleware in chain | |
| Returns: | |
| Response with security headers added | |
| """ | |
| # Generate per-request nonce BEFORE template rendering so Jinja2 can access | |
| # request.state.csp_nonce — mirrors the existing request.state.csrf_token pattern. | |
| nonce = secrets.token_hex(16) | |
| request.state.csp_nonce = nonce | |
| # Process request | |
| response = await call_next(request) | |
| # Clickjacking protection (OWASP A05:2021) — DENY blocks all framing | |
| response.headers["X-Frame-Options"] = "DENY" | |
| # MIME sniffing protection (prevents content type confusion attacks) | |
| response.headers["X-Content-Type-Options"] = "nosniff" | |
| # XSS protection for legacy browsers (modern browsers use CSP) | |
| response.headers["X-XSS-Protection"] = "1; mode=block" | |
| # Content Security Policy (OWASP A03:2021) | |
| if self.enable_csp: | |
| response.headers["Content-Security-Policy"] = self._get_csp_policy(nonce) | |
| # Force HTTPS (HIPAA §164.312(e)(1) - transmission security) | |
| if self.enable_hsts: | |
| response.headers["Strict-Transport-Security"] = ( | |
| f"max-age={self.hsts_max_age}; includeSubDomains; preload" | |
| ) | |
| # Permissions Policy (disable dangerous features) | |
| response.headers["Permissions-Policy"] = self._get_permissions_policy() | |
| # Referrer Policy (prevent leaking sensitive URLs) | |
| response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" | |
| # Remove server header (security through obscurity) | |
| response.headers.pop("Server", None) | |
| return response | |
| def _get_csp_policy(self, nonce: str) -> str: | |
| """ | |
| Get Content Security Policy directives. | |
| Each inline <script> tag in Jinja2 templates carries nonce="{{ request.state.csp_nonce }}" | |
| so 'unsafe-inline' is no longer required (OWASP A03:2021). | |
| Returns: | |
| CSP policy string | |
| """ | |
| policy_directives = [ | |
| "default-src 'self'", # Only load resources from same origin | |
| f"script-src 'self' 'nonce-{nonce}'", # Per-request nonce; no unsafe-inline | |
| "style-src 'self' 'unsafe-inline'", # Allow inline styles (needed for UI) | |
| "img-src 'self' data: https:", # Allow images from self, data URIs, HTTPS | |
| "font-src 'self' data:", # Allow fonts from self and data URIs | |
| "connect-src 'self'", # API calls only to same origin | |
| "frame-ancestors 'none'", # Block all framing (defence in depth alongside X-Frame-Options: DENY) | |
| "base-uri 'self'", # Prevent base tag injection | |
| "form-action 'self'", # Forms only submit to same origin | |
| "upgrade-insecure-requests", # Upgrade HTTP to HTTPS | |
| ] | |
| return "; ".join(policy_directives) | |
| def _get_permissions_policy(self) -> str: | |
| """ | |
| Get Permissions Policy directives | |
| Policy: Disable all unnecessary browser features | |
| Returns: | |
| Permissions-Policy string | |
| """ | |
| # Disable all dangerous features (defense in depth) | |
| disabled_features = [ | |
| "geolocation=()", | |
| "microphone=()", | |
| "camera=()", | |
| "magnetometer=()", | |
| "gyroscope=()", | |
| "speaker=()", | |
| "usb=()", | |
| "payment=()", | |
| "interest-cohort=()", # Disable FLoC tracking | |
| ] | |
| return ", ".join(disabled_features) | |
| class RateLimitMiddleware(BaseHTTPMiddleware): | |
| """ | |
| Rate limiting middleware (per-user, per-tenant) | |
| Limits: | |
| - Per-user: 100 requests/minute | |
| - Per-tenant: 10,000 requests/minute | |
| - Per-IP: 1,000 requests/minute (DDoS protection) | |
| Standards: OWASP API Security Top 10 (API4:2023) | |
| Performance: Uses Redis for distributed rate limiting | |
| Previous Locations (CONSOLIDATED): | |
| - src/middleware/rate_limit.py ❌ DELETED | |
| - src/middleware/api_gateway.py ❌ DELETED (extracted) | |
| - src/api/middleware/rate_limiter.py ❌ DELETED | |
| - src/api/middleware/rate_limiting.py ❌ DELETED | |
| - src/core/security/__init__.py ❌ DELETED (extracted) | |
| - src/core/common/middleware_stack.py ✅ USES THIS | |
| """ | |
| def __init__( | |
| self, | |
| app, | |
| redis_client=None, | |
| per_user_limit: int = 100, # requests per minute | |
| per_tenant_limit: int = 10000, | |
| per_ip_limit: int = 1000, | |
| ): | |
| """ | |
| Initialize rate limiter | |
| Args: | |
| app: ASGI application | |
| redis_client: Redis client for distributed rate limiting | |
| per_user_limit: Max requests per user per minute | |
| per_tenant_limit: Max requests per tenant per minute | |
| per_ip_limit: Max requests per IP per minute | |
| """ | |
| super().__init__(app) | |
| self.redis = redis_client | |
| self.per_user_limit = per_user_limit | |
| self.per_tenant_limit = per_tenant_limit | |
| self.per_ip_limit = per_ip_limit | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| """ | |
| Check rate limits before processing request | |
| Args: | |
| request: Incoming HTTP request | |
| call_next: Next middleware in chain | |
| Returns: | |
| Response (429 if rate limit exceeded) | |
| """ | |
| # Extract identifiers | |
| user_id = request.headers.get("X-User-ID", "anonymous") | |
| tenant_id = request.headers.get("X-Tenant-ID", "default") | |
| client_ip = request.client.host if request.client else "unknown" | |
| # Check rate limits (if Redis available) | |
| if self.redis: | |
| # Check per-user limit | |
| user_key = f"ratelimit:user:{tenant_id}:{user_id}" | |
| if await self._is_rate_limited(user_key, self.per_user_limit): | |
| logger.warning( | |
| "rate_limit_exceeded", user_id=user_id, tenant_id=tenant_id, limit_type="user" | |
| ) | |
| return Response( | |
| content="Rate limit exceeded", status_code=429, headers={"Retry-After": "60"} | |
| ) | |
| # Check per-tenant limit | |
| tenant_key = f"ratelimit:tenant:{tenant_id}" | |
| if await self._is_rate_limited(tenant_key, self.per_tenant_limit): | |
| logger.warning("rate_limit_exceeded", tenant_id=tenant_id, limit_type="tenant") | |
| return Response( | |
| content="Tenant rate limit exceeded", | |
| status_code=429, | |
| headers={"Retry-After": "60"}, | |
| ) | |
| # Check per-IP limit (DDoS protection) | |
| ip_key = f"ratelimit:ip:{client_ip}" | |
| if await self._is_rate_limited(ip_key, self.per_ip_limit): | |
| logger.warning("rate_limit_exceeded", client_ip=client_ip, limit_type="ip") | |
| return Response( | |
| content="IP rate limit exceeded", status_code=429, headers={"Retry-After": "60"} | |
| ) | |
| # Process request | |
| response = await call_next(request) | |
| # Add rate limit headers | |
| response.headers["X-RateLimit-Limit"] = str(self.per_user_limit) | |
| return response | |
| async def _is_rate_limited(self, key: str, limit: int) -> bool: | |
| """ | |
| Check if rate limit exceeded using sliding window | |
| Args: | |
| key: Redis key for rate limiting | |
| limit: Maximum requests per minute | |
| Returns: | |
| True if rate limited, False otherwise | |
| """ | |
| if not self.redis: | |
| return False | |
| try: | |
| # Increment counter with 60-second expiry | |
| count = await self.redis.incr(key) | |
| if count == 1: | |
| await self.redis.expire(key, 60) | |
| return count > limit | |
| except Exception as e: | |
| logger.error("rate_limit_check_failed", error=str(e)) | |
| # Fail open (don't block requests on Redis failure) | |
| return False | |
| # Export for backward compatibility | |
| __all__ = ["SecurityHeadersMiddleware", "RateLimitMiddleware"] | |