The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): keep Nous credentials when Vercel's edge checkpoint blocks a token refresh
kshitijk4poor96f6abaeec88
diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.pyindex 93b74fc9290..13c513053af 100644--- a/hermes_cli/auth_nous.py+++ b/hermes_cli/auth_nous.py@@ -613,6 +613,18 @@ def _refresh_access_token(raise AuthError(f"Nous Portal is temporarily unavailable (HTTP {response.status_code}).",provider="nous", code="temporarily_unavailable", retryable=True)+ # Vercel's Security Checkpoint in front of the Portal answers non-browser clients with a+ # 403 (``x-vercel-mitigated: deny``) or 429 (``challenge``) page (#120602). That is the edge+ # refusing the request, not the token endpoint rejecting the grant, so keep the credentials+ # and retry later instead of forcing a re-login.+ mitigated = response.headers.get("x-vercel-mitigated") if response.status_code in {403, 429} else None+ if mitigated:+ from agent.retry_utils import parse_retry_after_seconds+ raise AuthError(+ f"Nous Portal's edge firewall blocked the token refresh (HTTP {response.status_code}, "+ f"x-vercel-mitigated={mitigated}). Your login is still valid; Hermes will retry.",+ provider="nous", code="upstream_blocked", retryable=True,+ retry_after=parse_retry_after_seconds(response.headers))from hermes_cli.auth import _OAUTH_GRANT_DEAD_CODEStry:error_payload = response.json()diff --git a/tests/hermes_cli/test_auth_nous_provider.py b/tests/hermes_cli/test_auth_nous_provider.pyindex a8e992a5ef6..0e60b3597b6 100644--- a/tests/hermes_cli/test_auth_nous_provider.py+++ b/tests/hermes_cli/test_auth_nous_provider.py@@ -685,31 +685,39 @@ def test_refresh_token_reuse_detection_surfaces_actionable_message():@pytest.mark.parametrize(- "status_code, body, expected_code, expected_terminal",+ "status_code, body, headers, expected_code, expected_terminal",[- (500, None, "temporarily_unavailable", False),- (503, None, "temporarily_unavailable", False),- (599, None, "temporarily_unavailable", False),- (429, {"code": "429", "message": "rate limited"}, None, False),- (404, {"message": "not found"}, None, False),- (400, ValueError("not json"), None, False),- (401, {"message": "unauthorized"}, "invalid_grant", True),- (403, ValueError("not json"), "invalid_grant", True),- (400, ["not", "a", "dict"], None, False),- (401, "unauthorized", "invalid_grant", True),+ (500, None, {}, "temporarily_unavailable", False),+ (503, None, {}, "temporarily_unavailable", False),+ (599, None, {}, "temporarily_unavailable", False),+ (429, {"code": "429", "message": "rate limited"}, {}, None, False),+ (404, {"message": "not found"}, {}, None, False),+ (400, ValueError("not json"), {}, None, False),+ (401, {"message": "unauthorized"}, {}, "invalid_grant", True),+ (403, ValueError("not json"), {}, "invalid_grant", True),+ (400, ["not", "a", "dict"], {}, None, False),+ (401, "unauthorized", {}, "invalid_grant", True),+ # Vercel Security Checkpoint in front of the Portal (#120602): the edge, not the token+ # endpoint, refused the request -- the refresh token is still good.+ (403, ValueError("not json"), {"x-vercel-mitigated": "deny"}, "upstream_blocked", False),+ (429, ValueError("not json"), {"x-vercel-mitigated": "challenge"}, "upstream_blocked", False),+ # A 401 is the token endpoint speaking even behind the edge header: stays terminal.+ (401, ValueError("not json"), {"x-vercel-mitigated": "deny"}, "invalid_grant", True),],)def test_refresh_token_exchange_error_classification(- status_code, body, expected_code, expected_terminal+ status_code, body, headers, expected_code, expected_terminal):"""A Portal 5xx is transient even when its body is not OAuth JSON (#120976), and anon-5xx body that carries no OAuth ``error`` code must not be treated as a dead grant --- except a 401/403, which always means the refresh token itself was rejected."""+ except a 401/403, which always means the refresh token itself was rejected, unless the+ 403/429 carries ``x-vercel-mitigated`` (the edge firewall answered, not the Portal; #120602)."""from hermes_cli.auth import _is_terminal_nous_refresh_error, _refresh_access_tokenclass _FakeResponse:def __init__(self):self.status_code = status_code+ self.headers = dict(headers)def json(self):if body is None:@@ -733,10 +741,86 @@ def test_refresh_token_exchange_error_classification(assert exc_info.value.code == expected_codeassert exc_info.value.relogin_required is expected_terminalassert _is_terminal_nous_refresh_error(exc_info.value) is expected_terminal- if expected_code == "temporarily_unavailable":+ if expected_code in {"temporarily_unavailable", "upstream_blocked"}:assert exc_info.value.retryable is True+def test_refresh_token_exchange_edge_block_carries_retry_after():+ """A checkpointed 429 hands its ``Retry-After`` to the caller as the cooldown hint."""+ from hermes_cli.auth import _refresh_access_token++ class _FakeResponse:+ status_code = 429+ headers = {"x-vercel-mitigated": "challenge", "Retry-After": "30"}++ def json(self):+ raise ValueError("not json")++ class _FakeClient:+ def post(self, *args, **kwargs):+ return _FakeResponse()++ with pytest.raises(AuthError) as exc_info:+ _refresh_access_token(+ client=_FakeClient(), portal_base_url="https://portal.nousresearch.com",+ client_id="hermes-cli", refresh_token="refresh-still-valid")++ assert exc_info.value.code == "upstream_blocked"+ assert exc_info.value.retry_after == 30.0+ assert "edge firewall" in str(exc_info.value)+ assert "x-vercel-mitigated=challenge" in str(exc_info.value)++[email protected]("status_code", [403, 429])+def test_runtime_refresh_edge_block_preserves_nous_oauth_credentials(+ tmp_path, monkeypatch, status_code+):+ """A Vercel Security Checkpoint deny/challenge on the token endpoint must not quarantine the+ still-valid refresh token or tell the user to re-login (#120602)."""+ import hermes_cli.auth as auth_mod+ import hermes_cli.auth_nous as auth_nous++ hermes_home = tmp_path / "hermes"+ access_token = _invoke_jwt(seconds=3600)+ refresh_token = "refresh-still-valid"+ _setup_nous_auth(+ hermes_home, access_token=access_token, refresh_token=refresh_token,+ expires_at=_future_iso(3600), expires_in=3600)+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))++ class _FakeResponse:+ headers = {"x-vercel-mitigated": "deny" if status_code == 403 else "challenge"}++ def __init__(self):+ self.status_code = status_code++ def json(self):+ raise ValueError("Forbidden is not JSON")++ class _FakeClient:+ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ def post(self, *args, **kwargs):+ return _FakeResponse()++ monkeypatch.setattr(auth_nous, "_nous_http_client", lambda *args: _FakeClient())++ with pytest.raises(AuthError) as exc_info:+ auth_mod.resolve_nous_runtime_credentials(force_refresh=True)++ state = auth_mod.get_provider_auth_state("nous")+ assert state["access_token"] == access_token+ assert state["refresh_token"] == refresh_token+ assert "last_auth_error" not in state+ assert exc_info.value.code == "upstream_blocked"+ assert exc_info.value.relogin_required is False+ assert exc_info.value.retryable is True++def test_runtime_refresh_503_preserves_nous_oauth_credentials(tmp_path, monkeypatch):"""The real runtime resolver must not quarantine credentials during a Portal outage (#120976)."""import hermes_cli.auth as auth_mod