Skip to content

The agent that grows with you

refactor(hermes_cli): compact dashboard_auth docstrings (keep WHY/invariants); drop _lax_bare_attrs dup

Tekniumb90311f0d87d
diff --git a/hermes_cli/dashboard_auth/base.py b/hermes_cli/dashboard_auth/base.py
index 52d63515631..17ed5d2b13c 100644
--- a/hermes_cli/dashboard_auth/base.py
+++ b/hermes_cli/dashboard_auth/base.py
@@ -75,11 +75,10 @@ def classify_jwks_lookup_error(exc: BaseException) -> Exception:
"""Map a ``PyJWKClient.get_signing_key_from_jwt`` failure to the protocol.
Only a genuine transport failure (``PyJWKClientConnectionError``, or an
- unexpected JWKS shape = IDP misbehaving) is a :class:`ProviderError` (503,
- never forces logout). A non-JWT bearer (``DecodeError``), a JWKS with no key
- for this ``kid`` (``PyJWKSetError``) or any other invalid token means the
- token is simply not verifiable by this provider -> :class:`InvalidCodeError`
- (``verify_session`` returns ``None``; next provider / refresh / 401).
+ unexpected JWKS shape) is a :class:`ProviderError` (503, never forces logout).
+ A non-JWT bearer (``DecodeError``), a JWKS with no key for this ``kid``
+ (``PyJWKSetError``) or any other invalid token is simply not verifiable by this
+ provider -> :class:`InvalidCodeError` (``verify_session`` returns ``None``).
Folding "cannot parse" into "cannot reach" once made every opaque bearer a
fast 503 against a healthy Portal.
"""
@@ -103,31 +102,27 @@ def classify_jwks_lookup_error(exc: BaseException) -> Exception:
class DashboardAuthProvider(ABC):
"""Protocol every dashboard-auth provider plugin implements.
- Lifecycle: ``start_login`` (redirect URL + PKCE state for cookies) ->
- IDP -> ``complete_login`` (code + verifier -> Session) ->
- ``verify_session`` on every request -> ``refresh_session`` near expiry ->
- ``revoke_session`` on logout (best-effort, must not raise).
+ Lifecycle: ``start_login`` (redirect URL + PKCE state) -> IDP ->
+ ``complete_login`` (code + verifier -> Session) -> ``verify_session`` per
+ request -> ``refresh_session`` near expiry -> ``revoke_session`` on logout
+ (best-effort, must not raise).
Failure semantics:
- * ``start_login`` / ``complete_login`` raise ``ProviderError`` when the
- IDP is unreachable; ``complete_login`` raises ``InvalidCodeError`` on
- a bad code/state.
- * ``verify_session`` returns ``None`` for expired/unknown tokens and
- raises ``ProviderError`` when unreachable — middleware refreshes on
- the former and answers 503 on the latter.
- * ``refresh_session`` raises ``RefreshExpiredError`` when the token is
- invalid for that provider (an opaque foreign token is
- indistinguishable from an expired one, so middleware tries the rest)
- and ``ProviderError`` on network failure (503 without clearing cookies
- if none succeeds).
+ * ``start_login`` / ``complete_login`` raise ``ProviderError`` when the IDP
+ is unreachable; ``complete_login`` raises ``InvalidCodeError`` on a bad
+ code/state.
+ * ``verify_session`` returns ``None`` for expired/unknown tokens (middleware
+ refreshes) and raises ``ProviderError`` when unreachable (503).
+ * ``refresh_session`` raises ``RefreshExpiredError`` when the token is invalid
+ for that provider (an opaque foreign token looks expired, so middleware
+ tries the rest) and ``ProviderError`` on network failure (503, cookies kept).
Subclasses MUST set ``name`` (stable lowercase id) and ``display_name``.
- Capability flags: ``supports_password`` (renders a credential form and
- implements ``complete_password_login``; ``start_login``/``complete_login``
- may be ``NotImplementedError`` stubs), ``supports_token`` (implements
- ``verify_token`` for the token-auth seam), ``supports_session`` (False for
- token-only credentials such as drain, which are never offered a login).
- Everything downstream of login is identical for every kind of session.
+ Capability flags: ``supports_password`` (credential form +
+ ``complete_password_login``; OAuth methods may be ``NotImplementedError``
+ stubs), ``supports_token`` (``verify_token`` for the token-auth seam),
+ ``supports_session`` (False for token-only credentials such as drain, never
+ offered a login). Everything downstream of login is identical for every session.
"""
name: str = ""
@@ -157,10 +152,9 @@ class DashboardAuthProvider(ABC):
"""Verify a username/password pair and mint a :class:`Session`.
Only called when ``supports_password`` is True. Raise
- ``InvalidCredentialsError`` on rejection (SHOULD spend constant time
- on unknown users to avoid a timing oracle) and ``ProviderError`` when
- the credential store is unreachable. The default raises so a provider
- that forgets the flag fails loudly rather than accepting credentials.
+ ``InvalidCredentialsError`` on rejection (SHOULD be constant time for
+ unknown users — no timing oracle) and ``ProviderError`` when the store is
+ unreachable. The default raises so a mis-flagged provider fails loudly.
"""
raise NotImplementedError(
f"{type(self).__name__} does not support password login "
@@ -170,12 +164,11 @@ class DashboardAuthProvider(ABC):
def verify_token(self, *, token: str) -> "Optional[TokenPrincipal]":
"""Verify a non-interactive bearer token; return its principal.
- Stacking mirrors ``verify_session``: return ``None`` (never raise) for
- a token this provider does not recognise so the seam falls through;
- raise ``ProviderError`` ONLY for a genuine backing-store outage (the
- seam surfaces 503 only if no provider accepts the token). Shared
- secrets MUST be compared with ``hmac.compare_digest``. The default
- raises so a mis-flagged provider fails loudly.
+ Mirrors ``verify_session``: return ``None`` (never raise) for an
+ unrecognised token so the seam falls through; raise ``ProviderError`` ONLY
+ for a genuine backing-store outage. Shared secrets MUST be compared with
+ ``hmac.compare_digest``. The default raises so a mis-flagged provider fails
+ loudly.
"""
raise NotImplementedError(
f"{type(self).__name__} does not support token auth "
@@ -183,10 +176,8 @@ class DashboardAuthProvider(ABC):
def assert_protocol_compliance(cls: type) -> None:
- """Raise ``TypeError`` if ``cls`` doesn't fully implement the provider protocol.
-
- Call it from every provider plugin's unit tests.
- """
+ """Raise ``TypeError`` if ``cls`` doesn't fully implement the provider protocol
+ (call it from every provider plugin's unit tests)."""
for attr in ("name", "display_name"):
if not getattr(cls, attr, ""):
raise TypeError(f"{cls.__name__} missing or empty attribute: {attr!r}")
diff --git a/hermes_cli/dashboard_auth/cookies.py b/hermes_cli/dashboard_auth/cookies.py
index 278d32edf01..49f1bcdb1ff 100644
--- a/hermes_cli/dashboard_auth/cookies.py
+++ b/hermes_cli/dashboard_auth/cookies.py
@@ -1,28 +1,24 @@
"""Cookie helpers for dashboard auth.
-Cookies (all HttpOnly, ``SameSite=Lax`` unless noted, Path = proxy prefix or /):
+All HttpOnly, ``SameSite=Lax`` unless noted, Path = proxy prefix or /:
- hermes_session_at access token; Max-Age = token TTL (~15 min)
- - hermes_session_rt rotating refresh token; written only when the
- provider returned one (AT-only sessions degrade
- gracefully), always cleared on logout/expiry
- - hermes_session_provider non-secret routing hint so a refresh token is
- not handed to the wrong provider when several
- auth plugins are enabled
+ - hermes_session_rt rotating refresh token; written only when the provider
+ returned one, always cleared on logout/expiry
+ - hermes_session_provider non-secret routing hint so an RT is not handed to the
+ wrong provider when several auth plugins are enabled
- hermes_session_pkce PKCE state + CSRF nonce + provider hint, 10 min.
- ``SameSite=None; Secure`` over HTTPS because it is
- set on the /auth/login 302 and must survive the
- cross-site redirect chain out to the IDP and back
- (Chromium drops Lax cookies set on such a 302,
+ ``SameSite=None; Secure`` over HTTPS: it is set on the
+ /auth/login 302 and must survive the cross-site redirect
+ chain (Chromium drops Lax cookies set on such a 302,
crbug 40508226); plain HTTP falls back to Lax.
- hermes_sso_attempt one-shot auto-SSO loop-guard marker (60 s)
-``Secure`` is set only when the request arrived over HTTPS
-(``request.url.scheme``, which honours ``X-Forwarded-Proto`` only from a peer
-in uvicorn's ``forwarded_allow_ips``). Cookie-prefix hardening follows
-draft-west-cookie-prefixes: bare name over HTTP; ``__Host-`` on gated HTTPS
-with Path=/; ``__Secure-`` behind a proxy prefix (``__Host-`` forbids
-Path != /). Setters and readers BOTH resolve the name through
-:func:`_resolved_name` — a mismatch silently breaks sessions.
+``Secure`` only when ``request.url.scheme`` is https (honours ``X-Forwarded-Proto``
+only from uvicorn's ``forwarded_allow_ips``). Cookie-prefix hardening per
+draft-west-cookie-prefixes: bare name over HTTP; ``__Host-`` on gated HTTPS with
+Path=/; ``__Secure-`` behind a proxy prefix (``__Host-`` forbids Path != /). Setters
+and readers BOTH resolve the name via :func:`_resolved_name` — a mismatch silently
+breaks sessions.
"""
from __future__ import annotations
@@ -138,13 +134,9 @@ def _clear_cookie_variants(
response.set_cookie(bare_name, "", max_age=0, **bare_attrs)
-def _lax_bare_attrs(prefix: str) -> dict:
- return {"path": _cookie_path(prefix), "httponly": True, "samesite": "lax"}
-
-
def clear_session_cookies(response: Response, *, prefix: str = "") -> None:
"""Delete the AT, RT and provider cookies (every name variant, active path)."""
- bare_attrs = _lax_bare_attrs(prefix)
+ bare_attrs = _common_attrs(use_https=False, prefix=prefix)
for name in (SESSION_AT_COOKIE, SESSION_RT_COOKIE, SESSION_PROVIDER_COOKIE):
_clear_cookie_variants(
response, name, prefix=prefix, https_samesite="lax", bare_attrs=bare_attrs)
@@ -153,11 +145,10 @@ def clear_session_cookies(response: Response, *, prefix: str = "") -> None:
def encode_pkce_payload(parts: dict[str, str]) -> str:
"""Serialise PKCE segments to the wire value ``base64url(JSON)``, no padding.
- The urlsafe alphabet is a strict subset of RFC 6265 cookie-octets (no
- ``;``, ``"``, ``\\``), so http.cookies never quotes it (strict proxy hops
- such as Go net/http reject the quoted form) and no segment value can
- collide with a delimiter. Padding ``=`` would trigger quoting; the parser
- restores it.
+ The urlsafe alphabet is a strict subset of RFC 6265 cookie-octets, so
+ http.cookies never quotes it (strict proxies such as Go net/http reject the
+ quoted form) and no value can collide with a delimiter. Padding ``=`` would
+ trigger quoting; the parser restores it.
"""
raw = json.dumps(parts, separators=(",", ":"), sort_keys=True)
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")
@@ -207,19 +198,16 @@ def read_pkce_cookie(request: Request) -> Optional[str]:
def parse_pkce_payload(raw: str) -> dict[str, str]:
"""Decode a PKCE cookie value into its segment dict (inverse of
- :func:`encode_pkce_payload`). EVERY reader must go through this — a reader
- that interprets the raw wire value parses zero segments and silently
- disables the check it feeds (provider dispatch, CSRF state, broker binding).
+ :func:`encode_pkce_payload`). EVERY reader must go through this — reading the
+ raw wire value parses zero segments and silently disables the check it feeds
+ (provider dispatch, CSRF state, broker binding).
- Compatibility ladder for cookies minted by an older server during a rolling
- upgrade (10-minute TTL), each rung unambiguous:
+ Compatibility ladder for cookies minted by an older server mid-upgrade:
1. base64url(JSON) — current.
- 2. Oldest flat form with raw ``;`` delimiters — split WITHOUT unquoting
- (the ``next`` segment carries its own URL-encoding; unquoting first
- would turn a ``%3B`` inside it into a bogus delimiter).
- 3. URL-encoded flat form (``quote(payload, safe="")``) — unquote once, split.
- A NEW cookie hitting an OLD server fails the state check and the user
- simply retries; nothing is minted.
+ 2. Flat form with raw ``;`` delimiters — split WITHOUT unquoting (the ``next``
+ segment carries its own URL-encoding; a ``%3B`` inside it is not a delimiter).
+ 3. URL-encoded flat form — unquote once, split.
+ A NEW cookie hitting an OLD server fails the state check; the user retries.
"""
if _B64URL_RE.match(raw):
try:
@@ -249,7 +237,7 @@ def clear_sso_attempt_cookie(response: Response, *, prefix: str = "") -> None:
later silent attempt."""
_clear_cookie_variants(
response, SSO_ATTEMPT_COOKIE, prefix=prefix, https_samesite="lax",
- bare_attrs=_lax_bare_attrs(prefix))
+ bare_attrs=_common_attrs(use_https=False, prefix=prefix))
def detect_https(request: Request) -> bool:
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.py
index b2b962f0658..5b88be85a5b 100644
--- a/hermes_cli/dashboard_auth/middleware.py
+++ b/hermes_cli/dashboard_auth/middleware.py
@@ -57,24 +57,17 @@ _GATE_PUBLIC_PREFIXES: tuple[str, ...] = (
def _path_is_public(path: str) -> bool:
- """True if ``path`` bypasses the gate.
-
- :data:`PUBLIC_API_PATHS` (shared with the legacy middleware) is matched
- exactly so ``/api/status`` never exposes ``/api/status/extension``;
- :data:`_GATE_PUBLIC_PREFIXES` is prefix-matched.
- """
+ """True if ``path`` bypasses the gate: :data:`PUBLIC_API_PATHS` (shared with the
+ legacy middleware) matched exactly so ``/api/status`` never exposes
+ ``/api/status/extension``; :data:`_GATE_PUBLIC_PREFIXES` prefix-matched."""
return path in PUBLIC_API_PATHS or any(
path == p or path.startswith(p) for p in _GATE_PUBLIC_PREFIXES)
def _safe_next_target(request: Request) -> str:
- """URL-encoded ``next`` value for the login redirect, or ``""``.
-
- Only same-origin relative paths outside the auth flow and ``/api`` are
- kept (see :func:`is_safe_next_path`); the query string is preserved. SPA
- deep links that are dropped fall back to the SPA's own
- ``sessionStorage["hermes.lastLocation"]``.
- """
+ """URL-encoded ``next`` value for the login redirect, or ``""``. Only same-origin
+ paths outside the auth flow and ``/api`` are kept (query preserved); dropped
+ deep links fall back to the SPA's ``sessionStorage["hermes.lastLocation"]``."""
path = request.url.path
if not path or not is_safe_next_path(path):
return ""
@@ -84,12 +77,9 @@ def _safe_next_target(request: Request) -> str:
def _unauth_response(request: Request, *, reason: str) -> Response:
"""API routes -> 401 JSON with ``login_url``; HTML routes -> 302 -> /login.
-
- fetch() follows a 302 opaquely into the cross-origin OAuth dance, so API
- routes never get redirects; the SPA's global 401 handler navigates to
- ``login_url`` when ``error`` is ``unauthenticated`` or ``session_expired``.
- Both shapes carry ``next=`` and the active proxy prefix.
- """
+ fetch() follows a 302 opaquely into the cross-origin OAuth dance, so API routes
+ never get redirects; the SPA's 401 handler navigates to ``login_url`` on
+ ``unauthenticated`` / ``session_expired``. Both carry ``next=`` and the prefix."""
next_param = _safe_next_target(request)
prefix = prefix_from_request(request)
login_url = f"{prefix}/login?next={next_param}" if next_param else f"{prefix}/login"
@@ -106,13 +96,12 @@ def _unauth_response(request: Request, *, reason: str) -> Response:
def _auto_sso_response(request: Request) -> Response | None:
"""302 straight to ``/auth/login`` on an unauthenticated HTML load, or ``None``.
- Only when: the request is a document load (not ``/api/*``); exactly one
- interactive provider is registered and it is OAuth-style (a password
- provider must render the form); and the one-shot loop-guard cookie is
- absent. A present marker means the portal had no session for us last time
- — clear it and fall back to ``/login`` rather than ping-pong. Removes the
- interstitial click, not a security check: ``/auth/login`` runs the
- unchanged PKCE flow.
+ Only for a document load (not ``/api/*``) when exactly one interactive
+ provider is registered and it is OAuth-style (a password provider must render
+ the form), and the one-shot loop-guard cookie is absent — a present marker
+ means the portal had no session last time: clear it and fall back to ``/login``
+ rather than ping-pong. Convenience, not a security check: ``/auth/login`` runs
+ the unchanged PKCE flow.
"""
if request.url.path.startswith("/api/"):
return None
@@ -139,11 +128,9 @@ def _auto_sso_response(request: Request) -> Response | None:
def _verify_access_token(
request: Request, *, access_token: str, provider_hint: str | None = None, audit: bool = True):
"""Run ``verify_session`` across the provider stack; Session or ``None``.
-
- ``audit=False`` is the native-app bearer path (no cookie, no server-side
- refresh — the desktop rotates via ``/auth/native/refresh``); same
- 503-on-outage semantics via :func:`scan_session_providers`.
- """
+ ``audit=False`` is the native-app bearer path (no cookie, no server-side refresh
+ — the desktop rotates via ``/auth/native/refresh``); 503-on-outage semantics
+ come from :func:`scan_session_providers`."""
def _audit_unreachable(provider):
if audit:
audit_log(
@@ -242,13 +229,10 @@ async def gated_auth_middleware(
def _attempt_refresh(request: Request, *, refresh_token, provider_hint: str | None = None):
- """Rotate an expired session via the refresh token; ``(Session, provider_name)`` or ``None``.
-
- ``RefreshExpiredError`` rejects the token for that candidate only (Basic
- raises it for foreign opaque tokens too), so remaining providers are
- tried. If none succeeds and any raised ``ProviderError``, re-raises with
- that provider's name so the caller returns 503 without clearing cookies.
- """
+ """Rotate an expired session via the refresh token; ``(Session, provider_name)``
+ or ``None``. ``RefreshExpiredError`` rejects that candidate only (Basic raises it
+ for foreign opaque tokens too); if none succeeds and any raised ``ProviderError``
+ it is re-raised so the caller returns 503 without clearing cookies."""
if not refresh_token:
return None
diff --git a/hermes_cli/dashboard_auth/native_flow.py b/hermes_cli/dashboard_auth/native_flow.py
index ed934efcbd0..19b3ecdf696 100644
--- a/hermes_cli/dashboard_auth/native_flow.py
+++ b/hermes_cli/dashboard_auth/native_flow.py
@@ -99,11 +99,8 @@ def register_pending(
*, code_challenge: str, redirect_uri: str, client_state: str, client_ip: str = "",
now: Optional[int] = None) -> str:
"""Stash a pending native authorization; return an opaque ``broker_state``.
-
- ``code_challenge`` is the DESKTOP's cc_d (the verifier is never seen until
- redemption). Raises ``NativeFlowError`` (fail closed) when the store is at
- capacity or ``client_ip`` already holds ``_MAX_PENDING_PER_IP`` entries.
- """
+ ``code_challenge`` is the DESKTOP's cc_d. Raises ``NativeFlowError`` (fail closed)
+ at store capacity or when ``client_ip`` holds ``_MAX_PENDING_PER_IP`` entries."""
now = _now(now)
broker_state = secrets.token_urlsafe(32)
with _lock:
@@ -131,11 +128,9 @@ def get_pending(broker_state: str, *, now: Optional[int] = None) -> _Pending:
def complete_pending(broker_state: str, *, session: Session, now: Optional[int] = None) -> str:
- """Consume a pending authorization (single use) and mint a one-time gateway
- code bound to the desktop's challenge + the verified ``session``.
-
- Raises :class:`PendingNotFound` if the broker_state is unknown/expired.
- """
+ """Consume a pending authorization (single use) and mint a one-time gateway code
+ bound to the desktop's challenge + ``session``; :class:`PendingNotFound` if
+ unknown/expired."""
now = _now(now)
with _lock:
_gc_locked(now)
@@ -152,12 +147,9 @@ def complete_pending(broker_state: str, *, session: Session, now: Optional[int]
def redeem_code(*, code: str, code_verifier: str, now: Optional[int] = None) -> Session:
- """Verify PKCE + consume a gateway code; return the bound :class:`Session`.
-
- The entry is popped BEFORE the PKCE check so a wrong verifier cannot be
- retried against the same code: on any failure the code is already consumed
- (no oracle, no replay). Raises :class:`CodeInvalid`.
- """
+ """Verify PKCE + consume a gateway code; return the bound :class:`Session`. The
+ entry is popped BEFORE the PKCE check so a wrong verifier cannot be retried
+ (no oracle, no replay). Raises :class:`CodeInvalid`."""
now = _now(now)
with _lock:
_gc_locked(now)
diff --git a/hermes_cli/dashboard_auth/prefix.py b/hermes_cli/dashboard_auth/prefix.py
index e4f08699579..13e950ec013 100644
--- a/hermes_cli/dashboard_auth/prefix.py
+++ b/hermes_cli/dashboard_auth/prefix.py
@@ -91,11 +91,9 @@ def prefix_from_request(request) -> str:
def _normalise_public_url(raw: Optional[str]) -> str:
- """Cleaned ``scheme://netloc[/path]`` (trailing slash stripped so callers
- can append paths) or ``""`` when empty/malformed/injection-suspect. Callers
- treat ``""`` as "fall back to request reconstruction" — an explicit empty
- value is indistinguishable from an unset env var.
- """
+ """Cleaned ``scheme://netloc[/path]`` (trailing slash stripped) or ``""`` when
+ empty/malformed/injection-suspect; ``""`` means "fall back to request
+ reconstruction" (an explicit empty value equals an unset env var)."""
url = raw.strip() if raw else ""
if not url or any(c in url for c in _REJECT_CHARS):
return ""
@@ -129,12 +127,9 @@ def _load_dashboard_section() -> dict:
def resolve_public_url() -> str:
"""Operator-declared dashboard public URL, or ``""`` (reconstruct from request).
-
- Precedence: ``HERMES_DASHBOARD_PUBLIC_URL`` env (empty-after-strip counts
- as unset so a provisioned-but-blank secret cannot shadow config.yaml), then
- ``dashboard.public_url``. A malformed value at either level warns and falls
- through to the next, so a typo in one surface never disables the other.
- """
+ Precedence: ``HERMES_DASHBOARD_PUBLIC_URL`` env (blank counts as unset so a
+ provisioned-but-blank secret cannot shadow config.yaml), then
+ ``dashboard.public_url``; a malformed value warns and falls through."""
env_raw = os.environ.get("HERMES_DASHBOARD_PUBLIC_URL", "")
env_clean = _normalise_public_url(env_raw)
if env_clean:
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.py
index e029defc017..cb811cdc321 100644
--- a/hermes_cli/dashboard_auth/routes.py
+++ b/hermes_cli/dashboard_auth/routes.py
@@ -62,11 +62,10 @@ def _prefix(request: Request) -> str:
def _redirect_uri(request: Request) -> str:
"""Absolute ``/auth/callback`` URL handed to the IDP.
- An operator-declared public URL (``HERMES_DASHBOARD_PUBLIC_URL`` /
- ``dashboard.public_url``) is the complete authority — ``X-Forwarded-Prefix``
- is ignored so an already-baked-in prefix is not doubled. Otherwise
- ``url_for`` (honours ``X-Forwarded-Host/Proto`` under uvicorn
- ``proxy_headers``) with the prefix prepended, which Starlette does not do.
+ An operator-declared public URL is the complete authority (``X-Forwarded-Prefix``
+ ignored so a baked-in prefix is not doubled); otherwise ``url_for`` (honours
+ ``X-Forwarded-Host/Proto`` under uvicorn ``proxy_headers``) with the prefix
+ prepended, which Starlette does not do.
"""
public_url = _prefix_mod.resolve_public_url()
if public_url:
@@ -80,21 +79,15 @@ def _redirect_uri(request: Request) -> str:
def _provider_pkce_segments(cookie_payload: dict[str, str]) -> dict[str, str]:
- """Parse a provider's flat ``state=…;verifier=…`` PKCE string into a dict.
-
- The ONE place the provider's flat form is parsed; from here on the payload
- is a dict down to :func:`set_pkce_cookie`'s base64url(JSON) encoding.
- """
+ """Parse a provider's flat ``state=…;verifier=…`` PKCE string into a dict — the
+ ONE place the flat form is parsed; :func:`set_pkce_cookie` encodes the dict."""
flat = cookie_payload.get("hermes_session_pkce", "")
return dict(seg.split("=", 1) for seg in flat.split(";") if "=" in seg)
def _validate_post_login_target(raw: str) -> str:
- """Return ``raw`` (URL-decoded) if it is a safe same-origin path, else ``""``.
-
- Re-validated at every hop (gate -> /login -> /auth/login -> cookie ->
- callback) because a ``next=`` value can re-enter via a crafted URL.
- """
+ """``raw`` (URL-decoded) if it is a safe same-origin path, else ``""``. Re-validated
+ at every hop because a ``next=`` value can re-enter via a crafted URL."""
if not raw:
return ""
decoded = unquote(raw)
@@ -122,12 +115,9 @@ def _bearer_payload(session: Session) -> dict[str, Any]:
def _finish_native_login(
request: Request, *, broker_state: str, session: Session, provider: str) -> str:
- """Mint the one-time loopback code for a pending native authorization.
-
- Shared tail of ``/auth/callback`` and ``/auth/password-login``: returns the
- desktop's ``redirect_uri?code=…&state=…``. No session cookies are set on
- the native path — the desktop redeems the code at ``/auth/native/token``.
- """
+ """Shared tail of ``/auth/callback`` and ``/auth/password-login``: mint the
+ one-time loopback code and return the desktop's ``redirect_uri?code=…&state=…``.
+ No session cookies on the native path — the desktop redeems at ``/auth/native/token``."""
ip = _client_ip(request)
try:
pending = native_flow.get_pending(broker_state)
@@ -155,12 +145,9 @@ def _login_success(request: Request, session: Session, provider: str) -> None:
def _start_upstream_login(request: Request, p, *, audit_failure: bool, extra_pkce: dict[str, str]):
- """Run ``start_login`` and 302 to the IDP with the PKCE cookie set.
-
- The PKCE cookie is the only server-controlled channel that survives the
- IDP round trip (IDPs echo back only code+state), so it carries the
- provider name plus ``extra_pkce`` (pre-validated ``next`` / native ``broker``).
- """
+ """Run ``start_login`` and 302 to the IDP with the PKCE cookie set. That cookie
+ is the only server-controlled channel surviving the round trip (IDPs echo back
+ only code+state), so it carries the provider name plus ``extra_pkce``."""
try:
ls = p.start_login(redirect_uri=_redirect_uri(request))
except ProviderError as e:
@@ -223,12 +210,9 @@ async def auth_login(request: Request, provider: str, next: str = ""):
def _validate_loopback_redirect_uri(raw: str) -> str:
- """Accept only ``http://127.0.0.1[:port]/…`` / ``http://[::1][:port]/…``.
-
- Security boundary: /auth/native/authorize is public, so a non-loopback host
- would turn the callback into an open redirect leaking a live authorization
- code. ``localhost`` is rejected per RFC 8252 §8.3 (may resolve off-loopback).
- """
+ """Accept only ``http://127.0.0.1[:port]/…`` / ``http://[::1][:port]/…``. Security
+ boundary: the route is public, so a non-loopback host would make the callback
+ an open redirect leaking a live code. ``localhost`` is rejected (RFC 8252 §8.3)."""
if not raw:
raise _http(400, "redirect_uri required")
parsed = urlparse(raw)
@@ -240,14 +224,10 @@ def _validate_loopback_redirect_uri(raw: str) -> str:
def _select_native_provider(provider: str):
- """Resolve the provider for a native authorize request.
-
- An empty ``provider`` auto-selects when exactly one brokerable (non-password)
- session provider exists — password providers can never be the OAuth broker
- target, so a normal OIDC+basic deployment must not fail with "Unknown
- provider". With zero brokerable providers a lone password provider is still
- selected so the caller can emit an explanatory 400 rather than a 404.
- """
+ """Resolve the provider for a native authorize request. An empty ``provider``
+ auto-selects the single brokerable (non-password) session provider — so an
+ OIDC+basic deployment does not fail with "Unknown provider"; with none, a lone
+ password provider is still returned so the caller emits a 400 rather than 404."""
if provider:
return get_provider(provider)
sess_providers = list_session_providers()
@@ -263,14 +243,10 @@ def _select_native_provider(provider: str):
async def auth_native_authorize(
request: Request, provider: str = "", code_challenge: str = "",
code_challenge_method: str = "", redirect_uri: str = "", state: str = ""):
- """Begin an RFC 8252 native-app login for the desktop app.
-
- Stashes a pending broker authorization keyed by an opaque ``broker_state``
- that rides in the gateway's own PKCE cookie, then runs the normal upstream
- round trip; the desktop's challenge/state never touch the cookie. Password
- providers are sent to the ``/login`` form (system browser => OS password
- manager) and ``/auth/password-login`` completes the pending authorization.
- """
+ """Begin an RFC 8252 native-app login: stash a pending broker authorization keyed
+ by an opaque ``broker_state`` riding in the gateway's own PKCE cookie (the
+ desktop's challenge/state never touch it), then run the normal upstream round
+ trip. Password providers go to the ``/login`` form instead."""
if code_challenge_method.upper() != "S256":
raise _http(400, "code_challenge_method must be S256")
if not code_challenge:
@@ -370,10 +346,8 @@ _pw_attempts_lock = threading.Lock()
def _password_rate_limited(ip: str) -> bool:
- """True if ``ip`` exceeded the budget; records the attempt when allowed.
-
- An empty IP shares one bucket — fail-safe toward throttling.
- """
+ """True if ``ip`` exceeded the budget; records the attempt when allowed. An empty
+ IP shares one bucket — fail-safe toward throttling."""
now = time.monotonic()
cutoff = now - _PW_RATE_WINDOW_SEC
with _pw_attempts_lock:
@@ -403,14 +377,12 @@ class _PasswordLoginBody(BaseModel):
async def auth_password_login(request: Request, body: _PasswordLoginBody):
"""Authenticate a username/password against a password provider.
- Returns JSON ``{"ok": true, "next": <path>}`` (the form POSTs via fetch,
- which follows a 302 opaquely) and sets the session cookies. When the PKCE
- cookie carries a native ``broker`` handle, ``next`` is instead the
- desktop's loopback redirect and NO cookies are set.
-
- Failure modes are deliberately generic (no username/provider oracle):
- unknown or non-password provider -> 404; bad credentials -> 401; backing
- store unreachable -> 503; too many attempts from this IP -> 429.
+ Returns ``{"ok": true, "next": <path>}`` (the form POSTs via fetch, which
+ follows a 302 opaquely) and sets the session cookies; with a native ``broker``
+ handle in the PKCE cookie, ``next`` is the desktop's loopback redirect and NO
+ cookies are set. Failures are deliberately generic (no username/provider
+ oracle): unknown/non-password provider 404, bad credentials 401, store
+ unreachable 503, rate limited 429.
"""
ip = _client_ip(request)
if _password_rate_limited(ip):
@@ -504,8 +476,7 @@ async def api_auth_me(request: Request):
@router.post("/api/auth/ws-ticket", name="auth_ws_ticket")
async def api_auth_ws_ticket(request: Request):
"""Mint a 30s single-use ticket for a WS upgrade (browsers cannot set
- ``Authorization`` on the upgrade). One ticket per WS is the expected pattern.
- """
+ ``Authorization`` on the upgrade); one ticket per WS."""
sess = _require_session(request)
from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDS, mint_ticket
@@ -525,12 +496,9 @@ class _NativeTokenBody(BaseModel):
@router.post("/auth/native/token", name="auth_native_token")
async def auth_native_token(request: Request, body: _NativeTokenBody):
- """Exchange a loopback gateway code + PKCE verifier for bearer tokens.
-
- The code is consumed on every path (no verifier oracle, no replay); any
- unknown/expired/redeemed code or PKCE mismatch is a generic 400. Tokens go
- in the JSON body; no cookie is set.
- """
+ """Exchange a loopback gateway code + PKCE verifier for bearer tokens. The code
+ is consumed on every path (no verifier oracle, no replay); any failure is a
+ generic 400. Tokens go in the JSON body; no cookie is set."""
try:
session = native_flow.redeem_code(code=body.code, code_verifier=body.code_verifier)
except native_flow.CodeInvalid:
@@ -550,12 +518,9 @@ class _NativeRefreshBody(BaseModel):
@router.post("/auth/native/refresh", name="auth_native_refresh")
async def auth_native_refresh(request: Request, body: _NativeRefreshBody):
- """Rotate a desktop-held refresh token (mirrors the gate's ``_attempt_refresh``).
-
- Tries each session provider (hinted one first) until one rotates the
- token. Every provider rejecting the RT -> 401 ``session_expired`` (desktop
- starts a fresh login); none rotated and one unreachable -> 503.
- """
+ """Rotate a desktop-held refresh token (mirrors the gate's ``_attempt_refresh``):
+ every provider rejecting the RT -> 401 ``session_expired`` (desktop re-logs);
+ none rotated and one unreachable -> 503."""
if not body.refresh_token:
raise _http(400, "refresh_token required")
try: