The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(skills): a revoked GITHUB_TOKEN no longer blocks hub installs; fall through to gh auth / anonymous and name it (#98725)
Teknium351e5f05a07f
diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.pyindex 18c83954e67..244e04bd594 100644--- a/hermes_cli/skills_hub.py+++ b/hermes_cli/skills_hub.py@@ -605,11 +605,14 @@ def _print_fetch_failure(c: Console, sources, identifier: str, meta=None, sourcerate_limited = any(getattr(src, "is_rate_limited", False)or getattr(getattr(src, "github", None), "is_rate_limited", False)for src in sources)+ # Credentials GitHub refused with 401 (the fetch already fell through past them, #98725).+ rejected = next((r for src in sources+ if isinstance(r := getattr(getattr(src, "auth", None), "rejected", None), list) and r), [])# Index hit but files gone: a stale index entry, not a user typo — name it so users stop- # re-trying spellings (#3259). Only when no adapter was rate limited: a throttled fetch- # also yields meta-without-bundle, and calling that "stale" would send users away from a- # skill that exists.- if meta is not None and not rate_limited:+ # re-trying spellings (#3259). Only when no adapter was rate limited or refused a credential:+ # those fetches also yield meta-without-bundle, and calling that "stale" would send users away+ # from a skill that exists.+ if meta is not None and not rate_limited and not rejected:src_id = getattr(source, "source_id", lambda: "the registry")()c.print(f"[bold red]Error:[/] '{identifier}' is listed in the {src_id} index, "f"but its files no longer exist upstream.")@@ -617,6 +620,9 @@ def _print_fetch_failure(c: Console, sources, identifier: str, meta=None, source"its author. Try `hermes skills search` for an alternative.[/]\n")returnc.print(f"[bold red]Error:[/] Could not download '{identifier}'.")+ if rejected:+ c.print(f"[yellow]Hint:[/] GitHub rejected {' and '.join(rejected)} (401 Bad credentials). "+ f"Replace or remove the token in {display_hermes_home()}/.env, or re-run [bold]gh auth login[/].")if rate_limited:c.print("[yellow]Hint:[/] GitHub API rate limit exhausted ""(unauthenticated: 60 requests/hour).\n"diff --git a/tests/hermes_cli/test_skills_hub.py b/tests/hermes_cli/test_skills_hub.pyindex c54d3d1e45f..4ae60497a58 100644--- a/tests/hermes_cli/test_skills_hub.py+++ b/tests/hermes_cli/test_skills_hub.py@@ -605,6 +605,22 @@ def test_do_install_stale_index_names_the_problem(monkeypatch):assert "Could not fetch" not in out+def test_fetch_failure_names_rejected_github_credential():+ """A credential GitHub refused is named, never reported as a stale index entry (#98725)."""+ from types import SimpleNamespace+ from hermes_cli.skills_hub import _print_fetch_failure++ src = SimpleNamespace(is_rate_limited=False, auth=SimpleNamespace(rejected=["GITHUB_TOKEN/GH_TOKEN"]),+ source_id=lambda: "hermes-index")+ sink = StringIO()+ console = Console(file=sink, force_terminal=False, color_system=None, width=200)+ _print_fetch_failure(console, [src], "o/r/s", meta=object(), source=src)++ out = sink.getvalue()+ assert "rejected GITHUB_TOKEN/GH_TOKEN" in out+ assert "Stale index entry" not in out++@pytest.mark.parametrize("meta_hit", [False, True])def test_do_install_generic_when_no_index_hit_or_rate_limited(monkeypatch, meta_hit):"""No index hit — or a throttled fetch that only *looks* like a stale entry — keeps thediff --git a/tests/tools/test_skills_hub.py b/tests/tools/test_skills_hub.pyindex 0bc5b0199ca..f1bfa6d221d 100644--- a/tests/tools/test_skills_hub.py+++ b/tests/tools/test_skills_hub.py@@ -156,6 +156,29 @@ class TestGitHubSourceFileFetch:"skill/references/foo%23bar.md")+ @pytest.mark.parametrize("gh_token", ["gh-live", "gh-dead"])+ def test_rejected_token_falls_through_to_next_credential(self, monkeypatch, gh_token):+ """A 401 on the .env token retries with `gh auth token`, then anonymously (#98725)."""+ import tools.skills_hub as hub+ auth = GitHubAuth()+ monkeypatch.setattr(auth, "_try_pat", lambda: "pat-dead")+ monkeypatch.setattr(auth, "_try_gh_cli", lambda: gh_token)+ monkeypatch.setattr(auth, "_try_github_app", lambda: None)+ sent = []++ def fake_get(url, *, headers, **_kw):+ sent.append(headers)+ dead = headers.get("Authorization", "").endswith("-dead")+ return httpx.Response(401 if dead else 200, content=b"body")++ monkeypatch.setattr(hub, "_skills_hub_http_get", fake_get)+ assert GitHubSource(auth)._fetch_file_bytes("o/r", "s/SKILL.md") == b"body"+ expected = ["token pat-dead", "token gh-live"] if gh_token == "gh-live" else [+ "token pat-dead", "token gh-dead", None]+ assert [h.get("Authorization") for h in sent] == expected+ assert sent[-1]["Accept"] == "application/vnd.github.v3.raw"+ assert auth.rejected[0] == "GITHUB_TOKEN/GH_TOKEN"+# ---------------------------------------------------------------------------# SkillsShSource# ---------------------------------------------------------------------------diff --git a/tools/skills_hub_github.py b/tools/skills_hub_github.pyindex 0b9257a8a4f..81a735796b0 100644--- a/tools/skills_hub_github.py+++ b/tools/skills_hub_github.py@@ -78,6 +78,10 @@ class GitHubAuth:self._cached_token: Optional[str] = Noneself._cached_method: Optional[str] = Noneself._app_token_expiry: float = 0+ # Credentials GitHub answered 401 to: skipped from then on so the chain falls through (#98725).+ self._rejected_tokens: set = set()+ self._rejected_methods: set = set()+ self.rejected: List[str] = [] # human labels, for the install errordef get_headers(self) -> Dict[str, str]:token = self._resolve_token()@@ -97,8 +101,8 @@ class GitHubAuth:for method, resolve in (("pat", self._try_pat), ("gh-cli", self._try_gh_cli), ("github-app", self._try_github_app),):- token = resolve()- if token:+ token = None if method in self._rejected_methods else resolve()+ if token and token not in self._rejected_tokens:self._cached_token, self._cached_method = token, methodif method == "github-app":self._app_token_expiry = time.time() + 3500 # ~58 min (tokens last 1 hour)@@ -106,6 +110,21 @@ class GitHubAuth:self._cached_method = "anonymous"return None+ def reject(self, token: str) -> None:+ """GitHub answered 401 Bad credentials to *token*: stop sending it, so the next method and+ finally anonymous are tried. A revoked GITHUB_TOKEN in .env otherwise shadows a working+ `gh auth login` (and anonymous access to public repos) for the whole process."""+ if token in self._rejected_tokens:+ return+ self._rejected_tokens.add(token)+ if token == self._cached_token and self._cached_method:+ label = {"pat": "GITHUB_TOKEN/GH_TOKEN", "gh-cli": "`gh auth token`"}.get(+ self._cached_method, "the GitHub App token")+ self._rejected_methods.add(self._cached_method)+ self.rejected.append(label)+ self._cached_token = self._cached_method = None+ logger.warning("GitHub rejected %s (401 Bad credentials); trying the next credential", label)+@staticmethoddef _try_pat() -> Optional[str]:# Profile-scoped secret lookup (multiplexed gateway safe).@@ -113,16 +132,10 @@ class GitHubAuth:return get_secret("GITHUB_TOKEN") or get_secret("GH_TOKEN")def _try_gh_cli(self) -> Optional[str]:- try:- result = subprocess.run(- ["gh", "auth", "token"], capture_output=True, text=True, encoding='utf-8', errors='replace',- timeout=5, stdin=subprocess.DEVNULL, creationflags=windows_hide_flags(),- )- if result.returncode == 0 and result.stdout.strip():- return result.stdout.strip()- except (FileNotFoundError, subprocess.TimeoutExpired) as e:- logger.debug("gh CLI token lookup failed: %s", e)- return None+ # Shared with git clones: strips GH_TOKEN/GITHUB_TOKEN, which gh would otherwise echo back+ # instead of its keyring login (the dead .env token would come back as the "gh" credential).+ from hermes_cli.git_credentials import _gh_cli_token+ return _gh_cli_token()def _try_github_app(self) -> Optional[str]:from agent.secret_scope import get_secret@@ -471,6 +484,14 @@ class GitHubSource(SkillSource):last_resp = respif resp.status_code == 200:return resp+ sent = hdrs.get("Authorization", "")+ if resp.status_code == 401 and sent:+ # Bad credentials: same request with the next credential, then anonymous.+ self.auth.reject(sent.split(" ", 1)[-1])+ retry = {k: v for k, v in hdrs.items() if k != "Authorization"}+ retry.update((k, v) for k, v in self.auth.get_headers().items() if k == "Authorization")+ return self._github_get(url, params=params, headers=retry, timeout=timeout,+ max_retries=max_retries)if resp.status_code in (403, 429):limited = _is_rate_limit_response(resp)if not limited or last_attempt: