|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
| 5 | +import os |
| 6 | +import shutil |
| 7 | +import subprocess |
| 8 | +from typing import TYPE_CHECKING |
| 9 | +from urllib.error import URLError |
| 10 | + |
5 | 11 | from .base import AuthProvider |
6 | 12 |
|
| 13 | +if TYPE_CHECKING: |
| 14 | + from .config import AuthConfigEntry |
7 | 15 |
|
8 | | -class GitHubAuth(AuthProvider): |
9 | | - """GitHub authentication provider. |
10 | 16 |
|
11 | | - Supports the ``bearer`` auth scheme, used for PATs, fine-grained PATs, |
12 | | - OAuth tokens, and GitHub App installation tokens. |
13 | | - """ |
| 17 | +_GITHUB_CLI_TIMEOUT_SECONDS = 10 |
| 18 | + |
| 19 | + |
| 20 | +def _is_safe_cli_hostname(hostname: str) -> bool: |
| 21 | + """Return whether *hostname* is a shell-safe DNS hostname.""" |
| 22 | + if not hostname or len(hostname) > 253 or not hostname.isascii(): |
| 23 | + return False |
| 24 | + labels = hostname.split(".") |
| 25 | + return all( |
| 26 | + 0 < len(label) <= 63 |
| 27 | + and label[0].isalnum() |
| 28 | + and label[-1].isalnum() |
| 29 | + and all(char.isalnum() or char == "-" for char in label) |
| 30 | + for label in labels |
| 31 | + ) |
| 32 | + |
| 33 | + |
| 34 | +class GitHubCliAuthError(URLError): |
| 35 | + """Raised when GitHub CLI cannot provide a configured credential.""" |
| 36 | + |
| 37 | + |
| 38 | +class GitHubAuth(AuthProvider): |
| 39 | + """GitHub authentication provider.""" |
14 | 40 |
|
15 | 41 | key = "github" |
16 | | - supported_auth_schemes = ("bearer",) |
| 42 | + supported_auth_schemes = ("bearer", "github-cli") |
| 43 | + |
| 44 | + def __init__(self) -> None: |
| 45 | + self._github_cli_cache: dict[str, tuple[bool, str]] = {} |
17 | 46 |
|
18 | 47 | def auth_headers(self, token: str, auth_scheme: str) -> dict[str, str]: |
19 | | - """Return ``Authorization: Bearer <token>``.""" |
20 | | - if auth_scheme != "bearer": |
| 48 | + """Return a bearer authorization header.""" |
| 49 | + if auth_scheme not in self.supported_auth_schemes: |
21 | 50 | raise ValueError( |
22 | 51 | f"GitHubAuth does not support auth scheme {auth_scheme!r}" |
23 | 52 | ) |
24 | | - return {"Authorization": f"Bearer {token}"} |
| 53 | + return {"Authorization": "Bearer " + token} |
| 54 | + |
| 55 | + def resolve_token(self, entry: AuthConfigEntry) -> str | None: |
| 56 | + """Resolve a configured token or acquire one from GitHub CLI.""" |
| 57 | + if entry.auth != "github-cli": |
| 58 | + return super().resolve_token(entry) |
| 59 | + |
| 60 | + credential_host = self._credential_hostname(entry) |
| 61 | + cached = self._github_cli_cache.get(credential_host) |
| 62 | + if cached is not None: |
| 63 | + succeeded, value = cached |
| 64 | + if succeeded: |
| 65 | + return value |
| 66 | + raise GitHubCliAuthError(value) |
| 67 | + |
| 68 | + try: |
| 69 | + token = self._acquire_via_gh_cli(credential_host) |
| 70 | + except GitHubCliAuthError as exc: |
| 71 | + message = str(exc.reason) |
| 72 | + self._github_cli_cache[credential_host] = (False, message) |
| 73 | + raise GitHubCliAuthError(message) from None |
| 74 | + |
| 75 | + self._github_cli_cache[credential_host] = (True, token) |
| 76 | + return token |
| 77 | + |
| 78 | + @staticmethod |
| 79 | + def _credential_hostname(entry: AuthConfigEntry) -> str: |
| 80 | + """Use the first configured host for GitHub CLI credential acquisition.""" |
| 81 | + hostname = entry.hosts[0] |
| 82 | + if "*" in hostname: |
| 83 | + raise GitHubCliAuthError( |
| 84 | + "GitHub authentication failed for provider 'github': " |
| 85 | + "the first hostname in a github-cli entry must be an exact " |
| 86 | + "hostname, not a wildcard." |
| 87 | + ) |
| 88 | + return hostname |
| 89 | + |
| 90 | + @staticmethod |
| 91 | + def _acquire_via_gh_cli(hostname: str) -> str: |
| 92 | + """Run the fixed GitHub CLI token command for *hostname*.""" |
| 93 | + if not _is_safe_cli_hostname(hostname): |
| 94 | + raise GitHubCliAuthError( |
| 95 | + "GitHub authentication failed for provider 'github': " |
| 96 | + "the configured hostname is not valid for GitHub CLI authentication." |
| 97 | + ) |
| 98 | + |
| 99 | + resolved = shutil.which("gh") |
| 100 | + if not resolved or not os.path.isabs(resolved): |
| 101 | + raise GitHubCliAuthError( |
| 102 | + "GitHub authentication failed for provider 'github': " |
| 103 | + "GitHub CLI ('gh') was not found." |
| 104 | + ) |
| 105 | + |
| 106 | + try: |
| 107 | + result = subprocess.run( # noqa: S603 |
| 108 | + [resolved, "auth", "token", "--hostname", hostname], |
| 109 | + capture_output=True, |
| 110 | + text=True, |
| 111 | + timeout=_GITHUB_CLI_TIMEOUT_SECONDS, |
| 112 | + check=False, |
| 113 | + shell=False, |
| 114 | + ) |
| 115 | + except subprocess.TimeoutExpired: |
| 116 | + raise GitHubCliAuthError( |
| 117 | + "GitHub authentication failed for provider 'github': " |
| 118 | + f"GitHub CLI timed out while requesting a token for {hostname!r}." |
| 119 | + ) from None |
| 120 | + except (OSError, UnicodeDecodeError): |
| 121 | + raise GitHubCliAuthError( |
| 122 | + "GitHub authentication failed for provider 'github': " |
| 123 | + f"GitHub CLI could not provide a token for {hostname!r}." |
| 124 | + ) from None |
| 125 | + |
| 126 | + if result.returncode != 0: |
| 127 | + raise GitHubCliAuthError( |
| 128 | + "GitHub authentication failed for provider 'github': " |
| 129 | + f"GitHub CLI could not provide a token for {hostname!r}. " |
| 130 | + f"Run 'gh auth login --hostname {hostname}'." |
| 131 | + ) |
| 132 | + |
| 133 | + token = result.stdout.strip() |
| 134 | + if not token: |
| 135 | + raise GitHubCliAuthError( |
| 136 | + "GitHub authentication failed for provider 'github': " |
| 137 | + f"GitHub CLI returned an empty token for {hostname!r}. " |
| 138 | + f"Run 'gh auth login --hostname {hostname}'." |
| 139 | + ) |
| 140 | + if not token.isascii() or "\r" in token or "\n" in token: |
| 141 | + raise GitHubCliAuthError( |
| 142 | + "GitHub authentication failed for provider 'github': " |
| 143 | + f"GitHub CLI returned a malformed token for {hostname!r}." |
| 144 | + ) |
| 145 | + return token |
0 commit comments