Skip to content

The agent that grows with you

fix(update-check): authenticate api.github.com calls and name the branch-tip failure

ethernet6ba45b300c0a
diff --git a/apps/desktop/electron/github-api-auth.test.ts b/apps/desktop/electron/github-api-auth.test.ts
deleted file mode 100644
index ffc67e2c2a4..00000000000
--- a/apps/desktop/electron/github-api-auth.test.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-import assert from 'node:assert/strict'
-
-import { beforeEach, test } from 'vitest'
-
-import {
- describeGitHubCredentialSource,
- findGhCli,
- forgetGhCliToken,
- GH_CLI_TIMEOUT_MS,
- githubApiHeaders,
- githubTokenFromEnv,
- githubTokenRejected,
- resolveGitHubCredential
-} from './github-api-auth'
-
-// The exact headers the anonymous update check sends today; the change must
-// leave this shape byte-identical when no token is configured.
-const UPDATE_CHECK_HEADERS = {
- Accept: 'application/vnd.github.sha',
- 'User-Agent': 'hermes-desktop-update-check'
-}
-
-beforeEach(() => {
- forgetGhCliToken()
-})
-
-/** execFile stand-in that records every spawn and answers with a scripted result. */
-function fakeExecFile(result: { error?: Error | null; stdout?: string }) {
- const calls: Array<{ file: string; args: string[]; options: Record<string, unknown> }> = []
- let stdinEnded = 0
-
- const execFileFn = ((file, args, options, callback) => {
- calls.push({ file, args, options })
- queueMicrotask(() => callback(result.error ?? null, result.stdout ?? '', ''))
-
- return {
- stdin: {
- end() {
- stdinEnded += 1
- }
- }
- }
- }) as any
-
- return { calls, execFileFn, stdinEnded: () => stdinEnded }
-}
-
-test('GITHUB_TOKEN wins over GH_TOKEN, blanks fall through, values are trimmed', () => {
- assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: 'pat-a', GH_TOKEN: 'pat-b' }), 'pat-a')
- assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: ' ', GH_TOKEN: ' pat-b ' }), 'pat-b')
- assert.equal(githubTokenFromEnv({ GITHUB_TOKEN: '', GH_TOKEN: '' }), null)
- assert.equal(githubTokenFromEnv({}), null)
-})
-
-test('anonymous sends no Authorization key at all; a token adds the `token` scheme without touching the base', () => {
- const anonymous = githubApiHeaders(UPDATE_CHECK_HEADERS, null)
-
- assert.deepEqual(anonymous, UPDATE_CHECK_HEADERS)
- assert.equal('Authorization' in anonymous, false)
-
- const authed = githubApiHeaders(UPDATE_CHECK_HEADERS, 'pat-a')
-
- assert.equal(authed.Authorization, 'token pat-a')
- assert.equal(authed['User-Agent'], 'hermes-desktop-update-check')
- // The caller's base object is a constant; mutating it would leak the token
- // into every later request that builds from it.
- assert.equal('Authorization' in UPDATE_CHECK_HEADERS, false)
-})
-
-test('only an authenticated 401 counts as the credential being rejected', () => {
- // The anonymous-retry gate: a stale GITHUB_TOKEN or gh login must fall back
- // to the anonymous request that worked before credentials were wired in.
- assert.equal(githubTokenRejected({ statusCode: 401, authenticated: true }), true)
- assert.equal(githubTokenRejected({ statusCode: 401, authenticated: false }), false)
- assert.equal(githubTokenRejected({ statusCode: 403, authenticated: true }), false)
- assert.equal(githubTokenRejected({ statusCode: 429, authenticated: true }), false)
- assert.equal(githubTokenRejected(null), false)
-})
-
-// #112615: a Finder/launcher-started app inherits /usr/bin:/bin:/usr/sbin:/sbin,
-// so `gh` from Homebrew (macOS) or the GitHub CLI installer (Windows) is
-// invisible on PATH — the rung must look where those installers put it.
-test('gh is found in the GUI-safe install locations a minimal launch PATH omits', () => {
- const brewGh = '/opt/homebrew/bin/gh'
- const macos = findGhCli({ PATH: '/usr/bin:/bin:/usr/sbin:/sbin' }, 'darwin', p => p === brewGh)
-
- assert.equal(macos, brewGh)
-
- const winGh = 'C:\\Program Files\\GitHub CLI\\gh.exe'
-
- const windows = findGhCli(
- { Path: 'C:\\Windows\\System32', ProgramFiles: 'C:\\Program Files' },
- 'win32',
- p => p === winGh
- )
-
- assert.equal(windows, winGh)
-
- // PATH still wins over the fallbacks when both have one.
- const pathGh = '/usr/local/bin/gh'
- const both = findGhCli({ PATH: '/usr/local/bin' }, 'darwin', p => p === pathGh || p === brewGh)
-
- assert.equal(both, pathGh)
- assert.equal(
- findGhCli({ PATH: '/usr/bin' }, 'linux', () => false),
- null
- )
-})
-
-test('gh rung: argv-only spawn, stdin closed, bounded, cached for the process, and after the env rung', async () => {
- const exists = (p: string) => p === '/opt/homebrew/bin/gh'
- const env = { PATH: '/usr/bin:/bin' }
- const logged = fakeExecFile({ stdout: 'gho_from_gh\n' })
-
- const first = await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: logged.execFileFn })
-
- assert.deepEqual(first, { token: 'gho_from_gh', source: 'gh-cli' })
- assert.equal(logged.calls.length, 1)
- assert.equal(logged.calls[0].file, '/opt/homebrew/bin/gh')
- assert.deepEqual(logged.calls[0].args, ['auth', 'token'])
- assert.equal(logged.calls[0].options.shell, undefined)
- assert.equal(logged.calls[0].options.windowsHide, true)
- assert.equal(logged.calls[0].options.timeout, GH_CLI_TIMEOUT_MS)
- assert.equal(logged.stdinEnded(), 1)
-
- // Process-lifetime cache: the second check does not spawn gh again.
- await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: logged.execFileFn })
- assert.equal(logged.calls.length, 1)
-
- // Env token outranks gh and never spawns it.
- forgetGhCliToken()
-
- const fromEnv = await resolveGitHubCredential({
- env: { ...env, GH_TOKEN: 'pat-env' },
- platform: 'darwin',
- exists,
- execFileFn: logged.execFileFn
- })
-
- assert.deepEqual(fromEnv, { token: 'pat-env', source: 'env' })
- assert.equal(logged.calls.length, 1)
-
- // Logged-out gh (exit 1, empty stdout) and a missing gh both mean anonymous.
- forgetGhCliToken()
- const loggedOut = fakeExecFile({ error: Object.assign(new Error('exit 1'), { code: 1 }), stdout: '' })
-
- assert.equal(
- await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: loggedOut.execFileFn }),
- null
- )
-
- // "none" is not cached: a `gh auth login` after launch is picked up by the next check without a restart.
- const nowLogged = fakeExecFile({ stdout: 'gho_after_login\n' })
-
- assert.deepEqual(
- await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: nowLogged.execFileFn }),
- {
- token: 'gho_after_login',
- source: 'gh-cli'
- }
- )
-
- forgetGhCliToken()
- assert.equal(
- await resolveGitHubCredential({ env, platform: 'darwin', exists: () => false, execFileFn: logged.execFileFn }),
- null
- )
- assert.equal(logged.calls.length, 1)
-})
-
-test('the rejected-credential log line names the source, never the token', () => {
- assert.match(describeGitHubCredentialSource('env'), /GITHUB_TOKEN \/ GH_TOKEN/)
- assert.match(describeGitHubCredentialSource('gh-cli'), /gh auth token/)
-})
diff --git a/apps/desktop/electron/github-api-auth.ts b/apps/desktop/electron/github-api-auth.ts
deleted file mode 100644
index 09884e605df..00000000000
--- a/apps/desktop/electron/github-api-auth.ts
+++ /dev/null
@@ -1,220 +0,0 @@
-import { execFile as nodeExecFile } from 'node:child_process'
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { delimiterForPlatform, pathEnvKey, POSIX_SANE_PATH_ENTRIES } from './backend-env'
-
-// Credentials for the self-update check's api.github.com calls.
-//
-// The passive check asks the REST API for the branch tip SHA. Unauthenticated
-// that budget is 60 requests/hour keyed on the *client IP*, so a shared exit —
-// office NAT, VPN, a proxy node many users sit behind — exhausts the bucket for
-// everyone on it and the check reports a rate limit that reads as "Hermes can't
-// reach the update server". Authenticating moves the caller onto the token's
-// 5,000/hour budget.
-//
-// Credential ladder, mirroring the Python client (tools/skills_hub_github.py::GitHubAuth):
-// 1. GITHUB_TOKEN, then GH_TOKEN, read from the process env per request and never stored.
-// 2. `gh auth token` — the gh CLI's own login. A GUI-launched app inherits a
-// minimal environment, so this is the only rung that helps most desktop
-// users; the answer (token or "none") is cached for the process lifetime
-// so the check never spawns gh more than once.
-// 3. Anonymous.
-// A token GitHub rejects (401) drops the caller back to rung 3 for that request;
-// the token itself never reaches a log line or an error string.
-
-/** Env vars consulted, in precedence order. */
-export const GITHUB_TOKEN_ENV_VARS = ['GITHUB_TOKEN', 'GH_TOKEN'] as const
-
-/** `gh auth token` must answer within this; a wedged keyring prompt must not stall the check. */
-export const GH_CLI_TIMEOUT_MS = 3000
-
-export type GitHubTokenSource = 'env' | 'gh-cli'
-
-export interface GitHubCredential {
- token: string
- source: GitHubTokenSource
-}
-
-type Env = Record<string, string | undefined>
-
-interface GhCliOptions {
- env?: Env
- platform?: NodeJS.Platform
- execFileFn?: typeof nodeExecFile
- exists?: (filePath: string) => boolean
- timeoutMs?: number
-}
-
-/** First non-blank env token, trimmed. A blank value falls through to the next. */
-export function githubTokenFromEnv(env: Env = {}): string | null {
- for (const name of GITHUB_TOKEN_ENV_VARS) {
- const value = env[name]
-
- if (typeof value === 'string' && value.trim()) {
- return value.trim()
- }
- }
-
- return null
-}
-
-/**
- * Directories searched for the gh CLI: PATH first, then the install locations
- * a GUI launch's minimal PATH omits — the same sane POSIX entries backend-env
- * appends for the backend, plus the GitHub CLI installer's Windows targets.
- */
-export function ghCliSearchDirs(env: Env = process.env, platform: NodeJS.Platform = process.platform): string[] {
- const dirs = String(env[pathEnvKey(env, platform)] || '')
- .split(delimiterForPlatform(platform))
- .filter(Boolean)
-
- if (platform === 'win32') {
- const programFiles = env.ProgramFiles || 'C:\\Program Files'
- const localAppData = env.LOCALAPPDATA
-
- dirs.push(path.win32.join(programFiles, 'GitHub CLI'))
-
- if (localAppData) {
- dirs.push(path.win32.join(localAppData, 'Programs', 'GitHub CLI'))
- }
- } else {
- dirs.push(...POSIX_SANE_PATH_ENTRIES, '/home/linuxbrew/.linuxbrew/bin')
-
- if (env.HOME) {
- dirs.push(path.posix.join(env.HOME, '.local', 'bin'), path.posix.join(env.HOME, '.nix-profile', 'bin'))
- }
- }
-
- return [...new Set(dirs)]
-}
-
-/** Absolute path of the gh CLI, or null when no candidate directory has one. */
-export function findGhCli(
- env: Env = process.env,
- platform: NodeJS.Platform = process.platform,
- exists: (filePath: string) => boolean = fs.existsSync
-): string | null {
- const pathModule = platform === 'win32' ? path.win32 : path.posix
- const executable = platform === 'win32' ? 'gh.exe' : 'gh'
-
- for (const dir of ghCliSearchDirs(env, platform)) {
- const candidate = pathModule.join(dir, executable)
-
- if (exists(candidate)) {
- return candidate
- }
- }
-
- return null
-}
-
-/**
- * Run `gh auth token` once. argv only (no shell), stdin closed immediately,
- * bounded by GH_CLI_TIMEOUT_MS. Missing gh, a logged-out gh (exit 1), a
- * timeout, or a spawn failure all resolve to null — the caller goes anonymous.
- */
-export function readGhCliToken({
- env = process.env,
- platform = process.platform,
- execFileFn = nodeExecFile,
- exists = fs.existsSync,
- timeoutMs = GH_CLI_TIMEOUT_MS
-}: GhCliOptions = {}): Promise<string | null> {
- const gh = findGhCli(env, platform, exists)
-
- if (!gh) {
- return Promise.resolve(null)
- }
-
- return new Promise(resolve => {
- try {
- const child = execFileFn(
- gh,
- ['auth', 'token'],
- { encoding: 'utf8', timeout: timeoutMs, windowsHide: true, env: env as NodeJS.ProcessEnv },
- (error, stdout) => {
- const token = typeof stdout === 'string' ? stdout.trim() : ''
-
- resolve(!error && token ? token : null)
- }
- )
-
- // gh may prompt on a TTY-less stdin when its keyring is locked; never wait on it.
- child?.stdin?.end?.()
- } catch {
- resolve(null)
- }
- })
-}
-
-let ghCliTokenPromise: Promise<string | null> | null = null
-
-/**
- * `gh auth token`, cached for the process once it answers with a token. A "none" answer (gh missing,
- * logged out, hung) is not cached: a `gh auth login` after launch is honoured by the next check, and
- * the check is passive and hourly, so re-asking costs one bounded spawn per check at most.
- */
-export function githubTokenFromGhCli(options: GhCliOptions = {}): Promise<string | null> {
- ghCliTokenPromise ??= readGhCliToken(options).then(token => {
- if (token === null) {
- ghCliTokenPromise = null
- }
-
- return token
- })
-
- return ghCliTokenPromise
-}
-
-/** Drop the cached gh answer so the next request asks gh again (rejected token, tests). */
-export function forgetGhCliToken(): void {
- ghCliTokenPromise = null
-}
-
-/** Walk the ladder: env token, then the cached gh CLI login, else null (anonymous). */
-export async function resolveGitHubCredential(options: GhCliOptions = {}): Promise<GitHubCredential | null> {
- const env = options.env ?? process.env
- const fromEnv = githubTokenFromEnv(env)
-
- if (fromEnv) {
- return { token: fromEnv, source: 'env' }
- }
-
- const fromGh = await githubTokenFromGhCli({ ...options, env })
-
- return fromGh ? { token: fromGh, source: 'gh-cli' } : null
-}
-
-/**
- * Headers for api.github.com. The `token` scheme (not `Bearer`) matches the
- * Python client. Anonymous callers get the base headers untouched: an empty
- * `Authorization` header is a 401, so it must be absent, not blank.
- */
-export function githubApiHeaders(base: Record<string, string>, token?: string | null): Record<string, string> {
- const headers = { ...base }
-
- if (token) {
- headers.Authorization = `token ${token}`
- }
-
- return headers
-}
-
-/**
- * True when api.github.com rejected the credential itself (HTTP 401 on an
- * authenticated call). A stale or revoked token must not fail the update
- * check closed — the caller retries anonymously, which is exactly what worked
- * before credentials were wired in. Anonymous 401s and every other status are
- * not the token's fault and are surfaced as-is.
- */
-export function githubTokenRejected(
- error: { statusCode?: number; authenticated?: boolean } | null | undefined
-): boolean {
- return error?.statusCode === 401 && error?.authenticated === true
-}
-
-/** Log-safe name of a rejected credential's source; never includes the token. */
-export function describeGitHubCredentialSource(source: GitHubTokenSource): string {
- return source === 'env' ? 'the GITHUB_TOKEN / GH_TOKEN from the environment' : 'the gh CLI login (`gh auth token`)'
-}
diff --git a/hermes_cli/github_api.py b/hermes_cli/github_api.py
new file mode 100644
index 00000000000..cd38ef6f84a
--- /dev/null
+++ b/hermes_cli/github_api.py
@@ -0,0 +1,107 @@
+"""Credentials and failure copy for the update check's api.github.com calls.
+
+The passive source check asks the REST API for a branch tip. Unauthenticated
+that budget is 60 requests/hour keyed on the *client IP*, so a shared exit
+(office NAT, VPN, proxy) exhausts it for everyone behind it and the check
+reports a 403 that read as "Hermes can't reach the update server".
+Authenticating moves the caller onto the token's 5,000/hour budget.
+
+Credential ladder: GITHUB_TOKEN, then GH_TOKEN, then ``gh auth token`` (the
+gh CLI's own login — the only rung most desktop users have, since a
+GUI-launched app inherits a minimal environment; its answer is cached per
+process so the check never spawns gh more than once), then anonymous. A
+token GitHub rejects (401) drops that request to anonymous. The token itself
+never reaches a log line or an error string.
+"""
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import time
+import urllib.error
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+GITHUB_TOKEN_ENV_VARS = ("GITHUB_TOKEN", "GH_TOKEN")
+_GH_CLI_TIMEOUT_SECONDS = 3
+_gh_cli_cache: Optional[str] = None
+_gh_cli_probed = False
+
+
+def github_token_from_env(env=os.environ) -> Optional[str]:
+ """First non-blank env token, trimmed. A blank value falls through to the next."""
+ for name in GITHUB_TOKEN_ENV_VARS:
+ value = (env.get(name) or "").strip()
+ if value:
+ return value
+ return None
+
+
+def _gh_cli_token() -> Optional[str]:
+ global _gh_cli_cache, _gh_cli_probed
+ if _gh_cli_probed:
+ return _gh_cli_cache
+ _gh_cli_probed = True
+ from hermes_cli._subprocess_compat import windows_hide_flags
+ try:
+ result = subprocess.run(
+ ["gh", "auth", "token"], capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=_GH_CLI_TIMEOUT_SECONDS, stdin=subprocess.DEVNULL, creationflags=windows_hide_flags(),
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ logger.debug("gh CLI token lookup unavailable: %s", exc)
+ return None
+ token = result.stdout.strip() if result.returncode == 0 else ""
+ _gh_cli_cache = token or None
+ return _gh_cli_cache
+
+
+def github_token() -> Optional[str]:
+ """The credential for this request, or None for anonymous."""
+ return github_token_from_env() or _gh_cli_token()
+
+
+def describe_github_failure(exc: BaseException, authenticated: bool, now: Optional[float] = None) -> str:
+ """One line a user can act on instead of a generic "could not resolve" (#105855).
+
+ A 403/429 with ``x-ratelimit-remaining: 0`` is the anonymous per-IP budget spent
+ by every client behind one exit — the line names the fix the user actually has
+ (a GITHUB_TOKEN) and the real reset time. Any other status is reported as what it is.
+ """
+ if isinstance(exc, urllib.error.HTTPError):
+ status = exc.code
+ headers = exc.headers or {}
+ remaining = _header_int(headers, "x-ratelimit-remaining")
+ if status in (403, 429) and remaining == 0:
+ reset = _header_int(headers, "x-ratelimit-reset")
+ when = "within an hour"
+ if reset is not None:
+ minutes = int((reset - (time.time() if now is None else now) + 59) // 60)
+ if minutes >= 1:
+ when = "in about a minute" if minutes == 1 else f"in about {minutes} minutes"
+ if authenticated:
+ return f"GitHub API rate limit reached for your GITHUB_TOKEN (HTTP {status}) — it resets {when}."
+ return (f"GitHub API rate limit reached (HTTP {status}): anonymous requests are limited to 60 per hour "
+ f"per network address, shared with everyone behind the same connection. It resets {when}; "
+ "setting GITHUB_TOKEN in the environment lifts the limit.")
+ if status >= 500:
+ return (f"GitHub is having trouble (HTTP {status} from api.github.com) — check githubstatus.com "
+ "and try again later.")
+ return f"api.github.com answered HTTP {status}."
+ if isinstance(exc, urllib.error.URLError):
+ reason = exc.reason
+ if isinstance(reason, TimeoutError) or "timed out" in str(reason).lower():
+ return "api.github.com did not answer within 10 seconds."
+ return f"Connection to api.github.com failed ({reason}) — check your connection, firewall or proxy."
+ if isinstance(exc, TimeoutError):
+ return "api.github.com did not answer within 10 seconds."
+ return f"api.github.com: {exc}"
+
+
+def _header_int(headers, name: str) -> Optional[int]:
+ try:
+ return int(str(headers.get(name, "")).strip())
+ except (TypeError, ValueError):
+ return None
diff --git a/hermes_cli/source_check.py b/hermes_cli/source_check.py
index 238d1b999a1..92456f6954f 100644
--- a/hermes_cli/source_check.py
+++ b/hermes_cli/source_check.py
@@ -12,6 +12,7 @@ import time
from pathlib import Path
from typing import Optional
from urllib.parse import quote
+import urllib.error
import urllib.request
from hermes_constants import get_hermes_home
@@ -100,28 +101,65 @@ def _github_compare_behind(current_rev: str, target_rev: str, repository: str =
def _request(url: str, accept: str = "application/vnd.github+json") -> str:
- req = urllib.request.Request(url, headers={"Accept": accept, "User-Agent": "hermes-update-check"})
+ """GET an api.github.com resource with the credential ladder in hermes_cli.github_api.
+
+ A token GitHub rejects (401) drops this request to anonymous rather than
+ failing the check on a stale credential.
+ """
+ from hermes_cli.github_api import github_token
+
+ token = github_token()
+ try:
+ return _request_with(url, accept, token)
+ except urllib.error.HTTPError as exc:
+ if token is None or exc.code != 401:
+ raise
+ logger.debug("GitHub rejected the configured token; retrying anonymously")
+ return _request_with(url, accept, None)
+
+
+def _request_with(url: str, accept: str, token: str | None) -> str:
+ headers = {"Accept": accept, "User-Agent": "hermes-update-check"}
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=10) as response:
return response.read(2 * 1024 * 1024).decode("utf-8-sig").strip()
-def _branch_tip(repository: str | None, branch: str, root: Path, git: str, remote: str = "origin") -> tuple[str | None, bool]:
+def _branch_tip(repository: str | None, branch: str, root: Path, git: str,
+ remote: str = "origin") -> tuple[str | None, bool, str | None]:
+ """``(sha, missing, failure)``: ``missing`` only on a confirmed empty advertisement;
+ ``failure`` names why no tip could be read, for the user-facing message."""
# A successful empty ref advertisement alone proves a branch was deleted.
# GitHub 404 can also mean a private repository: it must not heal a branch.
+ failure = None
if repository:
- sha = _quiet(lambda: _request(
- f"https://api.github.com/repos/{repository}/commits/{quote(branch, safe='')}",
- "application/vnd.github.sha"))
+ from hermes_cli.github_api import describe_github_failure, github_token
+ try:
+ sha = _request(f"https://api.github.com/repos/{repository}/commits/{quote(branch, safe='')}",
+ "application/vnd.github.sha")
+ except Exception as exc:
+ sha = None
+ failure = describe_github_failure(exc, authenticated=github_token() is not None)
if _is_full_sha(sha):
- return sha, False
+ return sha, False, None
+ if failure is None:
+ failure = "api.github.com returned no commit for the branch."
if branch == "main" and remote == "origin":
- return None, False
+ return None, False, failure
result = _git_run(["ls-remote", "--exit-code", "--heads", remote, f"refs/heads/{branch}"],
cwd=root, git=git, timeout=10)
if result is None:
- return None, False
+ return None, False, failure or f"`git ls-remote {remote}` could not run."
sha = result.stdout.split()[0] if result.returncode == 0 and result.stdout else None
- return (sha if _is_full_sha(sha) else None), result.returncode == 2
+ if _is_full_sha(sha):
+ return sha, False, None
+ if result.returncode == 2:
+ return None, True, None
+ detail = (result.stderr or "").strip().splitlines()
+ return None, False, failure or (f"`git ls-remote {remote}` failed: {detail[-1]}" if detail
+ else f"`git ls-remote {remote}` returned no tip.")
def _commits(payload: dict | None) -> list[dict]:
@@ -235,7 +273,7 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = N
# Forks must keep their own origin, including its authentication.
remote = (f"https://github.com/{OFFICIAL_REPOSITORY}.git"
if embedded or (official_ssh and selected_branch != "main") else "origin")
- target, missing = _branch_tip(repository, selected_branch, root, git, remote)
+ target, missing, failure = _branch_tip(repository, selected_branch, root, git, remote)
if missing and selected_branch != "main":
result["branch"] = "main"
if branch_config_path and not branch and configured_branch == selected_branch:
@@ -244,9 +282,11 @@ def check_for_updates(*, install_root: Path | None = None, home: Path | None = N
if current_config == desktop_config:
from utils import atomic_json_write
atomic_json_write(branch_config_path, {**desktop_config, "branch": "main"})
- target, _ = _branch_tip(repository, "main", root, git, remote if embedded else "origin")
+ target, _, failure = _branch_tip(repository, "main", root, git, remote if embedded else "origin")
if target is None:
- result.update(error="fetch-failed", message="Could not resolve the remote branch tip.")
+ result.update(error="fetch-failed",
+ message=f"Could not resolve the remote branch tip: {failure}" if failure
+ else "Could not resolve the remote branch tip.")
else:
behind = UPDATE_AVAILABLE_NO_COUNT
if head == target or (not embedded and _git_ok(
diff --git a/tests/hermes_cli/test_banner_git_state.py b/tests/hermes_cli/test_banner_git_state.py
index f4eec97ca99..163504e4ddd 100644
--- a/tests/hermes_cli/test_banner_git_state.py
+++ b/tests/hermes_cli/test_banner_git_state.py
@@ -96,7 +96,7 @@ def test_check_via_local_git_insteadof_rewrite_routes_to_ssh_fastpath(tmp_path,
return real_run(args, **kwargs)
monkeypatch.setattr(source_check.subprocess, "run", spy_run)
- monkeypatch.setattr(source_check, "_branch_tip", lambda *args: (head_sha, False))
+ monkeypatch.setattr(source_check, "_branch_tip", lambda *args: (head_sha, False, None))
behind = source_check.check_for_updates(install_root=repo_dir, branch="main").get("behind")
diff --git a/tests/hermes_cli/test_source_check.py b/tests/hermes_cli/test_source_check.py
index 33f57c0bd38..fc9be51ecf2 100644
--- a/tests/hermes_cli/test_source_check.py
+++ b/tests/hermes_cli/test_source_check.py
@@ -21,6 +21,12 @@ def source_channel(name, repository, branch="main"):
"delivery": {"kind": "source-branch", "branch": branch}}
+class Installation(tuple):
+ """The 8-tuple every test unpacks, plus the GitHub probe's request/response hooks."""
+ authorizations: list
+ response_headers: dict
+
+
@pytest.fixture
def installation(tmp_path, monkeypatch):
from hermes_cli import source_releases
@@ -52,14 +58,23 @@ def installation(tmp_path, monkeypatch):
responses = {MAIN_CHANNEL: (200, lambda: source_channel(
"main", source_releases.source_repository(["git"], root)))}
requests = []
+ # Authorization header of every api.github.com call, in request order (None when anonymous).
+ authorizations = []
+ # Optional extra response headers per path (rate-limit headers for the failure-copy tests).
+ response_headers = {}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
requests.append(self.path)
- code, body = responses.get(self.path, (404, {}))
+ authorizations.append(self.headers.get("Authorization"))
+ entry = responses.get(self.path, (404, {}))
+ # A callable entry decides per request (it sees the handler, hence the headers).
+ code, body = entry(self) if callable(entry) else entry
if callable(body):
body = body()
self.send_response(code)
+ for name, value in response_headers.get(self.path, {}).items():
+ self.send_header(name, value)
self.end_headers()
self.wfile.write((body if isinstance(body, str) else json.dumps(body)).encode())
@@ -75,10 +90,21 @@ def installation(tmp_path, monkeypatch):
def local(request, *args, **kwargs):
url = urlsplit(request.full_url)
assert url.hostname in {"api.github.com", "hermes-assets.nousresearch.com"}
- return original(f"http://127.0.0.1:{server.server_port}{url.path}" + (f"?{url.query}" if url.query else ""), *args, **kwargs)
+ rewritten = urllib.request.Request(
+ f"http://127.0.0.1:{server.server_port}{url.path}" + (f"?{url.query}" if url.query else ""),
+ headers=dict(request.header_items()))
+ return original(rewritten, *args, **kwargs)
monkeypatch.setattr(urllib.request, "urlopen", local)
- yield root, linked, home, base, head, responses, requests, git
+ # The credential ladder must not read this machine's gh login or env.
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ monkeypatch.delenv("GH_TOKEN", raising=False)
+ from hermes_cli import github_api
+ monkeypatch.setattr(github_api, "_gh_cli_token", lambda: None)
+ fixture = Installation((root, linked, home, base, head, responses, requests, git))
+ fixture.authorizations = authorizations
+ fixture.response_headers = response_headers
+ yield fixture
server.shutdown()
server.server_close()
thread.join()
@@ -375,3 +401,41 @@ def test_official_ssh_healing_uses_public_https_without_retargeting_forks(instal
assert status["behind"] == 0
else:
assert status["error"] == "fetch-failed"
+
+
+def github_authorizations(installation, path):
+ """Authorization header of each api.github.com call to ``path``, in order."""
+ return [auth for seen, auth in zip(installation[6], installation.authorizations) if seen == path]
+
+
+def test_github_calls_carry_the_configured_token_and_retry_anonymously_on_401(installation, monkeypatch):
+ from hermes_cli.source_check import check_for_updates
+ root, linked, home, base, head, responses, requests, git = installation
+ url = "/repos/fixture/fork/commits/main"
+ responses[url] = (200, head)
+ monkeypatch.setenv("GITHUB_TOKEN", " ghp_fixture ")
+ assert check_for_updates(install_root=root, home=home)["behind"] == 0
+ assert github_authorizations(installation, url) == ["Bearer ghp_fixture"]
+
+ # A rejected token is not a failed check: the same request is retried without it.
+ responses[url] = lambda handler: (401, {}) if handler.headers.get("Authorization") else (200, head)
+ assert check_for_updates(install_root=root, home=home, force=True)["behind"] == 0
+ assert github_authorizations(installation, url)[-2:] == ["Bearer ghp_fixture", None]
+
+
+def test_branch_tip_failure_names_the_cause(installation):
+ from hermes_cli.source_check import check_for_updates
+ root, linked, home, base, head, responses, requests, git = installation
+ url = "/repos/fixture/fork/commits/main"
+ responses[url] = (403, {})
+ installation.response_headers[url] = {"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": "4102444800"}
+ status = check_for_updates(install_root=root, home=home)
+ assert status["error"] == "fetch-failed"
+ assert "rate limit" in status["message"] and "GITHUB_TOKEN" in status["message"]
+ assert github_authorizations(installation, url) == [None]
+
+ installation.response_headers.pop(url)
+ responses[url] = (503, {})
+ status = check_for_updates(install_root=root, home=home, force=True)
+ assert status["error"] == "fetch-failed"
+ assert "HTTP 503" in status["message"]