Skip to content

The agent that grows with you

fix(doctor): validate GITHUB_TOKEN/GH_TOKEN against api.github.com and name the .env file

teknium117958bfef30f
diff --git a/hermes_cli/doctor_connectivity.py b/hermes_cli/doctor_connectivity.py
index 7ac5f44d412..60ded153579 100644
--- a/hermes_cli/doctor_connectivity.py
+++ b/hermes_cli/doctor_connectivity.py
@@ -368,6 +368,38 @@ def _probe_ipv6_path() -> ProbeResult:
return _row(name, "ok", f"(IPv6 path to {host} reachable)") # refused/reset also prove a live path
+GITHUB_API_USER_URL = "https://api.github.com/user"
+
+
+def _probe_github_token() -> ProbeResult:
+ """Validate a configured ``GITHUB_TOKEN``/``GH_TOKEN`` against api.github.com (#115257).
+
+ A dead PAT in ``.env`` used to fail every git-auth clone with a message that never named the
+ token; the resolver now falls through to the gh CLI, and this row tells the user WHICH file
+ still carries the stale token so they can remove it.
+ """
+ name = "GitHub token"
+ from hermes_cli.config import get_env_value, load_env
+ var = next((v for v in ("GITHUB_TOKEN", "GH_TOKEN") if get_env_value(v)), None)
+ if var is None:
+ return _skip(name) # the Skills Hub section already reports gh-CLI / no-token state
+ from hermes_cli.doctor import _DHH
+ where = f"{_DHH}/.env" if var in load_env() else "the environment"
+ try:
+ import httpx
+ r = httpx.get(GITHUB_API_USER_URL, timeout=10, headers={
+ "Authorization": f"Bearer {get_env_value(var)}", "User-Agent": _HERMES_USER_AGENT,
+ "Accept": "application/vnd.github+json"})
+ except Exception as e:
+ return _row(name, "fail", f"({e})", ["Check network connectivity"])
+ if r.status_code == 200:
+ return _row(name, "ok", f"({var} from {where} accepted by api.github.com)")
+ if r.status_code == 401:
+ return _row(name, "fail", f"({var} in {where} rejected by api.github.com — expired or revoked)",
+ [f"{var} in {where} is expired or revoked: remove it (gh CLI login is used instead) or paste a fresh token"])
+ return _row(name, "fail", f"(HTTP {r.status_code} from api.github.com)")
+
+
def build_probes() -> list:
"""(label, callable) pairs in display order."""
global _APIKEY_PROVIDERS_CACHE
@@ -379,6 +411,7 @@ def build_probes() -> list:
# functools.partial binds each row's args so every callable keeps its own provider.
*((row[0], functools.partial(_probe_apikey_provider, *row)) for row in _APIKEY_PROVIDERS_CACHE),
("AWS Bedrock", _probe_bedrock), ("Azure Foundry (Entra ID)", _probe_azure_entra),
+ ("GitHub token", _probe_github_token),
]
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index 0df11bb5fe1..e7d67d3e4db 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -419,7 +419,7 @@ def _check_skills_hub(should_fix: bool, f: Finding) -> None:
check_warn(f"{q_count} skill(s) in quarantine", "(pending review)")
from hermes_cli.config import get_env_value
if get_env_value("GITHUB_TOKEN") or get_env_value("GH_TOKEN"):
- check_ok("GitHub token configured (authenticated API access)")
+ check_ok("GitHub token configured", "(validity checked under API Connectivity)")
else:
check_bool(_gh_authenticated(), ("GitHub authenticated via gh CLI", "(full API access — no GITHUB_TOKEN needed)"),
("No GITHUB_TOKEN", f"(60 req/hr rate limit — set in {_DHH}/.env for better rates)"))
diff --git a/tests/hermes_cli/test_doctor_github_token_probe.py b/tests/hermes_cli/test_doctor_github_token_probe.py
new file mode 100644
index 00000000000..d0c821e9ad0
--- /dev/null
+++ b/tests/hermes_cli/test_doctor_github_token_probe.py
@@ -0,0 +1,86 @@
+"""``hermes doctor`` validates a configured GITHUB_TOKEN/GH_TOKEN against api.github.com (#115257).
+
+An expired PAT left in ``.env`` used to be reported as "GitHub token configured" while every
+git-auth clone failed with a Git-level message that never named the token. The doctor now sends
+the token to the REST API and, on a refusal, names the variable and the ``.env`` file carrying it.
+"""
+
+from __future__ import annotations
+
+import json
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+import pytest
+
+from hermes_cli import doctor_connectivity as dc
+
+# GitHub's documented 401 body for a bad/expired token (REST API "Authentication" docs).
+_BAD_CREDENTIALS = {"message": "Bad credentials", "documentation_url": "https://docs.github.com/rest"}
+
+
+def github_stand_in(monkeypatch):
+ seen: list[dict] = []
+
+ class Handler(BaseHTTPRequestHandler):
+ status = 401
+
+ def do_GET(self): # noqa: N802 - http.server API
+ seen.append({"path": self.path, "authorization": self.headers.get("Authorization")})
+ body = json.dumps(_BAD_CREDENTIALS if self.status == 401 else {"login": "octocat"}).encode()
+ self.send_response(self.status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, format, *args): # noqa: A002 - http.server API; quiet
+ pass
+
+ srv = HTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ monkeypatch.setattr(dc, "GITHUB_API_USER_URL", f"http://127.0.0.1:{srv.server_port}/user")
+ yield Handler, seen
+ srv.shutdown()
+
+
+def _github_probe_row(monkeypatch, tmp_path, dotenv: str | None, *, name: str = "home"):
+ """Drive the production entry point: the doctor's probe table, run by ``run_probes``."""
+ home = tmp_path / name
+ home.mkdir()
+ if dotenv is not None:
+ (home / ".env").write_text(dotenv, encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ monkeypatch.setattr(dc, "_APIKEY_PROVIDERS_CACHE", [])
+ probes = [(label, fn) for label, fn in dc.build_probes() if label == "GitHub token"]
+ assert probes, "GitHub token probe missing from the doctor's connectivity table"
+ (result,) = dc.run_probes(probes)
+ return result
+
+
+def test_expired_dotenv_token_is_rejected_and_the_env_file_is_named(monkeypatch, tmp_path, github_stand_in):
+ handler, seen = github_stand_in
+ handler.status = 401
+ result = _github_probe_row(monkeypatch, tmp_path, "GITHUB_TOKEN=ghp_expired000000000000000000000000000000\n")
+ ((glyph, _label, detail),) = result.lines
+ assert "✗" in glyph
+ assert "GITHUB_TOKEN" in detail and "/.env" in detail and "rejected" in detail
+ assert result.issues and "GITHUB_TOKEN" in result.issues[0] and "/.env" in result.issues[0]
+ # The real token went to the API (not a synthetic pass) and never leaks into the row text.
+ assert seen and seen[0]["authorization"] == "Bearer ghp_expired000000000000000000000000000000"
+ assert "ghp_expired" not in detail and "ghp_expired" not in result.issues[0]
+
+
+def test_valid_token_is_ok_and_no_token_is_skipped(monkeypatch, tmp_path, github_stand_in):
+ handler, seen = github_stand_in
+ handler.status = 200
+ result = _github_probe_row(monkeypatch, tmp_path, "GH_TOKEN=gho_valid00000000000000000000000000000000\n")
+ ((glyph, _label, detail),) = result.lines
+ assert "✓" in glyph and "GH_TOKEN" in detail and not result.issues
+
+ seen.clear()
+ result = _github_probe_row(monkeypatch, tmp_path, None, name="home-without-token")
+ assert result.lines == [] and result.issues == [] and seen == [] # nothing configured: no request, no row
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index dff358df997..54242ba7fe5 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -219,6 +219,10 @@ SSH sources (`git@host:owner/repo.git`) authenticate through your ssh-agent as
before. The same resolution applies to `hermes plugins update`, catalog MCP
installs from git, and profile distributions fetched from a git URL.
+`hermes doctor` sends a configured `GITHUB_TOKEN`/`GH_TOKEN` to `api.github.com`
+(under **API Connectivity**) and, when GitHub rejects it, names the variable and the
+`.env` file that carries the expired token so you can remove or replace it.
+
### What the allow-list does NOT gate
Several categories of plugin bypass `plugins.enabled` — they're part of Hermes' built-in surface and would break basic functionality if gated off by default: