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
|
|
@ -79,6 +79,11 @@ VESSELAPI_IN_INGEST=0
|
|||
ADMIN_USER=
|
||||
ADMIN_PASSWORD_HASH=
|
||||
ADMIN_SESSION_SECRET=
|
||||
# Optional: force the session cookie's Secure flag (1/true/yes) when the app is
|
||||
# reached over plain HTTP behind a TLS-terminating proxy that rewrites
|
||||
# X-Forwarded-Proto to http (the cluster: Cloudflare tunnel -> Cilium Gateway).
|
||||
# Leave unset locally so the cookie works over http://localhost.
|
||||
ADMIN_COOKIE_SECURE=
|
||||
|
||||
# ── News pipeline (scraper + summarizer, profile `ingest`) ────────────────
|
||||
# Scraper crawls urls.txt continuously (default 10s between crawls).
|
||||
|
|
|
|||
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="/",
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -60,6 +60,13 @@ arrived over https (`X-Forwarded-Proto`, i.e. behind Cloudflare). Signature and
|
|||
expiry are checked with `hmac.compare_digest`; a token for another username, or
|
||||
one signed with a different secret, is rejected.
|
||||
|
||||
Set `ADMIN_COOKIE_SECURE=1` (`true`/`yes` also work) whenever the deployment is
|
||||
TLS-only but the app itself is reached over plain HTTP. In the cluster the
|
||||
Cloudflare tunnel originates at the Cilium Gateway on plain HTTP and Envoy
|
||||
normalizes `X-Forwarded-Proto` to `http`, so the header inference never fires
|
||||
there — the flag is what makes the cookie `Secure` in the cluster. Leave it
|
||||
unset for local development, where the cookie has to work over `http://localhost`.
|
||||
|
||||
## Abuse controls
|
||||
|
||||
* **Login rate limit:** 5 failed attempts per client IP (first hop of
|
||||
|
|
|
|||
|
|
@ -318,7 +318,8 @@ def test_login_missing_fields_is_401_not_500():
|
|||
assert resp.status_code == 401
|
||||
|
||||
|
||||
def test_login_success_sets_httponly_cookie():
|
||||
def test_login_success_sets_httponly_cookie(monkeypatch):
|
||||
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
|
||||
resp = _login()
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == {"authenticated": True, "admin": True}
|
||||
|
|
@ -337,12 +338,48 @@ def test_login_accepts_json_body():
|
|||
assert resp.json()["authenticated"] is True
|
||||
|
||||
|
||||
def test_login_cookie_marks_secure_behind_https_proxy():
|
||||
def test_login_cookie_marks_secure_behind_https_proxy(monkeypatch):
|
||||
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
|
||||
resp = _login(headers={"X-Forwarded-Proto": "https"})
|
||||
assert resp.status_code == 200
|
||||
assert "Secure" in resp.headers.get("set-cookie", "")
|
||||
|
||||
|
||||
def test_login_cookie_secure_via_env_flag_over_http_origin(monkeypatch):
|
||||
"""ADMIN_COOKIE_SECURE is what makes the cookie Secure in the cluster:
|
||||
the header arrives as ``http`` from the Cilium Gateway."""
|
||||
monkeypatch.setenv("ADMIN_COOKIE_SECURE", "1")
|
||||
resp = _login(headers={"X-Forwarded-Proto": "http"})
|
||||
assert resp.status_code == 200
|
||||
raw = resp.headers.get("set-cookie", "")
|
||||
assert "Secure" in raw
|
||||
assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax")
|
||||
assert "HttpOnly" in raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["true", "TRUE", " Yes ", "yes"])
|
||||
def test_login_cookie_env_flag_accepts_truthy_spellings(monkeypatch, value):
|
||||
monkeypatch.setenv("ADMIN_COOKIE_SECURE", value)
|
||||
resp = _login()
|
||||
assert resp.status_code == 200
|
||||
assert "Secure" in resp.headers.get("set-cookie", "")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["", "0", "false", "no", "off"])
|
||||
def test_login_cookie_env_flag_ignores_falsey_spellings(monkeypatch, value):
|
||||
monkeypatch.setenv("ADMIN_COOKIE_SECURE", value)
|
||||
resp = _login(headers={"X-Forwarded-Proto": "http"})
|
||||
assert resp.status_code == 200
|
||||
assert "Secure" not in resp.headers.get("set-cookie", "")
|
||||
|
||||
|
||||
def test_login_cookie_without_header_or_flag_is_not_secure_locally(monkeypatch):
|
||||
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
|
||||
resp = _login()
|
||||
assert resp.status_code == 200
|
||||
assert "Secure" not in resp.headers.get("set-cookie", "")
|
||||
|
||||
|
||||
def test_session_cookie_unlocks_admin_routes(no_db):
|
||||
login = _login()
|
||||
cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)}
|
||||
|
|
|
|||
Loading…
Reference in a new issue