feat(auth): ADMIN_COOKIE_SECURE forces the session cookie Secure
Behind the cluster's HTTP origin listener Envoy normalizes X-Forwarded-Proto to http, so _is_https() never fires and the session cookie was issued without Secure. Add an explicit deploy-time flag: set_session_cookie() now marks the cookie Secure when the env var is 1/true/yes (case-insensitive, stripped) or the header inference says https. clear_session_cookie() is unchanged, SameSite stays Lax. Tests cover flag-over-http, header-without-flag, and the local-dev path; docs/auth.md and .env.example document the variable.
This commit is contained in:
parent
d8113b37b8
commit
72757e7c51
4 changed files with 67 additions and 4 deletions
18
app/auth.py
18
app/auth.py
|
|
@ -16,7 +16,9 @@ Design notes
|
|||
* **No new dependencies.** Password hashing is stdlib ``hashlib.pbkdf2_hmac``
|
||||
and the session token is an HMAC-SHA256 signature over a base64url JSON
|
||||
payload. Cookies are HttpOnly, SameSite=Lax, Path=/, 7-day lifetime, and
|
||||
``Secure`` when the request arrived over https (``X-Forwarded-Proto``).
|
||||
``Secure`` when the request arrived over https (``X-Forwarded-Proto``) or
|
||||
when ``ADMIN_COOKIE_SECURE`` is truthy (TLS-only deployments behind an
|
||||
HTTP origin listener, where Envoy normalizes the header to ``http``).
|
||||
* **CSRF.** State-changing admin requests that carry an ``Origin``/``Referer``
|
||||
are rejected when the origin host differs from the request host. Requests
|
||||
without either header (curl, server-to-server) are allowed — the signed,
|
||||
|
|
@ -281,6 +283,18 @@ def _is_https(request: Request) -> bool:
|
|||
return request.url.scheme == "https"
|
||||
|
||||
|
||||
_TRUTHY = {"1", "true", "yes"}
|
||||
|
||||
|
||||
def cookie_secure_forced() -> bool:
|
||||
"""``ADMIN_COOKIE_SECURE`` marks the deployment TLS-only.
|
||||
|
||||
Read on every call so tests and restarts pick up env changes; the header
|
||||
inference in :func:`_is_https` stays as the fallback.
|
||||
"""
|
||||
return (os.getenv("ADMIN_COOKIE_SECURE") or "").strip().lower() in _TRUTHY
|
||||
|
||||
|
||||
def set_session_cookie(response, request: Request, token: str) -> None:
|
||||
response.set_cookie(
|
||||
COOKIE_NAME,
|
||||
|
|
@ -288,7 +302,7 @@ def set_session_cookie(response, request: Request, token: str) -> None:
|
|||
max_age=SESSION_TTL_SECONDS,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=_is_https(request),
|
||||
secure=cookie_secure_forced() or _is_https(request),
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue