Review

Hardening: HSTS, secure cookies, HTTPS redirect

Security review of the CareLink patient portal flagged plain HTTP access and session cookies without Secure. Adds middleware to redirect HTTP→HTTPS, emit HSTS (with preload), and set session cookies with Secure/HttpOnly/SameSite.

FastAPITier 1securitymiddleware

Click a line to flag it, pick one or more labels, then submit. If the change looks correct, approve it.

app/middleware/transport.py+18-2
11from starlette.middleware.base import BaseHTTPMiddleware
22from starlette.requests import Request
33from starlette.responses import RedirectResponse, Response
44
5+HSTS = "max-age=63072000; includeSubDomains; preload"
56
6-class RequestIdMiddleware(BaseHTTPMiddleware):
7+class TransportSecurityMiddleware(BaseHTTPMiddleware):
8+ async def dispatch(self, request: Request, call_next) -> Response:
9+ proto = request.headers.get("x-forwarded-proto", request.url.scheme)
10+ if proto == "http":
11+ https_url = request.url.replace(scheme="https")
12+ return RedirectResponse(str(https_url), status_code=308)
13+ response = await call_next(request)
14+ response.headers["Strict-Transport-Security"] = HSTS
15+ return response
716
817
918def attach_session(response: Response, token: str) -> None:
10- response.set_cookie("session", token, httponly=True, max_age=86400)
19+ response.set_cookie(
20+ "session",
21+ token,
22+ httponly=True,
23+ secure=True,
24+ samesite="lax",
25+ max_age=86400,
26+ )