github_api.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. """Credentials and failure copy for the update check's api.github.com calls.
  2. The passive source check asks the REST API for a branch tip. Unauthenticated
  3. that budget is 60 requests/hour keyed on the *client IP*, so a shared exit
  4. (office NAT, VPN, proxy) exhausts it for everyone behind it and the check
  5. reports a 403 that read as "Hermes can't reach the update server".
  6. Authenticating moves the caller onto the token's 5,000/hour budget.
  7. Credential ladder: GITHUB_TOKEN, then GH_TOKEN, then ``gh auth token`` (the
  8. gh CLI's own login — the only rung most desktop users have, since a
  9. GUI-launched app inherits a minimal environment; its answer is cached per
  10. process so the check never spawns gh more than once), then anonymous. A
  11. token GitHub rejects (401) drops that request to anonymous. The token itself
  12. never reaches a log line or an error string.
  13. """
  14. from __future__ import annotations
  15. import logging
  16. import os
  17. import subprocess
  18. import time
  19. import urllib.error
  20. from typing import Optional
  21. logger = logging.getLogger(__name__)
  22. GITHUB_TOKEN_ENV_VARS = ("GITHUB_TOKEN", "GH_TOKEN")
  23. _GH_CLI_TIMEOUT_SECONDS = 3
  24. _gh_cli_cache: Optional[str] = None
  25. _gh_cli_probed = False
  26. def github_token_from_env(env=os.environ) -> Optional[str]:
  27. """First non-blank env token, trimmed. A blank value falls through to the next."""
  28. for name in GITHUB_TOKEN_ENV_VARS:
  29. value = (env.get(name) or "").strip()
  30. if value:
  31. return value
  32. return None
  33. def _gh_cli_token() -> Optional[str]:
  34. global _gh_cli_cache, _gh_cli_probed
  35. if _gh_cli_probed:
  36. return _gh_cli_cache
  37. _gh_cli_probed = True
  38. from hermes_cli._subprocess_compat import windows_hide_flags
  39. try:
  40. result = subprocess.run(
  41. ["gh", "auth", "token"], capture_output=True, text=True, encoding="utf-8", errors="replace",
  42. timeout=_GH_CLI_TIMEOUT_SECONDS, stdin=subprocess.DEVNULL, creationflags=windows_hide_flags(),
  43. check=False,
  44. )
  45. except (OSError, subprocess.SubprocessError) as exc:
  46. logger.debug("gh CLI token lookup unavailable: %s", exc)
  47. return None
  48. token = result.stdout.strip() if result.returncode == 0 else ""
  49. _gh_cli_cache = token or None
  50. return _gh_cli_cache
  51. def github_token() -> Optional[str]:
  52. """The credential for this request, or None for anonymous."""
  53. return github_token_from_env() or _gh_cli_token()
  54. def describe_github_failure(exc: BaseException, authenticated: bool, now: Optional[float] = None) -> str:
  55. """One line a user can act on instead of a generic "could not resolve" (#105855).
  56. A 403/429 with ``x-ratelimit-remaining: 0`` is the anonymous per-IP budget spent
  57. by every client behind one exit — the line names the fix the user actually has
  58. (a GITHUB_TOKEN) and the real reset time. Any other status is reported as what it is.
  59. """
  60. if isinstance(exc, urllib.error.HTTPError):
  61. status = exc.code
  62. headers = exc.headers or {}
  63. remaining = _header_int(headers, "x-ratelimit-remaining")
  64. if status in (403, 429) and remaining == 0:
  65. reset = _header_int(headers, "x-ratelimit-reset")
  66. when = "within an hour"
  67. if reset is not None:
  68. minutes = int((reset - (time.time() if now is None else now) + 59) // 60)
  69. if minutes >= 1:
  70. when = "in about a minute" if minutes == 1 else f"in about {minutes} minutes"
  71. if authenticated:
  72. return f"GitHub API rate limit reached for your GITHUB_TOKEN (HTTP {status}) — it resets {when}."
  73. return (f"GitHub API rate limit reached (HTTP {status}): anonymous requests are limited to 60 per hour "
  74. f"per network address, shared with everyone behind the same connection. It resets {when}; "
  75. "setting GITHUB_TOKEN in the environment lifts the limit.")
  76. if status >= 500:
  77. return (f"GitHub is having trouble (HTTP {status} from api.github.com) — check githubstatus.com "
  78. "and try again later.")
  79. return f"api.github.com answered HTTP {status}."
  80. if isinstance(exc, urllib.error.URLError):
  81. reason = exc.reason
  82. if isinstance(reason, TimeoutError) or "timed out" in str(reason).lower():
  83. return "api.github.com did not answer within 10 seconds."
  84. return f"Connection to api.github.com failed ({reason}) — check your connection, firewall or proxy."
  85. if isinstance(exc, TimeoutError):
  86. return "api.github.com did not answer within 10 seconds."
  87. return f"api.github.com: {exc}"
  88. def _header_int(headers, name: str) -> Optional[int]:
  89. try:
  90. return int(str(headers.get(name, "")).strip())
  91. except (TypeError, ValueError):
  92. return None