Skip to content

The agent that grows with you

fix(auth): mark PKCE invalid_grant dead and store alias logins canonically

Adolanium5eb06591777b
diff --git a/hermes_cli/auth_oauth_pkce_plugin.py b/hermes_cli/auth_oauth_pkce_plugin.py
index 9bcd86ee47b..491672962e5 100644
--- a/hermes_cli/auth_oauth_pkce_plugin.py
+++ b/hermes_cli/auth_oauth_pkce_plugin.py
@@ -35,6 +35,9 @@ logger = logging.getLogger(__name__)
POOL_SOURCE = "manual:loopback_pkce" # ``manual:`` prefix = never pruned by load_pool() re-seeding
_LOOPBACK_LITERALS = frozenset({"127.0.0.1", "::1"})
+# Same grant-dead codes as the pool's plugin recovery (kept local so this module
+# can load while hermes_cli.auth is still importing).
+_GRANT_DEAD_CODES = frozenset({"invalid_grant", "invalid_token", "refresh_token_reused"})
@dataclass(frozen=True)
@@ -56,10 +59,12 @@ class OAuthPKCEConfig:
label: str = ""
-def _err(provider: str, message: str, code: str):
+def _err(provider: str, message: str, code: str, *, relogin_required: bool = False):
from hermes_cli.auth_constants import AuthError
- return AuthError(f"{provider}: {message}", provider=provider, code=code)
+ return AuthError(
+ f"{provider}: {message}", provider=provider, code=code, relogin_required=relogin_required,
+ )
def _host_allowed(host: str, allowlist: Tuple[str, ...]) -> bool:
@@ -104,7 +109,7 @@ def _post_token(provider: str, cfg: OAuthPKCEConfig, data: Dict[str, str], *, co
except Exception as exc:
raise _err(provider, f"OAuth token request failed: {type(exc).__name__}", code) from exc
if response.status_code >= 400:
- raise _err(provider, f"OAuth token request failed with HTTP {response.status_code}.", code)
+ raise _token_http_error(provider, response, code)
payload = response.json()
access_token = str(payload.get("access_token") or "").strip()
if not access_token:
@@ -118,6 +123,34 @@ def _post_token(provider: str, cfg: OAuthPKCEConfig, data: Dict[str, str], *, co
}
+def _token_http_error(provider: str, response: Any, fallback_code: str):
+ """Map a failed token HTTP response. Grant-dead JSON ``error`` values are terminal.
+ The response body is not logged."""
+ error = ""
+ try:
+ payload = response.json()
+ if isinstance(payload, dict):
+ error = str(payload.get("error") or "").strip()
+ except Exception:
+ error = ""
+ if error in _GRANT_DEAD_CODES:
+ return _err(
+ provider,
+ f"OAuth token request failed with HTTP {response.status_code} ({error}).",
+ error,
+ relogin_required=True,
+ )
+ return _err(provider, f"OAuth token request failed with HTTP {response.status_code}.", fallback_code)
+
+
+def _pool_provider(args: Any) -> str:
+ """Canonical profile name for the credential pool. ``args.provider`` may be an alias."""
+ raw = str(getattr(args, "provider", "") or "").strip().lower()
+ from providers import get_provider_profile
+ profile = get_provider_profile(raw)
+ return profile.name if profile is not None else raw
+
+
def login(provider: str, cfg: OAuthPKCEConfig, *, open_browser: bool = True) -> Dict[str, Any]:
"""Run the browser Authorization-Code + PKCE flow; returns the pool fields for the new grant."""
from hermes_cli.auth_device_flow import (
@@ -183,7 +216,7 @@ def pkce_auth_handler(cfg: OAuthPKCEConfig) -> Callable[[str, Any], bool]:
def handler(action: str, args: Any) -> bool:
from agent.credential_pool import AUTH_TYPE_OAUTH, PooledCredential, load_pool
- provider = str(getattr(args, "provider", "") or "").strip().lower()
+ provider = _pool_provider(args)
if action == "add":
tokens = login(provider, cfg, open_browser=not getattr(args, "no_browser", False))
entry = load_pool(provider).add_entry(PooledCredential(
diff --git a/tests/providers/test_oauth_pkce_plugin.py b/tests/providers/test_oauth_pkce_plugin.py
index 89df7aa519f..4f13be866c0 100644
--- a/tests/providers/test_oauth_pkce_plugin.py
+++ b/tests/providers/test_oauth_pkce_plugin.py
@@ -105,3 +105,60 @@ def test_token_url_off_authorize_allowlist_refused_before_any_request(idp, monke
assert {login_err.value.code, refresh_err.value.code} == {"oauth_token_host_rejected"}
with pytest.raises(AuthError, match="HTTPS"):
pkce.validate_config(PROVIDER, _config(idp, authorize_url="http://auth.example.com/authorize"))
+
+
+def test_spent_refresh_token_is_grant_dead_and_marks_the_pool_row_dead(idp, monkeypatch, tmp_path, request):
+ """RFC 6749 invalid_grant on refresh is terminal. The pool must DEAD the row, not EXHAUST it."""
+ from agent.credential_pool import STATUS_DEAD, load_pool
+
+ monkeypatch.setattr(pkce.webbrowser, "open", _browser_hits)
+ monkeypatch.setattr("hermes_cli.auth_device_flow._can_open_graphical_browser", lambda: True)
+ cfg = _config(idp)
+ handler, refresh = pkce.pkce_auth_handler(cfg), pkce.pkce_refresh_credential(cfg)
+ register_provider(ProviderProfile(name=PROVIDER, auth_type="oauth_external",
+ base_url="https://example.invalid/v1",
+ auth_handler=handler, refresh_credential=refresh))
+ request.addfinalizer(lambda: (providers._REGISTRY.pop(PROVIDER, None),
+ hermes_cli.auth.PROVIDER_REGISTRY.pop(PROVIDER, None)))
+ args = SimpleNamespace(provider=PROVIDER, no_browser=False)
+ assert handler("add", args) is True
+ rows = json.loads((tmp_path / "hermes" / "auth.json").read_text())["credential_pool"][PROVIDER]
+ spent = rows[0]["refresh_token"]
+ idp.refresh_tokens.discard(spent)
+
+ with pytest.raises(AuthError) as excinfo:
+ refresh(SimpleNamespace(provider=PROVIDER, id=rows[0]["id"], refresh_token=spent,
+ access_token=rows[0]["access_token"], expires_at_ms=None))
+ assert excinfo.value.code == "invalid_grant" and excinfo.value.relogin_required is True
+
+ pool = load_pool(PROVIDER)
+ result = pool.try_refresh_matching(credential_id=rows[0]["id"])
+ assert result is None or result.last_status == STATUS_DEAD
+ disk = json.loads((tmp_path / "hermes" / "auth.json").read_text())["credential_pool"][PROVIDER][0]
+ assert disk["last_status"] == STATUS_DEAD
+
+
+def test_alias_login_stores_the_row_under_the_canonical_profile_name(idp, monkeypatch, tmp_path, request):
+ """hermes auth add <alias> must write the pool under ProviderProfile.name, not the typed alias."""
+ from agent.credential_pool import load_pool
+
+ alias = "example-pkce-alias"
+ monkeypatch.setattr(pkce.webbrowser, "open", _browser_hits)
+ monkeypatch.setattr("hermes_cli.auth_device_flow._can_open_graphical_browser", lambda: True)
+ cfg = _config(idp)
+ handler = pkce.pkce_auth_handler(cfg)
+ register_provider(ProviderProfile(
+ name=PROVIDER, aliases=(alias,), auth_type="oauth_external",
+ base_url="https://example.invalid/v1",
+ auth_handler=handler, refresh_credential=pkce.pkce_refresh_credential(cfg)))
+ request.addfinalizer(lambda: (
+ providers._REGISTRY.pop(PROVIDER, None),
+ providers._ALIASES.pop(alias, None),
+ hermes_cli.auth.PROVIDER_REGISTRY.pop(PROVIDER, None),
+ hermes_cli.auth.PROVIDER_REGISTRY.pop(alias, None)))
+ args = SimpleNamespace(provider=alias, no_browser=False)
+ assert handler("add", args) is True
+ pool = json.loads((tmp_path / "hermes" / "auth.json").read_text())["credential_pool"]
+ assert PROVIDER in pool and alias not in pool
+ assert handler("status", args) is True
+ assert load_pool(PROVIDER).entries()[0].provider == PROVIDER