Spaces:
Paused

File size: 11,450 Bytes
ff28ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d80907b
2a99443
ff28ba2
 
 
2a99443
ff28ba2
 
 
 
 
2a99443
 
 
 
 
 
 
2e7af6d
2a99443
 
 
 
 
 
 
 
 
 
 
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
 
 
 
 
 
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
 
 
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
 
 
 
 
 
 
 
2e7af6d
 
ff28ba2
 
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
d80907b
 
 
 
 
ff28ba2
 
2e7af6d
d80907b
 
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
 
d80907b
2e7af6d
ff28ba2
 
 
 
 
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
2e7af6d
d80907b
ff28ba2
d80907b
 
 
 
 
ff28ba2
 
 
 
 
d80907b
ff28ba2
 
 
 
d80907b
ff28ba2
 
2e7af6d
ff28ba2
2e7af6d
ff28ba2
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
2e7af6d
ff28ba2
 
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
ff28ba2
2e7af6d
ff28ba2
 
 
 
 
 
2e7af6d
ff28ba2
 
 
 
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
 
 
 
 
 
 
 
2e7af6d
ff28ba2
 
 
 
 
 
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
 
 
 
 
 
 
 
 
 
2e7af6d
 
ff28ba2
 
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
 
 
 
 
2e7af6d
ff28ba2
 
 
 
 
 
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
2e7af6d
ff28ba2
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
 
2e7af6d
ff28ba2
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
2e7af6d
ff28ba2
 
 
 
 
2e7af6d
ff28ba2
 
 
 
 
2e7af6d
ff28ba2
 
 
 
 
 
 
 
2e7af6d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""
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()


@dataclass
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"]