fix(copilot): defer keychain auth lookup (#2739)

## Description

Defers macOS Keychain and Linux Secret Service OAuth discovery until
non-platform Copilot credentials fail during `headroom wrap copilot
--subscription`. This prevents needless macOS Keychain prompts when
saved Headroom OAuth authentication already resolves. Closes #2738.

## Type of Change

- [x] Bug fix (non-breaking change fixes an issue)
- [ ] New feature (non-breaking change adds functionality)
- [ ] Breaking change (fix or feature would cause existing functionality
change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/copilot_auth.py`: split subscription credential resolution
into a non-platform pass and a platform-secret-store fallback pass.
- `tests/test_copilot_auth.py`: cover successful saved-token resolution
without Keychain access, Keychain fallback, and duplicate-token
avoidance.
- `tests/test_copilot_subscription_smoke.py`: preserve the
generic-token-to-Keychain fallback smoke test for the new two-pass
candidate-discovery API.
- Merged current upstream main to pick up the audited cryptography
50.0.0 lock; latest head is `ec306470`.

## Testing

- [x] Unit tests pass for changed behavior
- [x] Linting passes
- [x] Type checking passes
- [x] New tests added
- [x] Manual testing performed

### Test Output

```text
UV_NO_SYNC=1 uv run --no-sync pytest tests/test_copilot_auth.py tests/test_copilot_macos_keychain.py tests/test_copilot_linux_secret.py tests/test_copilot_subscription_smoke.py tests/test_cli/test_wrap_copilot.py -q
158 passed

UV_NO_SYNC=1 uv run --no-sync ruff format --check .
1333 files already formatted

UV_NO_SYNC=1 uv run --no-sync ruff check .
All checks passed

UV_NO_SYNC=1 uv run --no-sync mypy headroom
Success: no issues found in 508 source files
```

## Real Behavior Proof

- Environment: macOS 26.5 (25F71), Python 3.14.5, Headroom topic
worktree `rnoz/fix-copilot-keychain-fallback`, GitHub Copilot CLI
1.0.77, saved Headroom OAuth credential present.
- Exact command / steps: commands below

```text
cd /Users/rnozal/projects/headroom/.worktrees/fix-copilot-keychain-fallback
UV_NO_SYNC=1 uv run --no-sync headroom wrap copilot --subscription --port 8795 -- --model claude-opus-4.8 --prompt 'Reply with exactly: OK' --silent --allow-all-tools --allow-all-paths --allow-all-urls
```

- Observed result: the command printed `OK`, launched against
`http://127.0.0.1:8795/p/fix-copilot-keychain-fallback/v1`, and no macOS
Keychain authorization dialog appeared.
- Not tested: an expired or revoked saved token falling back to a real
macOS Keychain item, Linux Secret Service, Windows Credential Manager,
and GitHub Enterprise credential hosts.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review
- [x] I commented my code, particularly in hard-to-understand areas (not
needed, the code is self-explanatory)
- [x] I made corresponding changes to documentation (not needed, no
user-facing API changes)
- [x] My changes generate no new warnings
- [x] I added tests to prove my fix is effective
- [x] New and existing relevant unit tests pass locally
- [x] I did **not** edit `CHANGELOG.md`

## Screenshots (if applicable)

Not applicable.

## Additional Notes

The full `pytest -q` run was attempted after installing the missing
`litellm` test dependency. It reached execution but failed in five
unrelated existing tests: four Kompress readiness tests depended on an
already-initialized PyTorch backend, and one Windows-only selector-loop
test failed under Python 3.14 on macOS. The changed Copilot suites and
the live wrapped-Copilot proof passed.
This commit is contained in:
rNoz
2026-10-01 00:09:41 -05:00
committed by GitHub
parent 8cfeb692ca
commit 81a8a28da3
3 changed files with 328 additions and 44 deletions
+62 -27
View File
@@ -808,7 +808,9 @@ def read_cached_oauth_token() -> str | None:
return None
def iter_oauth_token_candidates() -> list[CopilotTokenCandidate]:
def iter_oauth_token_candidates(
*, include_platform_secret_stores: bool = True
) -> list[CopilotTokenCandidate]:
"""Return reusable token candidates in safest-first discovery order."""
candidates: list[CopilotTokenCandidate] = []
@@ -834,6 +836,38 @@ def iter_oauth_token_candidates() -> list[CopilotTokenCandidate]:
)
)
if include_platform_secret_stores:
candidates.extend(_platform_secret_store_oauth_token_candidates())
candidates.extend(_read_file_oauth_token_candidates())
for env_var in _GENERIC_GITHUB_TOKEN_ENV_VARS:
token = os.environ.get(env_var, "").strip()
if token:
candidates.append(
CopilotTokenCandidate(
token=token,
source=f"env:{env_var}",
confidence="generic-github",
)
)
gh_token = _read_gh_cli_oauth_token()
if gh_token:
candidates.append(
CopilotTokenCandidate(
token=gh_token,
source="gh-cli",
confidence="generic-github",
)
)
return _dedupe_token_candidates(candidates)
def _platform_secret_store_oauth_token_candidates() -> list[CopilotTokenCandidate]:
"""Return OAuth candidates from platform credential stores."""
candidates: list[CopilotTokenCandidate] = []
windows_copilot_token = _read_windows_copilot_cli_oauth_token()
if windows_copilot_token:
candidates.append(
@@ -863,31 +897,7 @@ def iter_oauth_token_candidates() -> list[CopilotTokenCandidate]:
confidence="high",
)
)
candidates.extend(_read_file_oauth_token_candidates())
for env_var in _GENERIC_GITHUB_TOKEN_ENV_VARS:
token = os.environ.get(env_var, "").strip()
if token:
candidates.append(
CopilotTokenCandidate(
token=token,
source=f"env:{env_var}",
confidence="generic-github",
)
)
gh_token = _read_gh_cli_oauth_token()
if gh_token:
candidates.append(
CopilotTokenCandidate(
token=gh_token,
source="gh-cli",
confidence="generic-github",
)
)
return _dedupe_token_candidates(candidates)
return candidates
def _read_file_oauth_token_candidates() -> list[CopilotTokenCandidate]:
@@ -1153,9 +1163,34 @@ def resolve_subscription_bearer_token_details() -> CopilotSubscriptionTokenResol
api_url=_subscription_api_url_from_user_info_payload(payload),
)
for candidate in iter_oauth_token_candidates():
attempted_tokens: set[str] = set()
resolution = _resolve_subscription_oauth_token_candidates(
iter_oauth_token_candidates(include_platform_secret_stores=False),
attempted_tokens=attempted_tokens,
)
if resolution is not None:
return resolution
return _resolve_subscription_oauth_token_candidates(
[
candidate
for candidate in _platform_secret_store_oauth_token_candidates()
if candidate.token not in attempted_tokens
]
)
def _resolve_subscription_oauth_token_candidates(
candidates: list[CopilotTokenCandidate],
*,
attempted_tokens: set[str] | None = None,
) -> CopilotSubscriptionTokenResolution | None:
"""Return the first candidate GitHub accepts for subscription APIs."""
for candidate in candidates:
if not candidate.validate_for_subscription:
continue
if attempted_tokens is not None:
attempted_tokens.add(candidate.token)
if _is_copilot_api_token(candidate.token):
payload = _fetch_copilot_user_info(candidate.token)
if payload is not None:
+242 -7
View File
@@ -253,7 +253,11 @@ def test_read_cached_oauth_token_prefers_copilot_cli_before_generic_github_token
monkeypatch.delenv("GITHUB_COPILOT_TOKEN", raising=False)
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.setenv("GITHUB_TOKEN", "ghp-generic")
monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
monkeypatch.setattr(
copilot_auth,
"_read_windows_copilot_cli_oauth_token",
lambda: None,
)
monkeypatch.setattr(copilot_auth, "_read_macos_keychain_oauth_token", lambda: "gho-keychain")
monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
@@ -291,7 +295,7 @@ def test_resolve_subscription_bearer_token_skips_invalid_generic_token(
monkeypatch.setattr(
copilot_auth,
"iter_oauth_token_candidates",
lambda: [
lambda **_kwargs: [
copilot_auth.CopilotTokenCandidate(
token="ghp-generic",
source="env:GITHUB_TOKEN",
@@ -317,6 +321,30 @@ def test_resolve_subscription_bearer_token_skips_invalid_generic_token(
assert copilot_auth.resolve_subscription_bearer_token() == "tid_copilot"
def test_resolve_subscription_candidates_skips_unvalidated_candidate(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
copilot_auth,
"_subscription_resolution_from_token_exchange",
lambda candidate: pytest.fail(f"must not exchange {candidate.source}"),
)
assert (
copilot_auth._resolve_subscription_oauth_token_candidates(
[
copilot_auth.CopilotTokenCandidate(
token="gho-unvalidated",
source="untrusted",
confidence="low",
validate_for_subscription=False,
)
]
)
is None
)
def test_resolve_subscription_bearer_token_does_not_fallback_to_unexchanged_oauth(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -328,7 +356,7 @@ def test_resolve_subscription_bearer_token_does_not_fallback_to_unexchanged_oaut
monkeypatch.setattr(
copilot_auth,
"iter_oauth_token_candidates",
lambda: [
lambda **_kwargs: [
copilot_auth.CopilotTokenCandidate(
token="gho-copilot",
source="macos-keychain:copilot-cli",
@@ -349,6 +377,126 @@ def test_resolve_subscription_bearer_token_does_not_fallback_to_unexchanged_oaut
assert copilot_auth.resolve_subscription_bearer_token() is None
def test_resolve_subscription_bearer_token_defers_keychain_when_saved_token_resolves(
monkeypatch: pytest.MonkeyPatch,
) -> None:
copilot_auth.save_headroom_copilot_oauth_token("gho-saved")
monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
monkeypatch.setattr(
copilot_auth,
"_read_macos_keychain_oauth_token",
lambda: pytest.fail("Keychain must not be read when saved OAuth resolves"),
)
monkeypatch.setattr(copilot_auth, "_read_linux_secret_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_file_oauth_token_candidates", lambda: [])
monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
monkeypatch.setattr(
copilot_auth,
"_subscription_resolution_from_token_exchange",
lambda candidate: (
copilot_auth._subscription_resolution(
token="copilot-api",
source=f"{candidate.source}:token-exchange",
confidence="copilot-token-exchange",
api_url=copilot_auth.DEFAULT_API_URL,
refresh_oauth_token=candidate.token,
)
if candidate.token == "gho-saved"
else None
),
)
assert copilot_auth.resolve_subscription_bearer_token() == "copilot-api"
def test_resolve_subscription_bearer_token_reads_keychain_after_noninteractive_rejection(
monkeypatch: pytest.MonkeyPatch,
) -> None:
copilot_auth.save_headroom_copilot_oauth_token("gho-rejected")
monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
monkeypatch.setattr(
copilot_auth,
"_read_macos_keychain_oauth_token",
lambda: "gho-keychain",
)
monkeypatch.setattr(copilot_auth, "_read_linux_secret_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_file_oauth_token_candidates", lambda: [])
monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
monkeypatch.setattr(
copilot_auth,
"_subscription_resolution_from_token_exchange",
lambda candidate: (
copilot_auth._subscription_resolution(
token="copilot-api",
source=f"{candidate.source}:token-exchange",
confidence="copilot-token-exchange",
api_url=copilot_auth.DEFAULT_API_URL,
refresh_oauth_token=candidate.token,
)
if candidate.token == "gho-keychain"
else None
),
)
assert copilot_auth.resolve_subscription_bearer_token() == "copilot-api"
def test_resolve_subscription_bearer_token_reads_windows_store_after_noninteractive_rejection(
monkeypatch: pytest.MonkeyPatch,
) -> None:
copilot_auth.save_headroom_copilot_oauth_token("gho-rejected")
monkeypatch.setattr(
copilot_auth,
"_read_windows_copilot_cli_oauth_token",
lambda: "gho-windows",
)
monkeypatch.setattr(copilot_auth, "_read_macos_keychain_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_linux_secret_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_file_oauth_token_candidates", lambda: [])
monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
monkeypatch.setattr(
copilot_auth,
"_subscription_resolution_from_token_exchange",
lambda candidate: (
copilot_auth._subscription_resolution(
token="copilot-api",
source=f"{candidate.source}:token-exchange",
confidence="copilot-token-exchange",
api_url=copilot_auth.DEFAULT_API_URL,
refresh_oauth_token=candidate.token,
)
if candidate.token == "gho-windows"
else None
),
)
assert copilot_auth.resolve_subscription_bearer_token() == "copilot-api"
def test_resolve_subscription_bearer_token_skips_duplicate_keychain_candidate(
monkeypatch: pytest.MonkeyPatch,
) -> None:
copilot_auth.save_headroom_copilot_oauth_token("gho-duplicate")
monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
monkeypatch.setattr(
copilot_auth,
"_read_macos_keychain_oauth_token",
lambda: "gho-duplicate",
)
monkeypatch.setattr(copilot_auth, "_read_linux_secret_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_file_oauth_token_candidates", lambda: [])
monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
attempted_tokens: list[str] = []
monkeypatch.setattr(
copilot_auth,
"_subscription_resolution_from_token_exchange",
lambda candidate: attempted_tokens.append(candidate.token) or None,
)
assert copilot_auth.resolve_subscription_bearer_token() is None
assert attempted_tokens == ["gho-duplicate"]
def test_subscription_enterprise_host_repro(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -363,7 +511,7 @@ def test_subscription_enterprise_host_repro(
monkeypatch.setattr(
copilot_auth,
"iter_oauth_token_candidates",
lambda: [
lambda **_kwargs: [
copilot_auth.CopilotTokenCandidate(
token="gho-oauth",
source="headroom-copilot-auth:/tmp/copilot_auth.json",
@@ -419,7 +567,7 @@ def test_resolve_subscription_exchange_uses_cloud_enterprise_advertised_api(
monkeypatch.setattr(
copilot_auth,
"iter_oauth_token_candidates",
lambda: [
lambda **_kwargs: [
copilot_auth.CopilotTokenCandidate(
token="gho-oauth",
source="env:GITHUB_COPILOT_TOKEN",
@@ -486,7 +634,7 @@ def _resolve_subscription_producer_path(
patch.setattr(
copilot_auth,
"iter_oauth_token_candidates",
lambda: [
lambda **_kwargs: [
copilot_auth.CopilotTokenCandidate(
token="gho-oauth", source="test", confidence="test"
)
@@ -504,7 +652,7 @@ def _resolve_subscription_producer_path(
patch.setattr(
copilot_auth,
"iter_oauth_token_candidates",
lambda: [
lambda **_kwargs: [
copilot_auth.CopilotTokenCandidate(
token="tid_api", source="test", confidence="test"
)
@@ -1715,3 +1863,90 @@ def test_exchange_token_sync_uses_configured_corporate_tls_context(
assert result == payload
assert captured["context"] is tls_context
def test_iter_oauth_token_candidates_includes_linux_secret_service_token(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("GITHUB_COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_COPILOT_TOKEN", raising=False)
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_macos_keychain_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_linux_secret_oauth_token", lambda: "gho-linux")
monkeypatch.setattr(copilot_auth, "_read_file_oauth_token_candidates", lambda: [])
monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
candidates = copilot_auth.iter_oauth_token_candidates()
assert [(candidate.source, candidate.token) for candidate in candidates] == [
("linux-secret-service:copilot-cli", "gho-linux"),
]
def test_iter_oauth_token_candidates_skips_platform_secret_stores_when_disabled(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("GITHUB_COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_COPILOT_TOKEN", raising=False)
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.setattr(
copilot_auth,
"_read_windows_copilot_cli_oauth_token",
lambda: pytest.fail("Windows Credential Manager should not be read"),
)
monkeypatch.setattr(
copilot_auth,
"_platform_secret_store_oauth_token_candidates",
lambda: pytest.fail("platform secret stores should not be read"),
)
monkeypatch.setattr(copilot_auth, "_read_file_oauth_token_candidates", lambda: [])
monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
assert copilot_auth.iter_oauth_token_candidates(include_platform_secret_stores=False) == []
def test_iter_oauth_token_candidates_reads_windows_store_when_enabled(
monkeypatch: pytest.MonkeyPatch,
) -> None:
for env_var in (
"GITHUB_COPILOT_GITHUB_TOKEN",
"GITHUB_COPILOT_TOKEN",
"COPILOT_GITHUB_TOKEN",
"GITHUB_TOKEN",
"GH_TOKEN",
):
monkeypatch.delenv(env_var, raising=False)
monkeypatch.setattr(
copilot_auth,
"_read_windows_copilot_cli_oauth_token",
lambda: "gho-windows",
)
monkeypatch.setattr(copilot_auth, "_read_macos_keychain_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_linux_secret_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_file_oauth_token_candidates", lambda: [])
monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
candidates = copilot_auth.iter_oauth_token_candidates()
assert [(candidate.source, candidate.token) for candidate in candidates] == [
("windows-credential-manager:copilot-cli", "gho-windows"),
]
def test_platform_secret_store_candidates_include_macos_keychain_token(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
monkeypatch.setattr(copilot_auth, "_read_macos_keychain_oauth_token", lambda: "gho-macos")
monkeypatch.setattr(copilot_auth, "_read_linux_secret_oauth_token", lambda: None)
candidates = copilot_auth._platform_secret_store_oauth_token_candidates()
assert [(candidate.source, candidate.token) for candidate in candidates] == [
("macos-keychain:copilot-cli", "gho-macos"),
]
+24 -10
View File
@@ -100,19 +100,33 @@ def test_subscription_rejects_generic_token_and_accepts_api_token(
)
# A generic GitHub token is present but cannot be exchanged for a Copilot
# API token; a valid Copilot API token is discoverable behind it.
non_platform_candidates = [
copilot_auth.CopilotTokenCandidate(
token="ghp-generic-pat",
source="env:GITHUB_TOKEN",
confidence="generic-github",
)
]
platform_candidates = [
copilot_auth.CopilotTokenCandidate(
token="tid_real_copilot",
source="macos-keychain:copilot-cli",
confidence="high",
)
]
monkeypatch.setattr(
copilot_auth,
"iter_oauth_token_candidates",
lambda: [
copilot_auth.CopilotTokenCandidate(
token="ghp-generic-pat", source="env:GITHUB_TOKEN", confidence="generic-github"
),
copilot_auth.CopilotTokenCandidate(
token="tid_real_copilot",
source="macos-keychain:copilot-cli",
confidence="high",
),
],
lambda *, include_platform_secret_stores=True: (
platform_candidates + non_platform_candidates
if include_platform_secret_stores
else non_platform_candidates
),
)
monkeypatch.setattr(
copilot_auth,
"_platform_secret_store_oauth_token_candidates",
lambda: platform_candidates,
)
monkeypatch.setattr(
copilot_auth,