The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard-auth): url-encode the PKCE cookie value so strict proxy hops stop dropping it (#99176)
Ben Barclaya65a517d0492
diff --git a/hermes_cli/dashboard_auth/cookies.py b/hermes_cli/dashboard_auth/cookies.pyindex ed6f89a8e8b..5c49df24214 100644--- a/hermes_cli/dashboard_auth/cookies.py+++ b/hermes_cli/dashboard_auth/cookies.py@@ -67,6 +67,7 @@ Refresh-token handling:from __future__ import annotationsfrom typing import Literal, Optional, Tuple+from urllib.parse import quote, unquotefrom fastapi import Requestfrom fastapi.responses import Response@@ -306,9 +307,30 @@ def set_pkce_cookie(# sidesteps the bug — these cookies are explicitly designed for cross-site# delivery and Chromium processes them reliably during redirects.# Loopback HTTP degrades to Lax (SameSite=None requires Secure).+ #+ # Value encoding: the PKCE payload is a flat ``key=value;key=value``+ # string (``provider=…;state=…;verifier=…;next=…``). A raw ``;`` is a+ # cookie-attribute terminator, so Python's http.cookies wraps the value+ # in double quotes and escapes each ``;`` as the backslash-octal+ # ``\073``. Mainstream browsers store and echo that quoted form+ # verbatim, and Python parsers decode it — but the quoted form is NOT+ # made of plain RFC 6265 cookie-octets (``"`` and ``\`` are outside the+ # set), and stricter cookie-aware hops that parse and re-emit the+ # Cookie header drop the cookie entirely (verified for Go's net/http,+ # which rejects any cookie value containing a backslash — the parser+ # underlying much Go-based proxy/IDP middleware). The callback then+ # fails with "Missing PKCE state cookie" even though the browser sent+ # it (field case: a Traefik + Authentik + VPN chain, support thread+ # "Still unable to use Authentik for signin with traefik" — devtools+ # showed the browser sending the intact quoted cookie while Hermes+ # logged missing_pkce_cookie). URL-encoding the whole payload+ # (``;`` → ``%3B``)+ # keeps the wire value inside the unquoted cookie-octet set so every+ # RFC 6265 parser passes it through untouched. The readers in+ # routes.py decode via parse_pkce_payload() before the ``;`` split.response.set_cookie(_resolved_name(PKCE_COOKIE, use_https=use_https, prefix=prefix),- payload,+ quote(payload, safe=""),max_age=_PKCE_MAX_AGE,**_pkce_attrs(use_https=use_https, prefix=prefix),)@@ -369,6 +391,39 @@ def read_pkce_cookie(request: Request) -> Optional[str]:return _read_with_fallback(request, PKCE_COOKIE)+def parse_pkce_payload(raw: str) -> dict[str, str]:+ """Decode + parse a PKCE cookie value into its segment dict.++ Single inverse of :func:`set_pkce_cookie`'s encoding: URL-decode the+ wire value back to the flat ``provider=...;state=...;verifier=...``+ shape, then split on ``;``. EVERY reader of the PKCE cookie must go+ through this helper — a reader that splits the raw wire value sees+ the fully URL-encoded string (even ``=`` is ``%3D``), parses zero+ segments, and silently disables whatever check it was feeding+ (provider dispatch, CSRF state, native-flow broker binding).++ Mixed-version compatibility (10-minute PKCE TTL during a rolling+ upgrade): a cookie minted by a pre-encoding server arrives here —+ after starlette's cookie-header unquoting — as the flat form with+ RAW ``;`` between segments, and its ``next`` segment still carries+ its own single URL-encoding (``next=%2F...``). The new encoded form+ can never contain a raw ``;`` (it is ``%3B``). So a raw ``;`` is an+ exact old-format discriminator: split it as-is WITHOUT the payload+ decode, exactly like the old reader did, so an old ``next`` value+ containing ``%3B`` is not decoded into a bogus delimiter. (The+ reverse direction — a new encoded cookie hitting an old server —+ fails the state check and the user retries; nothing to do here.)+ """+ if ";" in raw:+ # Old-format (pre-encoding) cookie: already flat, split as-is.+ return dict(+ seg.split("=", 1) for seg in raw.split(";") if "=" in seg+ )+ return dict(+ seg.split("=", 1) for seg in unquote(raw).split(";") if "=" in seg+ )++def set_sso_attempt_cookie(response: Response, *, use_https: bool, prefix: str = "",) -> None:diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.pyindex d42165f867c..57acfda1be8 100644--- a/hermes_cli/dashboard_auth/routes.py+++ b/hermes_cli/dashboard_auth/routes.py@@ -41,6 +41,7 @@ from hermes_cli.dashboard_auth.cookies import (clear_session_cookies,clear_sso_attempt_cookie,detect_https,+ parse_pkce_payload,read_pkce_cookie,read_session_cookies,set_pkce_cookie,@@ -447,9 +448,10 @@ async def auth_callback(# ``next`` segment is optional (only present when /auth/login was# given a next= query). All keys live in the same flat namespace;# ``next`` carries a URL-encoded path so it never contains ``;``.- parts = dict(- seg.split("=", 1) for seg in pkce_raw.split(";") if "=" in seg- )+ # parse_pkce_payload URL-decodes the wire value (the setter encodes+ # the whole payload so no raw ``;``/``"``/``\`` reaches the wire)+ # before the ``;`` split.+ parts = parse_pkce_payload(pkce_raw)provider_name = parts.get("provider", "")expected_state = parts.get("state", "")verifier = parts.get("verifier", "")@@ -760,9 +762,7 @@ async def auth_password_login(request: Request, body: _PasswordLoginBody):cookie_provider = ""pkce_raw = read_pkce_cookie(request)if pkce_raw:- pkce_parts = dict(- seg.split("=", 1) for seg in pkce_raw.split(";") if "=" in seg- )+ pkce_parts = parse_pkce_payload(pkce_raw)broker_state = pkce_parts.get("broker", "")cookie_provider = pkce_parts.get("provider", "")if broker_state and cookie_provider != body.provider:diff --git a/tests/hermes_cli/test_dashboard_auth_cookies.py b/tests/hermes_cli/test_dashboard_auth_cookies.pyindex 794690a0af7..4a5a0eea462 100644--- a/tests/hermes_cli/test_dashboard_auth_cookies.py+++ b/tests/hermes_cli/test_dashboard_auth_cookies.py@@ -133,6 +133,265 @@ def test_read_session_cookies_from_request_secure_prefix():assert rt == "rt_value"+# ---------------------------------------------------------------------------+# PKCE cookie: regression for #83832 (field case: Traefik+Authentik chain)+# ---------------------------------------------------------------------------+#+# The PKCE payload is a flat ``key=value;key=value`` string. A raw ``;``+# is a cookie-attribute terminator, so Python's http.cookies emits the+# value in RFC 6265 quoted form with each ``;`` escaped as the+# backslash-octal ``\073``. Mainstream browsers echo that form back+# verbatim and Python decodes it — but ``"`` and ``\`` are outside the+# plain cookie-octet set, and cookie-aware proxy hops that parse and+# re-emit the Cookie header (verified for Go's net/http, common in+# Go-based proxy/IDP middleware) reject the value and drop the cookie+# entirely. The callback+# then 400s with "Missing PKCE state cookie" even though the browser+# sent the cookie. The fix URL-encodes the payload in the setter so the+# wire value contains only cookie-octets, and every reader decodes via+# cookies.parse_pkce_payload(). These tests pin the wire shape and the+# round trip.+++def test_set_pkce_cookie_url_encodes_payload_to_avoid_rfc6265_split():+ """The wire-level cookie value must contain only plain RFC 6265+ cookie-octets: no raw ``;`` (attribute terminator), no ``"`` and no+ ``\\`` (the http.cookies quoted form that strict cookie-aware proxy+ parsers — verified for Go's net/http — reject, dropping the whole+ cookie).++ Regression for #83832 / the Traefik+Authentik support case: the+ callback failed with "Missing PKCE state cookie" because a proxy+ hop dropped the quoted ``\\073`` form.+ """+ from urllib.parse import unquote+ client = TestClient(_build_app(use_https=True, prefix=""))+ r = client.get("/set-pkce")+ pkce_set = next(+ c for c in r.headers.get_list("set-cookie")+ if c.startswith(f"__Host-{PKCE_COOKIE}=")+ )+ # Take just the cookie name=value pair, ignore the attributes.+ pkce_value = pkce_set.split(";", 1)[0]+ wire = pkce_value.split("=", 1)[1]+ # No unquoted literal ``;`` in the value (attribute terminator). The+ # payload ``provider=stub;state=s;verifier=v`` is encoded as+ # ``provider%3Dstub%3Bstate%3Ds%3Bverifier%3Dv``.+ assert ";" not in wire, (+ f"unquoted ; leaked into the cookie value: {pkce_value!r}"+ )+ # The real field failure (Traefik/Authentik): the http.cookies quoted+ # form ``"...\073..."`` is not made of cookie-octets, and Go's+ # net/http drops any cookie whose value contains ``"`` or ``\``.+ # Pin the whole value to the plain RFC 6265 cookie-octet set.+ assert '"' not in wire and "\\" not in wire, (+ f"non-cookie-octet chars leaked into the wire value: {wire!r}"+ )+ cookie_octets = (+ "!#$%&'()*+-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"+ "[]^_`abcdefghijklmnopqrstuvwxyz{|}~"+ )+ assert all(ch in cookie_octets for ch in wire), (+ f"non-cookie-octet chars in the wire value: {wire!r}"+ )+ # Round-trip the URL-encoding back to the original payload.+ decoded = unquote(wire)+ assert decoded == "provider=stub;state=s;verifier=v", (+ f"URL-encoded payload didn't round-trip to the original: "+ f"got {decoded!r}"+ )+++def test_parse_pkce_payload_old_format_cookie_survives_rolling_upgrade():+ """Mixed-version window (10-minute PKCE TTL): a cookie minted by a+ pre-encoding server arrives at the new reader — after starlette's+ cookie-header unquoting — as the FLAT form with raw ``;`` between+ segments and a single-encoded ``next``. The reader must split it+ as-is, NOT payload-decode it first: decoding early would turn an+ old ``next`` value containing ``%3B`` into a bogus delimiter and+ truncate the post-login target.+ """+ from hermes_cli.dashboard_auth.cookies import parse_pkce_payload++ old = (+ "provider=stub;state=s123;verifier=v456;"+ "next=%2Fsessions%3Fx%3Da%3Bb%26project%3Dfoo"+ )+ parts = parse_pkce_payload(old)+ assert parts == {+ "provider": "stub",+ "state": "s123",+ "verifier": "v456",+ # Preserved verbatim — still single-encoded, exactly what the+ # old reader produced; the downstream next-validator unquotes.+ "next": "%2Fsessions%3Fx%3Da%3Bb%26project%3Dfoo",+ }, f"old-format cookie mis-parsed: {parts!r}"+++def test_parse_pkce_payload_new_format_round_trips_setter_encoding():+ """The new encoded wire form (no raw ``;`` possible — it is %3B)+ decodes back to the exact original payload segments."""+ from urllib.parse import quote++ from hermes_cli.dashboard_auth.cookies import parse_pkce_payload++ payload = "provider=stub;state=s123;verifier=v456;next=%2Fsessions"+ wire = quote(payload, safe="")+ assert ";" not in wire+ parts = parse_pkce_payload(wire)+ assert parts == {+ "provider": "stub",+ "state": "s123",+ "verifier": "v456",+ "next": "%2Fsessions",+ }, f"new-format wire value mis-parsed: {parts!r}"+++def test_pkce_cookie_round_trip_preserves_all_segments():+ """End-to-end: the browser stores the Set-Cookie, the server+ reads it back via ``read_pkce_cookie``, the OAuth callback+ in routes.py decodes the URL-encoded value and parses every+ segment. Pre-fix, the quoted ``\\073`` wire form was dropped+ whole by strict proxy-hop cookie parsers, so the callback saw+ no PKCE cookie at all.+ """+ import sys+ from pathlib import Path+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ from conftest_dashboard_auth import StubAuthProvider # type: ignore+ from hermes_cli import web_server+ from hermes_cli.dashboard_auth import clear_providers, register_provider+ from urllib.parse import unquote++ clear_providers()+ register_provider(StubAuthProvider())+ prev_host = getattr(web_server.app.state, "bound_host", None)+ prev_port = getattr(web_server.app.state, "bound_port", None)+ prev_required = getattr(web_server.app.state, "auth_required", None)+ web_server.app.state.bound_host = "fly-app.fly.dev"+ web_server.app.state.bound_port = 443+ web_server.app.state.auth_required = True+ try:+ client = TestClient(+ web_server.app, base_url="https://fly-app.fly.dev",+ )+ # /auth/login sets the PKCE cookie with provider / state / verifier+ # packed by the login handler. Capture both the PKCE value and+ # the state that the IDP saw.+ r1 = client.get(+ "/auth/login?provider=stub", follow_redirects=False,+ )+ assert r1.status_code == 302+ pkce_set = next(+ c for c in r1.headers.get_list("set-cookie")+ if "hermes_session_pkce" in c+ )+ # Pull just the name=value portion so we can echo it back as+ # a Cookie header.+ pkce_kv = pkce_set.split(";", 1)[0]+ # Confirm the setter URL-encoded the value.+ encoded_value = pkce_kv.split("=", 1)[1]+ decoded_value = unquote(encoded_value)+ # The login handler packs provider, state, and verifier+ # into the payload. All three must survive intact.+ assert "provider=stub" in decoded_value+ assert "state=" in decoded_value+ assert "verifier=" in decoded_value+ # And the encoded wire value must NOT have a literal, unquoted ``;``+ # between segments.+ assert ";" not in encoded_value, (+ f"literal ; in wire cookie value: {encoded_value!r}"+ )++ # Round-trip via /auth/callback — the success path confirms+ # the callback decoded the URL-encoded value and matched+ # the state. (302 to the post-login page = success.)+ state = r1.headers["location"].split("state=")[1]+ r2 = client.get(+ f"/auth/callback?code=stub_code&state={state}",+ headers={"cookie": pkce_kv},+ follow_redirects=False,+ )+ assert r2.status_code == 302, (+ f"OIDC callback failed — the PKCE cookie round trip is broken. "+ f"Body: {r2.text!r}"+ )+ finally:+ clear_providers()+ web_server.app.state.bound_host = prev_host+ web_server.app.state.bound_port = prev_port+ web_server.app.state.auth_required = prev_required+++def test_pkce_callback_works_when_next_query_includes_encoded_path():+ """The ``next=`` segment carries a URL-encoded path (e.g. a+ relative URL containing ``;`` from a query parameter on the+ post-login target). The setter URL-encodes the whole payload+ (so the ``;`` in the next= value doesn't trip RFC 6265), and+ the reader decodes the next= value back to its original form+ for the redirect."""+ import sys+ from pathlib import Path+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ from conftest_dashboard_auth import StubAuthProvider # type: ignore+ from hermes_cli import web_server+ from hermes_cli.dashboard_auth import clear_providers, register_provider+ from urllib.parse import quote, unquote++ clear_providers()+ register_provider(StubAuthProvider())+ prev_host = getattr(web_server.app.state, "bound_host", None)+ prev_port = getattr(web_server.app.state, "bound_port", None)+ prev_required = getattr(web_server.app.state, "auth_required", None)+ web_server.app.state.bound_host = "fly-app.fly.dev"+ web_server.app.state.bound_port = 443+ web_server.app.state.auth_required = True+ try:+ client = TestClient(+ web_server.app, base_url="https://fly-app.fly.dev",+ )+ # next= with a /sessions?view=recent&project=foo target.+ # The login handler URL-encodes the next= value once, then+ # the setter URL-encodes the whole payload. The reader+ # decodes the payload back, and the routes callback then+ # passes the next= through.+ next_target = "/sessions?view=recent&project=foo"+ r1 = client.get(+ f"/auth/login?provider=stub&next={quote(next_target, safe='')}",+ follow_redirects=False,+ )+ assert r1.status_code == 302+ pkce_kv = next(+ c for c in r1.headers.get_list("set-cookie")+ if "hermes_session_pkce" in c+ ).split(";", 1)[0]+ # Drive the callback — must succeed (302 to the post-login+ # target, NOT a 400 "Missing PKCE state cookie").+ state = r1.headers["location"].split("state=")[1]+ r2 = client.get(+ f"/auth/callback?code=stub_code&state={state}",+ headers={"cookie": pkce_kv},+ follow_redirects=False,+ )+ assert r2.status_code == 302, (+ f"callback failed with next= present: {r2.text!r}"+ )+ # The post-login redirect carries EXACTLY the original target:+ # login-side single-encode + setter whole-payload encode must be+ # symmetrically undone by parse_pkce_payload + the validator's+ # unquote. Pin the exact byte shape — a relaxed substring match+ # would hide an encode/decode imbalance.+ assert r2.headers.get("location") == next_target, (+ f"post-login redirect didn't carry the exact next= target: "+ f"{r2.headers.get('location')!r} != {next_target!r}"+ )+ finally:+ clear_providers()+ web_server.app.state.bound_host = prev_host+ web_server.app.state.bound_port = prev_port+ web_server.app.state.auth_required = prev_required++diff --git a/tests/hermes_cli/test_dashboard_auth_native_flow.py b/tests/hermes_cli/test_dashboard_auth_native_flow.pyindex 182b096a668..d632cab0cd9 100644--- a/tests/hermes_cli/test_dashboard_auth_native_flow.py+++ b/tests/hermes_cli/test_dashboard_auth_native_flow.py@@ -286,7 +286,12 @@ def test_native_authorize_empty_provider_password_only_brokers_to_login(assert r.status_code == 302, r.textassert r.headers["location"].endswith("/login")set_cookie = r.headers.get("set-cookie", "")- assert "broker=" in set_cookie+ # The PKCE cookie value is URL-encoded on the wire; decode through+ # the real reader inverse before asserting the broker handle rides+ # in it.+ from hermes_cli.dashboard_auth.cookies import parse_pkce_payload+ wire_value = set_cookie.split("=", 1)[1].split(";", 1)[0]+ assert "broker" in parse_pkce_payload(wire_value)# ---------------------------------------------------------------------------@@ -408,7 +413,10 @@ def test_native_authorize_password_provider_redirects_to_login(assert r.headers["location"].endswith("/login")set_cookie = r.headers.get("set-cookie", "")assert "pkce" in set_cookie- assert "broker=" in set_cookie+ # Wire value is URL-encoded; decode through the reader inverse.+ from hermes_cli.dashboard_auth.cookies import parse_pkce_payload+ wire_value = set_cookie.split("=", 1)[1].split(";", 1)[0]+ assert "broker" in parse_pkce_payload(wire_value)def _start_native_password_login(client, *, challenge, state="desk-state"):