Skip to content

Commit 67e0f72

Browse files
mnriemCopilot
andauthored
feat(auth): support GitHub CLI credentials (#4960)
* feat(auth): support GitHub CLI credentials Add a dedicated github-cli authentication mode with host-aware token resolution, in-memory caching, sanitized failures, tests, and documentation. Assisted-by: GitHub Copilot (model: GPT-5.6 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 434e2508-0633-4d40-8e0d-5edb92cbc177 * fix(auth): address GitHub CLI host handling Pass explicit GitHub CLI hostnames, map configured enterprise service hosts to their instance login, and route sanitized credential failures through existing URL error handling. Assisted-by: GitHub Copilot (model: GPT-5.6 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 434e2508-0633-4d40-8e0d-5edb92cbc177 * fix(auth): preserve GitHub CLI diagnostics Keep sanitized GitHub CLI credential failures distinct from offline errors in release checks and upgrade output, prove no HTTP fallback occurs, and document terminal failure caching. Assisted-by: GitHub Copilot (model: GPT-5.6 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 434e2508-0633-4d40-8e0d-5edb92cbc177 * fix(auth): scope credentials across redirects Prevent GitHub CLI tokens from following redirects to a different GitHub credential host while preserving authorization across public and configured enterprise aliases. Assisted-by: GitHub Copilot (model: GPT-5.6 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 434e2508-0633-4d40-8e0d-5edb92cbc177 * fix(auth): preserve bundle CLI diagnostics Assisted-by: GitHub Copilot (model: GPT-5.6 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 434e2508-0633-4d40-8e0d-5edb92cbc177 * fix(auth): validate GitHub CLI hostnames Assisted-by: GitHub Copilot (model: GPT-5.6 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 434e2508-0633-4d40-8e0d-5edb92cbc177 * refactor(auth): narrow GitHub CLI provider scope Remove consumer-specific error handling, redirect policy changes, and shared provider API changes. Keep GitHub CLI host selection within the GitHub provider by treating each provider entry as one credential scope. Assisted-by: GitHub Copilot (model: GPT-5.6 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 434e2508-0633-4d40-8e0d-5edb92cbc177 * fix(auth): select first configured GitHub CLI hostname Use hosts[0] as the credential hostname instead of inferring an instance from service prefixes. Document ordering and cover first-host selection, wildcard rejection, and cache isolation. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(ci): update vulnerable OpenTelemetry audit pin Upgrade only opentelemetry-api from 1.45.0 to 1.45.1 and regenerate its hashes to resolve CVE-2026-114603 in the committed audit snapshot. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * test(auth): cover registered GitHub CLI request paths Exercise build_request and open_url with the registered GitHub provider and an isolated credential cache. Verify bearer headers and fail-fast acquisition errors, and cover sanitized cached PermissionError and UnicodeDecodeError failures. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(auth): reject multiline GitHub CLI credentials Reject embedded CR and LF after trimming CLI output, before returning or caching a token. Cache only the sanitized failure diagnostic and cover CR, LF, and CRLF regressions. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(auth): preserve caller handling of GitHub CLI failures Classify GitHub CLI acquisition failures as URL errors so existing catalog handlers can warn and continue, while each affected HTTP request still fails without credential or anonymous fallback. Cache the sanitized reason without nesting URL-error wrappers. Add catalog-search regression, release-check, and redirect-wiring coverage; retain the approved first-host credential contract. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * docs(auth): list GitHub CLI in auth scheme table Add the GitHub CLI credential mode alongside bearer and remove the redundant prose below the table. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * docs(auth): clarify acquisition failure versus HTTP fallback Qualify the authentication process summary and HTTP helper docstrings: GitHub CLI acquisition errors stop the request immediately, whereas HTTP 401/403 after successful acquisition still permits matching-entry and anonymous fallback. No runtime behavior changes. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(auth): reject non-ASCII GitHub CLI credentials Reject decoded non-ASCII CLI output through the sanitized malformed-token path before returning or caching credentials. Extend failure-cache regression coverage to Latin-1 and non-Latin-1 Unicode and document the restriction. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(auth): preserve credential failures in release and bundle consumers Keep sanitized GitHub CLI diagnostics in release checks and upgrade failure rendering. Treat authentication failures as definitive in bundle catalog fetching and reference validation, rather than availability fallbacks. Add regressions that failed before the fix and document the caller behavior; preserve the first-host contract and authentication base classes. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * test(auth): normalize wrapped release diagnostics Normalize captured whitespace before checking authentication error details so Rich line wrapping does not make release-command tests depend on terminal width. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 434e2508-0633-4d40-8e0d-5edb92cbc177
1 parent fe971dc commit 67e0f72

7 files changed

Lines changed: 784 additions & 24 deletions

File tree

‎docs/reference/authentication.md‎

Lines changed: 75 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Either `token` or `token_env` must be set for the `bearer`, `basic-pat`, and `ba
5959
| Scheme | Header | Use for |
6060
|---|---|---|
6161
| `bearer` | `Authorization: Bearer <token>` | PATs, fine-grained PATs, OAuth tokens, GitHub App tokens |
62+
| `github-cli` | `Authorization: Bearer <token>` | Credentials acquired on demand via `gh auth token` |
6263
6364
**Example — PAT via environment variable:**
6465
@@ -71,6 +72,51 @@ Either `token` or `token_env` must be set for the `bearer`, `basic-pat`, and `ba
7172
}
7273
```
7374
75+
**Example — GitHub CLI:**
76+
77+
```json
78+
{
79+
"providers": [
80+
{
81+
"hosts": [
82+
"github.com",
83+
"api.github.com",
84+
"raw.githubusercontent.com",
85+
"codeload.github.com"
86+
],
87+
"provider": "github",
88+
"auth": "github-cli"
89+
}
90+
]
91+
}
92+
```
93+
94+
Install [GitHub CLI](https://cli.github.com/) and run `gh auth login` before
95+
using this mode. Specify runs the fixed command
96+
`gh auth token --hostname github.com` without a shell, caches the result in
97+
memory for the current process, and never writes the token to disk.
98+
Surrounding whitespace is trimmed; tokens containing non-ASCII characters,
99+
embedded carriage returns, or newlines are rejected without including the
100+
token in the error.
101+
Credential acquisition failures fail the affected request without trying another
102+
credential or an unauthenticated request. They use the existing URL-error
103+
category, so callers retain their normal error handling (for example, warning
104+
and skipping an unavailable catalog).
105+
Release checks and upgrades preserve the authentication diagnostic rather than
106+
reporting a network outage. Online bundle catalog fetching and reference
107+
validation treat authentication failures as errors, not as availability
108+
fallbacks to packaged snapshots or unchecked references.
109+
110+
For `github-cli` only, the **first hostname in `hosts`** is passed to
111+
`gh auth token --hostname`. Put `github.com` or your enterprise instance's
112+
GitHub CLI login hostname first. It must be an exact hostname, not a wildcard.
113+
All listed hosts remain request-matching destinations authorized to receive
114+
that credential; later entries may use supported wildcards. Specify does not
115+
infer the credential hostname from service prefixes or the requested URL.
116+
The in-memory cache is keyed by the first hostname. Use separate provider
117+
entries for hosts requiring different credentials. Host order has no effect
118+
on existing authentication modes.
119+
74120
### GitHub Enterprise Server (GHES)
75121

76122
To use a private catalog or extension hosted on a GitHub Enterprise Server
@@ -98,6 +144,28 @@ and `codeload.` subdomains your catalog/extension URLs use. A
98144
`*.ghes.example.com` wildcard matches subdomains but **not** the bare host,
99145
so always include the bare host explicitly.
100146

147+
With `auth: "github-cli"`, list your enterprise instance's GitHub CLI login
148+
hostname first, followed by any request hosts or wildcard patterns that should
149+
receive the same credential:
150+
151+
```json
152+
{
153+
"hosts": [
154+
"ghes.example.com",
155+
"raw.ghes.example.com",
156+
"codeload.ghes.example.com"
157+
],
158+
"provider": "github",
159+
"auth": "github-cli"
160+
}
161+
```
162+
163+
Specify runs `gh auth token --hostname ghes.example.com`, using the first
164+
hostname exactly as configured. Use separate provider entries for separate
165+
GitHub instances. The selected host must already be
166+
authenticated in GitHub CLI; failures suggest `gh auth login --hostname <host>`
167+
without including GitHub CLI command output.
168+
101169
### GitHub Enterprise Cloud with data residency (GHE.com)
102170

103171
GHE.com tenants use separate web and REST API hostnames. List both hosts so
@@ -264,10 +332,13 @@ You can configure multiple entries for different hosts or organizations:
264332
1. For each outbound HTTP request, the URL hostname is matched against
265333
the `hosts` patterns in `auth.json`.
266334
2. If a match is found, the corresponding provider resolves the token
267-
and attaches the appropriate `Authorization` header.
268-
3. If the request receives a 401 or 403, the next matching entry is tried.
269-
4. After all matching entries are exhausted, an unauthenticated request
270-
is attempted as a final fallback.
335+
and attaches the appropriate `Authorization` header. A `github-cli`
336+
acquisition failure ends the request immediately, without trying later
337+
matching entries or making an unauthenticated request.
338+
3. After successful token acquisition, if the request receives a 401 or 403,
339+
the next matching entry is tried.
340+
4. After all matching entries are exhausted without an acquisition failure,
341+
an unauthenticated request is attempted as a final fallback.
271342
5. On redirects, the `Authorization` header is stripped if the redirect
272343
target leaves the entry's declared hosts — preventing credential
273344
leakage to CDNs or third-party services.

‎src/specify_cli/_version.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
"rate limited (configure ~/.specify/auth.json with a GitHub token)"
3838
)
3939
_RESOLUTION_FAILURE_HTTP_PREFIX = "HTTP "
40+
_RESOLUTION_FAILURE_AUTH_PREFIX = "authentication error: "
4041
_FAILURE_INSTALLER_MISSING = "installer-missing"
4142
_FAILURE_INSTALLER_INVALID = "installer-invalid"
4243
_FAILURE_TARGET_TAG_UNPARSEABLE = "target-tag-unparseable"
@@ -108,11 +109,12 @@ def _fetch_latest_release_tag() -> tuple[str | None, str | None]:
108109
"""Return (tag, failure_category). Exactly one outbound call, 5 s timeout.
109110
110111
On success: (tag_name, None).
111-
On a documented network/HTTP failure (added in T029/T030): (None, category).
112+
On a documented authentication/network/HTTP failure: (None, category).
112113
On anything else — including a malformed response body — the exception
113114
propagates; there is no catch-all (research D-006).
114115
"""
115116
from .authentication.http import open_url
117+
from .authentication.github import GitHubCliAuthError
116118

117119
try:
118120
with open_url(
@@ -131,6 +133,8 @@ def _fetch_latest_release_tag() -> tuple[str | None, str | None]:
131133
if not isinstance(tag, str) or not tag:
132134
raise ValueError("GitHub API response missing valid tag_name")
133135
return tag, None
136+
except GitHubCliAuthError as exc:
137+
return None, f"{_RESOLUTION_FAILURE_AUTH_PREFIX}{exc.reason}"
134138
except urllib.error.HTTPError as e:
135139
# Order matters: HTTPError is a subclass of URLError.
136140
# 403 (primary rate limit / abuse detection) and 429 (Too Many Requests /
@@ -1021,7 +1025,10 @@ def _emit_failure(
10211025
"""Render user-facing output for resolver, installer, or verification failures."""
10221026
if (
10231027
category in _RESOLUTION_FAILURE_CATEGORIES
1024-
or category.startswith(_RESOLUTION_FAILURE_HTTP_PREFIX)
1028+
or category.startswith((
1029+
_RESOLUTION_FAILURE_HTTP_PREFIX,
1030+
_RESOLUTION_FAILURE_AUTH_PREFIX,
1031+
))
10251032
):
10261033
console.print(f"Upgrade aborted: {category}", soft_wrap=True)
10271034
return

‎src/specify_cli/authentication/github.py‎

Lines changed: 130 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,144 @@
22

33
from __future__ import annotations
44

5+
import os
6+
import shutil
7+
import subprocess
8+
from typing import TYPE_CHECKING
9+
from urllib.error import URLError
10+
511
from .base import AuthProvider
612

13+
if TYPE_CHECKING:
14+
from .config import AuthConfigEntry
715

8-
class GitHubAuth(AuthProvider):
9-
"""GitHub authentication provider.
1016

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."""
1440

1541
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]] = {}
1746

1847
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:
2150
raise ValueError(
2251
f"GitHubAuth does not support auth scheme {auth_scheme!r}"
2352
)
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

‎src/specify_cli/authentication/http.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ def build_request(url: str, extra_headers: dict[str, str] | None = None) -> urll
133133
134134
Uses the first matching entry from ``auth.json`` whose token resolves.
135135
Returns a plain request when no entry matches or the file doesn't exist.
136+
A ``github-cli`` acquisition failure raises immediately, without trying
137+
later matching entries or returning an unauthenticated request.
136138
"""
137139
headers: dict[str, str] = {}
138140
if extra_headers:
@@ -174,9 +176,12 @@ def open_url(
174176
"""Open *url* with config-driven auth, redirect stripping, and fallthrough.
175177
176178
1. Find ``auth.json`` entries whose hosts match the URL.
177-
2. For each entry, resolve the token and try the request.
178-
3. On 401/403 move to the next matching entry.
179-
4. After all entries exhausted (or none matched), try unauthenticated.
179+
2. For each entry, resolve the token and try the request. A ``github-cli``
180+
acquisition failure raises immediately, with no credential or
181+
unauthenticated fallback.
182+
3. On HTTP 401/403 after successful acquisition, try the next matching entry.
183+
4. After all entries exhausted without an acquisition failure (or none
184+
matched), try unauthenticated.
180185
5. Non-auth errors (404, 500, network) raise immediately.
181186
182187
*extra_headers* (e.g. ``Accept``) are merged into every attempt.

‎src/specify_cli/bundles/adapters.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@ def _http_get_json(source_id: str, url: str) -> dict:
228228
HTTPS/host guarantee from ``_validate_remote_url`` is preserved end to end
229229
rather than only on the initial URL.
230230
"""
231+
from ..authentication.github import GitHubCliAuthError
231232
from ..authentication.http import RedirectPolicyError, open_url
232233

233234
def _validate_redirect(_old_url: str, new_url: str) -> None:
@@ -258,9 +259,9 @@ def _validate_redirect(_old_url: str, new_url: str) -> None:
258259
raise BundlerError(
259260
f"Failed to fetch catalog from {url}: {exc}"
260261
) from exc
261-
except RedirectPolicyError as exc:
262-
# Unsafe/malformed redirects are security failures and must surface as
263-
# a hard error instead of being downgraded to catalog unavailability.
262+
except (GitHubCliAuthError, RedirectPolicyError) as exc:
263+
# Authentication and redirect-policy failures are definitive, not
264+
# transient catalog unavailability.
264265
raise BundlerError(
265266
f"Failed to fetch catalog from {url}: {exc}"
266267
) from exc

‎src/specify_cli/bundles/component_catalog.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from http.client import HTTPException
77
from urllib.error import HTTPError, URLError
88

9+
from ..authentication.github import GitHubCliAuthError
910
from ..authentication.http import RedirectPolicyError
1011
from . import BundlerError
1112
from .manifest import ComponentRef
@@ -19,7 +20,7 @@ def _is_unavailable(exc: BaseException) -> bool:
1920
seen: set[int] = set()
2021
while exc is not None and id(exc) not in seen:
2122
seen.add(id(exc))
22-
if isinstance(exc, RedirectPolicyError):
23+
if isinstance(exc, (GitHubCliAuthError, RedirectPolicyError)):
2324
return False
2425
if isinstance(exc, HTTPError):
2526
return exc.code in (408, 429) or 500 <= exc.code <= 599

0 commit comments

Comments
 (0)