Skip to content

The agent that grows with you

fix(plugins): attach stored git credentials only after an anonymous refusal, on every network verb

teknium19b55e7e6ac25
diff --git a/hermes_cli/git_credentials.py b/hermes_cli/git_credentials.py
index c6ffb5b57bf..017582b9194 100644
--- a/hermes_cli/git_credentials.py
+++ b/hermes_cli/git_credentials.py
@@ -15,6 +15,12 @@ Resolution order for an ``https://`` URL:
3. ``git credential fill`` against the user's configured credential helpers (any host: GitLab,
Bitbucket, self-hosted) with prompting disabled, so a stored credential is returned and a
missing one fails in ~100 ms instead of asking.
+
+The credential is attached only after an anonymous attempt is refused
+(:func:`run_git_with_credential_fallback`). Most catalog repos are public, and a stale or
+revoked stored token sent pre-emptively turns a clone that works anonymously into a 401 that git
+can only answer with the prompt this module disables — "could not read Username for
+'https://github.com': terminal prompts disabled".
"""
from __future__ import annotations
@@ -22,6 +28,7 @@ from __future__ import annotations
import base64
import logging
import os
+import re
import shutil
import subprocess
import urllib.parse
@@ -125,3 +132,41 @@ def with_git_auth(env: Mapping[str, str], url: str) -> dict[str, str]:
env[f"GIT_CONFIG_VALUE_{idx}"] = f"Authorization: basic {encoded}"
env["GIT_CONFIG_COUNT"] = str(idx + 1)
return env
+
+
+# What git prints when the remote wants a credential it could not obtain: the prompt that
+# GIT_TERMINAL_PROMPT=0 refused, a rejected credential, or a bare 401/403 from the server.
+_CREDENTIAL_REQUIRED_RE = re.compile(
+ r"could not read (?:username|password)|terminal prompts disabled|authentication failed"
+ r"|(?:error|status|http)[: ]+40[13]\b",
+ re.IGNORECASE,
+)
+
+
+def is_credential_required_error(result: subprocess.CompletedProcess) -> bool:
+ """True when a failed git run says the remote demands a credential (vs. a typo'd URL,
+ a missing commit, a network error, ...)."""
+ parts = []
+ for stream in (result.stderr, result.stdout):
+ if isinstance(stream, bytes):
+ stream = stream.decode("utf-8", errors="replace")
+ parts.append(stream or "")
+ return _CREDENTIAL_REQUIRED_RE.search("\n".join(parts)) is not None
+
+
+def run_git_with_credential_fallback(
+ argv: list[str], url: str, *, env: Mapping[str, str], **run_kwargs,
+) -> subprocess.CompletedProcess:
+ """Run the git network verb *argv* against *url* anonymously; when the remote refuses with
+ the credential-required class and the user owns a credential for that host, rerun once with
+ it attached. *env* is a :func:`noninteractive_git_env`; *run_kwargs* must capture output so
+ the refusal can be classified. Empty *url* means no fallback (local verbs)."""
+ run_kwargs.setdefault("stdin", subprocess.DEVNULL)
+ env = dict(env)
+ result = subprocess.run(argv, env=env, **run_kwargs)
+ if result.returncode == 0 or not url or not is_credential_required_error(result):
+ return result
+ auth_env = with_git_auth(env, url)
+ if auth_env == env:
+ return result
+ return subprocess.run(argv, env=auth_env, **run_kwargs)
diff --git a/hermes_cli/mcp_catalog.py b/hermes_cli/mcp_catalog.py
index bdc8797d536..b941c6ddc93 100644
--- a/hermes_cli/mcp_catalog.py
+++ b/hermes_cli/mcp_catalog.py
@@ -420,11 +420,15 @@ def _do_git_install(entry: CatalogEntry) -> Path:
# upfront so the fast path doesn't always fail noisily before the full-clone fallback.
is_sha_ref = bool(re.fullmatch(r"[0-9a-f]{7,40}", install.ref))
# Never hang on a credential prompt: installs run from CLI/dashboard flows nobody can answer.
- from hermes_cli.git_credentials import with_git_auth
- _git_env = with_git_auth(noninteractive_git_env(), install.url)
+ from hermes_cli.git_credentials import run_git_with_credential_fallback
def _git(*args: str) -> int:
- return subprocess.run([git, *args], stdin=subprocess.DEVNULL, env=_git_env).returncode
+ result = run_git_with_credential_fallback(
+ [git, *args], install.url, env=noninteractive_git_env(),
+ capture_output=True, text=True, encoding="utf-8", errors="replace")
+ if result.returncode != 0 and (result.stderr or "").strip():
+ _say(result.stderr.strip(), Colors.DIM)
+ return result.returncode
if not is_sha_ref and _git("clone", "--depth", "1", "--branch", install.ref, install.url, str(dest)) != 0:
# Branch/tag form failed (e.g. ref deleted upstream): fall through to full-clone path.
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index 00d1b102731..b09b20f303a 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -604,51 +604,15 @@ def _check_manifest_version(manifest: dict, plugin_name: str) -> None:
) from None
-def _is_credential_required_error(result: subprocess.CompletedProcess) -> bool:
- """True when git's exit looks like a credential/permission prompt that ``GIT_TERMINAL_PROMPT=0``
- blocked, or a server-side 401/403 — the class of error that says "this repo needs auth"."""
- blob = f"{result.stderr or ''}\n{result.stdout or ''}".lower()
- return (
- "could not read username" in blob
- or "could not read password" in blob
- or "authentication failed" in blob
- or "terminal prompts disabled" in blob
- or " 401 " in blob
- or " 403 " in blob
- )
-
-
-def _clone_with_auth_fallback(
- git_exe: str, target: Path, *clone_args: str, auth_url: str = ""
-) -> subprocess.CompletedProcess:
- """Run *clone_args* against *target* anonymously first, then retry with the user's stored
- HTTPS credential only when the first attempt fails with a credential-required error.
-
- Public catalog repos must clone without a credential — injecting ``Authorization: basic``
- against a public GitHub URL breaks the anonymous path (GitHub rejects the Basic header and
- git falls back to a Username prompt that ``GIT_TERMINAL_PROMPT=0`` blocks, surfacing as
- "could not read Username ... terminal prompts disabled", #114526). Private repos that
- genuinely demand auth reach the fallback naturally when anonymous access is refused.
- """
- result = _run_plugin_git(git_exe, target, *clone_args)
- if result.returncode == 0 or not _is_credential_required_error(result) or not auth_url:
- return result
- return _run_plugin_git(git_exe, target, *clone_args, auth_url=auth_url)
-
-
def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str]) -> str:
"""Shallow-clone *git_url* into *tmp_clone* (detached at *revision* when given), scrub any
- credentials from the recorded origin, and return the installed HEAD SHA.
-
- Clones anonymously first; only falls back to the user's stored HTTPS credential when the
- remote explicitly demands one (regression guard for #114526, where injecting ``gh auth``'s
- token against a public catalog URL broke the anonymous path)."""
+ credentials from the recorded origin, and return the installed HEAD SHA."""
git_exe = _resolve_git_executable()
if not git_exe:
raise PluginOperationError("git is not installed or not in PATH.")
clone_args = ["clone", "--depth", "1", *(["--no-checkout"] if revision else []), git_url, str(tmp_clone)]
try:
- result = _clone_with_auth_fallback(git_exe, tmp_clone.parent, *clone_args, auth_url=git_url)
+ result = _run_plugin_git(git_exe, tmp_clone.parent, *clone_args, auth_url=git_url)
except FileNotFoundError as e:
raise PluginOperationError("git is not installed or not in PATH.") from e
except subprocess.TimeoutExpired as e:
@@ -2029,14 +1993,12 @@ def _run_plugin_git(
git_exe: str, target: Path, *args: str, timeout: int = 60, auth_url: str = "",
) -> subprocess.CompletedProcess:
"""Run one git command inside a plugin checkout (non-interactive). *auth_url* names the remote
- a network verb talks to so a stored user credential for its host is attached (private repos)."""
- env = noninteractive_git_env()
- if auth_url:
- from hermes_cli.git_credentials import with_git_auth
- env = with_git_auth(env, auth_url)
- return subprocess.run(
- [git_exe, *args], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout,
- cwd=str(target), stdin=subprocess.DEVNULL, env=env)
+ a network verb talks to; it runs anonymously first and a stored user credential for that host
+ is attached only when the remote refuses anonymous access (private repos)."""
+ from hermes_cli.git_credentials import run_git_with_credential_fallback
+ return run_git_with_credential_fallback(
+ [git_exe, *args], auth_url, env=noninteractive_git_env(), capture_output=True, text=True,
+ encoding='utf-8', errors='replace', timeout=timeout, cwd=str(target))
def _stash_ref(git_exe: str, target: Path) -> str:
diff --git a/hermes_cli/profile_distribution.py b/hermes_cli/profile_distribution.py
index 639e550066f..16e77d80a54 100644
--- a/hermes_cli/profile_distribution.py
+++ b/hermes_cli/profile_distribution.py
@@ -231,17 +231,16 @@ def _looks_like_git_url(s: str) -> bool:
def _git_clone(url: str, dest: Path) -> None:
if _GITHUB_SHORTHAND_RE.match(url):
url = f"https://{url.rstrip('/')}"
- from hermes_cli.git_credentials import with_git_auth
+ from hermes_cli.git_credentials import run_git_with_credential_fallback
try:
- subprocess.run(
- ["git", "clone", "--depth", "1", url, str(dest)], check=True, capture_output=True,
- stdin=subprocess.DEVNULL, env=with_git_auth(noninteractive_git_env(), url),
+ result = run_git_with_credential_fallback(
+ ["git", "clone", "--depth", "1", url, str(dest)], url, env=noninteractive_git_env(),
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
)
except FileNotFoundError as exc:
raise DistributionError("git is required for git-URL installs") from exc
- except subprocess.CalledProcessError as exc:
- stderr = exc.stderr.decode("utf-8", errors="replace") if exc.stderr else ""
- raise DistributionError(f"git clone failed: {stderr.strip()}") from exc
+ if result.returncode != 0:
+ raise DistributionError(f"git clone failed: {(result.stderr or '').strip()}")
def _stage_source(source: str, workdir: Path) -> Tuple[Path, str]:
diff --git a/tests/hermes_cli/test_plugin_private_repo_auth.py b/tests/hermes_cli/test_plugin_private_repo_auth.py
index 4eb220e01c4..4525c5782b8 100644
--- a/tests/hermes_cli/test_plugin_private_repo_auth.py
+++ b/tests/hermes_cli/test_plugin_private_repo_auth.py
@@ -118,37 +118,62 @@ def test_public_clone_attempts_anonymously_when_credential_resolves(tmp_path, mo
assert "ghp_fake" not in str(clone_calls)
-def test_non_https_clone_skips_auth_header_even_when_credential_resolves(tmp_path, monkeypatch):
- """SSH-style ``[email protected]:owner/repo.git`` URLs reach git via the local ssh agent, not via
- the https Authorization extraheader — the credential path must be a true no-op for them."""
- clone_calls: list[list[str]] = []
[email protected]("verb", ["fetch", "pull"])
[email protected]("refused", [False, True])
+def test_ref_fetch_and_update_pull_attach_credential_only_after_anonymous_refusal(
+ tmp_path, monkeypatch, verb, refused):
+ """The pinned-ref fetch (``--ref`` install) and ``hermes plugins update``'s pull are the
+ clone's siblings: with a stored GitHub credential resolvable they still run anonymously
+ against a public remote, and attach the credential only after the remote refuses."""
+ _seed_bare_upstream(tmp_path)
+ repo = tmp_path / "checkout"
+ subprocess.run(["git", "clone", "-q", str(tmp_path / "upstream.git"), str(repo)], check=True)
+ revision = subprocess.run(["git", "-C", str(repo), "rev-parse", "HEAD"], capture_output=True,
+ text=True, check=True).stdout.strip()
+ public_url = "https://github.com/acme/public-plugin.git"
+ subprocess.run(["git", "-C", str(repo), "remote", "set-url", "origin", public_url], check=True)
+
+ attempts: list[list[str]] = []
real_run = subprocess.run
- target_url = "[email protected]:robbyczgw-cla/hermes-web-search-plus.git"
def spy_run(argv, *a, **kw):
- env = kw.get("env") or {}
- if "clone" in argv:
- clone_calls.append(_auth_headers_for(env, "github.com"))
- # Skip the real clone; the SSH path isn't under test here.
- return subprocess.CompletedProcess(argv, returncode=0, stdout="", stderr="")
- # Subsequent post-clone git calls (rev-parse, etc.) aren't under test; swallow them so
- # the absence of a real upstream doesn't cascade into a fixture error.
- if isinstance(argv, (list, tuple)) and argv and argv[0].endswith("git") and len(argv) > 1:
- return subprocess.CompletedProcess(argv, returncode=0, stdout="deadbeef\n", stderr="")
- return real_run(argv, *a, **kw)
+ if verb not in argv:
+ return real_run(argv, *a, **kw)
+ attempts.append(_auth_headers_for(kw.get("env") or {}, "https://github.com"))
+ if refused and len(attempts) == 1:
+ return subprocess.CompletedProcess(
+ argv, 128, stdout="",
+ stderr="fatal: could not read Username for 'https://github.com': terminal prompts disabled\n")
+ return subprocess.CompletedProcess(argv, 0, stdout="Already up to date.\n", stderr="")
monkeypatch.setattr(plugins_cmd.subprocess, "run", spy_run)
monkeypatch.setattr(git_credentials, "resolve_git_basic_auth", lambda url: ("x-access-token", "ghp_fake"))
- dest = tmp_path / "clone"
- plugins_cmd._clone_plugin_repo(dest, target_url, None)
+ if verb == "fetch":
+ plugins_cmd._checkout_exact_revision(repo, "git", revision, source_url=public_url)
+ else:
+ assert plugins_cmd._git_pull_plugin_dir(repo)[0] is True
- assert len(clone_calls) == 1, (
- f"non-HTTPS clone must be a single anonymous attempt, got {len(clone_calls)}: {clone_calls}"
- )
- assert clone_calls[0] == [], (
- f"non-HTTPS URL must not receive an Authorization extraheader, got {clone_calls[0]}"
- )
+ expected = base64.b64encode(b"x-access-token:ghp_fake").decode()
+ assert attempts == ([[], [f"Authorization: basic {expected}"]] if refused else [[]])
+
+
+def test_non_credential_failure_is_returned_without_an_authenticated_retry(monkeypatch):
+ """A failure that is not about credentials (missing repo, bad commit, network) must surface
+ as-is: the stored credential is never even resolved, let alone sent."""
+ calls: list = []
+ monkeypatch.setattr(git_credentials.subprocess, "run", lambda argv, **kw: (
+ calls.append(kw["env"]) or subprocess.CompletedProcess(
+ argv, 128, stdout="", stderr="fatal: repository 'https://github.com/acme/nope.git/' not found\n")))
+ monkeypatch.setattr(git_credentials, "resolve_git_basic_auth",
+ lambda url: pytest.fail("credential must not be resolved for a non-credential failure"))
+
+ result = git_credentials.run_git_with_credential_fallback(
+ ["git", "clone", "https://github.com/acme/nope.git"], "https://github.com/acme/nope.git",
+ env=noninteractive_git_env(), capture_output=True, text=True)
+
+ assert result.returncode == 128 and len(calls) == 1
+ assert _auth_headers_for(calls[0], "https://github.com") == []
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell stub credential helper")
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index a807e96b42c..a2410c69774 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -203,7 +203,11 @@ repositories too, through the same stored credentials described below.
`hermes plugins install` clones non-interactively (it never prompts for a
username or password), so a private repo needs a credential Hermes can find on
-its own. For an `https://` source it tries, in order:
+its own. Every clone, pinned `--ref` fetch and `hermes plugins update` pull is
+attempted anonymously first — public repos never see your credential, so a
+stale or revoked token cannot break a public install. Only when the remote
+refuses anonymous access does Hermes look for a credential. For an `https://`
+source it tries, in order:
1. `GITHUB_TOKEN` or `GH_TOKEN` from your `.env` (GitHub hosts only).
2. The `gh` CLI's login (`gh auth login`), GitHub hosts only.