Spaces:
Running on Zero
Running on Zero
Download app/core/middleware.py from avijit28/tunechecker-api: direct link, hf CLI and curl.
- Browser
- Download file 2.28 kB
-
https://huggingface.co/spaces/avijit28/tunechecker-api/resolve/main/app/core/middleware.py
- Command line
-
hf download hf://spaces/avijit28/tunechecker-api/app/core/middleware.py
-
curl -L -o middleware.py https://huggingface.co/spaces/avijit28/tunechecker-api/resolve/main/app/core/middleware.py
2.28 kB
| """Enterprise Security Headers Middleware. | |
| Guarantees full OWASP / Enterprise compliance by applying: | |
| - Strict-Transport-Security (HSTS) | |
| - Content-Security-Policy (CSP) | |
| - X-Content-Type-Options: nosniff | |
| - X-Frame-Options: DENY | |
| - X-XSS-Protection: 1; mode=block | |
| - Referrer-Policy: strict-origin-when-cross-origin | |
| - Permissions-Policy | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from typing import Callable | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.requests import Request | |
| from starlette.responses import Response | |
| logger = logging.getLogger("tunechecker.security_headers") | |
| # Enterprise Content Security Policy | |
| CSP_POLICY = ( | |
| "default-src 'self'; " | |
| "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; " | |
| "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " | |
| "font-src 'self' data: https://fonts.gstatic.com; " | |
| "img-src 'self' data: blob: https:; " | |
| "connect-src 'self' http: https: ws: wss:; " | |
| "media-src 'self' data: blob:; " | |
| "frame-ancestors 'none'; " | |
| "base-uri 'self'; " | |
| "form-action 'self';" | |
| ) | |
| class SecurityHeadersMiddleware(BaseHTTPMiddleware): | |
| """Enforce Enterprise-Grade HTTP Security Headers on every outgoing response.""" | |
| async def dispatch(self, request: Request, call_next: Callable) -> Response: | |
| response: Response = await call_next(request) | |
| # 1. HTTP Strict Transport Security (HSTS) - 1 year, includes subdomains | |
| response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains; preload" | |
| # 2. Content Security Policy (CSP) | |
| response.headers["Content-Security-Policy"] = CSP_POLICY | |
| # 3. MIME type sniffing prevention | |
| response.headers["X-Content-Type-Options"] = "nosniff" | |
| # 4. Anti-clickjacking protection | |
| response.headers["X-Frame-Options"] = "DENY" | |
| # 5. Cross-Site Scripting filter | |
| response.headers["X-XSS-Protection"] = "1; mode=block" | |
| # 6. Referrer Policy | |
| response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" | |
| # 7. Restrict dangerous browser features | |
| response.headers["Permissions-Policy"] = "camera=(), microphone=(self), geolocation=(), payment=()" | |
| return response | |