Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(copilot): deterministic subscription token handoff to the proxy

Tejas Chopra72da46121726
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index e11005fc7..3ab64f3f6 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -37,7 +37,6 @@ if sys.platform == "win32" and hasattr(sys.stdout, "buffer"):
import click
from headroom._version import __version__ as _HEADROOM_VERSION
-from headroom.copilot_auth import DEFAULT_API_URL as COPILOT_API_URL
from headroom.copilot_auth import (
has_oauth_auth,
resolve_client_bearer_token,
@@ -162,6 +161,7 @@ def _start_proxy(
anyllm_provider: str | None = None,
region: str | None = None,
openai_api_url: str | None = None,
+ copilot_api_token: str | None = None,
) -> subprocess.Popen:
"""Start Headroom proxy as a background subprocess.
@@ -217,6 +217,12 @@ def _start_proxy(
proxy_env.setdefault("HEADROOM_STACK", f"wrap_{agent_type}")
if openai_api_url:
proxy_env["OPENAI_TARGET_API_URL"] = openai_api_url
+ # Pin the wrapper-validated Copilot token for this proxy instance only.
+ # Injected into the subprocess env here (not the parent's os.environ) so it
+ # never leaks into shared state. The proxy's CopilotTokenProvider honours
+ # GITHUB_COPILOT_API_TOKEN directly, making upstream auth deterministic.
+ if copilot_api_token:
+ proxy_env["GITHUB_COPILOT_API_TOKEN"] = copilot_api_token
proc = subprocess.Popen(
cmd,
@@ -1600,6 +1606,7 @@ def _ensure_proxy(
anyllm_provider: str | None = None,
region: str | None = None,
openai_api_url: str | None = None,
+ copilot_api_token: str | None = None,
) -> subprocess.Popen | None:
"""Start or verify proxy. Returns process handle if we started it."""
helpers = _live_wrap_module()
@@ -1700,8 +1707,7 @@ def _ensure_proxy(
if missing:
needs_restart = True
flags_str = ", ".join(
- f if f.startswith("--") else f"--{f.replace('_', '-')}"
- for f in missing
+ f if f.startswith("--") else f"--{f.replace('_', '-')}" for f in missing
)
click.echo(f" Proxy on port {port} is missing: {flags_str}")
click.echo(" Restarting proxy with upgraded configuration...")
@@ -1748,6 +1754,7 @@ def _ensure_proxy(
anyllm_provider=anyllm_provider,
region=region,
openai_api_url=openai_api_url,
+ copilot_api_token=copilot_api_token,
),
)
click.echo(f" Proxy ready on http://127.0.0.1:{port}")
@@ -1823,6 +1830,7 @@ def _launch_tool(
anyllm_provider: str | None = None,
region: str | None = None,
openai_api_url: str | None = None,
+ copilot_api_token: str | None = None,
) -> None:
"""Common logic: start proxy, launch tool, clean up."""
proxy_holder: list[subprocess.Popen | None] = [None]
@@ -1849,6 +1857,7 @@ def _launch_tool(
anyllm_provider=anyllm_provider,
region=region,
openai_api_url=openai_api_url,
+ copilot_api_token=copilot_api_token,
)
if code_graph:
@@ -2481,6 +2490,7 @@ def copilot(
env = os.environ.copy()
openai_api_url: str | None = None
+ copilot_proxy_token: str | None = None
if _should_use_copilot_oauth(
backend=effective_backend,
provider_type=provider_type,
@@ -2504,6 +2514,16 @@ def copilot(
env["COPILOT_PROVIDER_BEARER_TOKEN"] = client_bearer
env["GITHUB_COPILOT_USE_TOKEN_EXCHANGE"] = "false"
env.pop("COPILOT_PROVIDER_API_KEY", None)
+ # Hand the exact token we resolved (and, for --subscription, validated
+ # against GitHub) to the proxy explicitly via copilot_proxy_token below.
+ # The proxy pins it as GITHUB_COPILOT_API_TOKEN, so upstream auth is
+ # deterministic instead of the proxy re-running unvalidated discovery
+ # (read_cached_oauth_token returns the *first* candidate, which may not
+ # be the one the wrapper approved → environment-dependent 401s). Passing
+ # it as a launch argument — rather than mutating this process's global
+ # os.environ — keeps the token off shared state and out of unrelated
+ # code paths.
+ copilot_proxy_token = client_bearer
env_vars_display = [
"COPILOT_PROVIDER_TYPE=openai",
f"COPILOT_PROVIDER_BASE_URL=http://127.0.0.1:{port}/v1",
@@ -2518,9 +2538,6 @@ def copilot(
env["GITHUB_COPILOT_API_URL"] = openai_api_url
env["OPENAI_TARGET_API_URL"] = openai_api_url
env_vars_display.append(f"COPILOT_PROVIDER_API_URL={openai_api_url}")
- os.environ["GITHUB_COPILOT_USE_TOKEN_EXCHANGE"] = "false"
- os.environ["GITHUB_COPILOT_API_URL"] = openai_api_url
- os.environ["OPENAI_TARGET_API_URL"] = openai_api_url
else:
env, env_vars_display = _build_copilot_launch_env(
port=port,
@@ -2563,6 +2580,7 @@ def copilot(
anyllm_provider=anyllm_provider,
region=region,
openai_api_url=openai_api_url,
+ copilot_api_token=copilot_proxy_token,
)
diff --git a/tests/test_cli/test_wrap_copilot.py b/tests/test_cli/test_wrap_copilot.py
index 6381f792e..5be89c210 100644
--- a/tests/test_cli/test_wrap_copilot.py
+++ b/tests/test_cli/test_wrap_copilot.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import importlib
+import os
import sys
import types
from pathlib import Path
@@ -255,6 +256,59 @@ def test_wrap_copilot_subscription_uses_github_auth_without_provider_key(
assert captured["openai_api_url"] == DEFAULT_API_URL
+def test_wrap_copilot_subscription_pins_validated_token_for_proxy(
+ runner: CliRunner,
+ wrap_modules: tuple[types.ModuleType, click.Group],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """`--subscription` must hand the *validated* token to the proxy.
+
+ The proxy honours ``GITHUB_COPILOT_API_TOKEN``; the wrapper passes the
+ resolved token as the ``copilot_api_token`` launch argument so the proxy
+ pins exactly it (rather than re-discovering a possibly different,
+ unvalidated token). The token rides the launch arg, never the child env or
+ the parent's global ``os.environ``. This guards the deterministic handoff.
+ """
+ _wrap_cli, main = wrap_modules
+ for var in ("COPILOT_PROVIDER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"):
+ monkeypatch.delenv(var, raising=False)
+
+ business_api = "https://api.business.githubcopilot.com"
+ captured: dict[str, object] = {}
+
+ def fake_launch_tool(**kwargs: object) -> None:
+ captured.update(kwargs)
+
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="copilot"),
+ patch(
+ "headroom.cli.wrap.resolve_subscription_bearer_token",
+ return_value="gho-validated",
+ ),
+ patch("headroom.cli.wrap.resolve_copilot_api_url", return_value=business_api),
+ patch("headroom.cli.wrap.has_oauth_auth", return_value=False),
+ patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool),
+ ):
+ result = runner.invoke(main, ["wrap", "copilot", "--subscription", "--no-rtk"])
+
+ assert result.exit_code == 0, result.output
+ env = captured["env"]
+ assert isinstance(env, dict)
+ # The validated token is handed to the proxy as an explicit launch
+ # argument — not via the child env, not via the parent's os.environ.
+ assert captured["copilot_api_token"] == "gho-validated"
+ assert "GITHUB_COPILOT_API_TOKEN" not in env
+ assert os.environ.get("GITHUB_COPILOT_API_TOKEN") is None
+ assert env["COPILOT_PROVIDER_TYPE"] == "openai"
+ assert env["COPILOT_PROVIDER_BEARER_TOKEN"] == "gho-validated"
+ assert env["GITHUB_COPILOT_USE_TOKEN_EXCHANGE"] == "false"
+ assert env["OPENAI_TARGET_API_URL"] == business_api
+ assert captured["openai_api_url"] == business_api
+ assert "COPILOT_PROVIDER_API_KEY" not in env
+ # The secret must never be echoed to the terminal.
+ assert "gho-validated" not in result.output
+
+
def test_wrap_copilot_subscription_requires_reusable_auth(
runner: CliRunner,
wrap_modules: tuple[types.ModuleType, click.Group],
diff --git a/tests/test_copilot_subscription_smoke.py b/tests/test_copilot_subscription_smoke.py
new file mode 100644
index 000000000..e9759b5e8
--- /dev/null
+++ b/tests/test_copilot_subscription_smoke.py
@@ -0,0 +1,199 @@
+"""Cross-platform smoke test for GitHub Copilot subscription routing.
+
+The subscription flow has to behave identically on macOS, Linux, and Windows
+(and in headless Docker/CI), but the only OS-specific part — reading the
+Copilot CLI token from the platform secret store — is impossible to exercise
+portably. This suite proves the *portable* contract instead:
+
+1. With an explicit token in the environment, resolution + API-URL discovery
+ succeed on every platform without touching any secret store. This is the
+ universal escape hatch (``GITHUB_COPILOT_TOKEN`` etc.) that makes the
+ feature work anywhere, including headless CI.
+2. Each OS-specific secret reader is inert on a foreign platform — so on any
+ given OS only that OS's reader can fire, and a missing/foreign secret store
+ degrades to ``None`` rather than crashing.
+3. The proxy injects exactly the token the wrapper validated (the
+ deterministic-handoff fix), never a different discoverable one.
+4. The full wrapper→proxy chain carries one consistent token end to end.
+
+Everything here is hermetic: no Keychain, no ``secret-tool``, no Credential
+Manager, no network. It runs the same on every OS.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from headroom import copilot_auth, copilot_linux_secret, copilot_macos_keychain
+
+BUSINESS_API = "https://api.business.githubcopilot.com"
+
+
+def _stub_all_secret_stores(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Simulate 'no OS secret store / not logged in' on every platform."""
+ 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: None)
+ monkeypatch.setattr(copilot_auth, "_read_file_oauth_token_candidates", lambda: [])
+ monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
+
+
+def _clear_token_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ for var in (
+ *copilot_auth._COPILOT_OAUTH_TOKEN_ENV_VARS,
+ *copilot_auth._GENERIC_GITHUB_TOKEN_ENV_VARS,
+ *copilot_auth._API_TOKEN_ENV_VARS,
+ ):
+ monkeypatch.delenv(var, raising=False)
+
+
+# ---------------------------------------------------------------------------
+# 1. The env-var path resolves on any platform with no secret store.
+# ---------------------------------------------------------------------------
+def test_env_token_resolves_subscription_without_secret_store(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _stub_all_secret_stores(monkeypatch)
+ _clear_token_env(monkeypatch)
+ monkeypatch.setenv("GITHUB_COPILOT_TOKEN", "gho-env-universal")
+ monkeypatch.setattr(
+ copilot_auth,
+ "_fetch_copilot_user_info",
+ lambda token: (
+ {"endpoints": {"api": BUSINESS_API}} if token == "gho-env-universal" else None
+ ),
+ )
+
+ assert copilot_auth.resolve_subscription_bearer_token() == "gho-env-universal"
+ assert copilot_auth.resolve_copilot_api_url("gho-env-universal") == BUSINESS_API
+
+
+def test_api_url_falls_back_to_default_when_user_info_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _clear_token_env(monkeypatch)
+ monkeypatch.delenv("GITHUB_COPILOT_API_URL", raising=False)
+ monkeypatch.setattr(copilot_auth, "_fetch_copilot_user_info", lambda token: None)
+
+ # No network / no endpoints advertised → safe default, never a crash.
+ assert copilot_auth.resolve_copilot_api_url("gho-anything") == copilot_auth.DEFAULT_API_URL
+
+
+def test_subscription_rejects_token_github_does_not_accept(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _stub_all_secret_stores(monkeypatch)
+ _clear_token_env(monkeypatch)
+ # A generic GitHub token is present but GitHub's Copilot API rejects it;
+ # a valid Copilot token is discoverable behind it.
+ 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="gho-real-copilot",
+ source="macos-keychain:copilot-cli",
+ confidence="high",
+ ),
+ ],
+ )
+ monkeypatch.setattr(
+ copilot_auth,
+ "_fetch_copilot_user_info",
+ lambda token: {"endpoints": {"api": BUSINESS_API}} if token == "gho-real-copilot" else None,
+ )
+
+ assert copilot_auth.resolve_subscription_bearer_token() == "gho-real-copilot"
+
+
+# ---------------------------------------------------------------------------
+# 2. Each OS reader is inert on a foreign platform.
+# ---------------------------------------------------------------------------
[email protected]("foreign_platform", ["linux", "win32"])
+def test_macos_reader_noop_off_darwin(
+ monkeypatch: pytest.MonkeyPatch, foreign_platform: str
+) -> None:
+ monkeypatch.setattr(copilot_macos_keychain.sys, "platform", foreign_platform)
+ assert copilot_macos_keychain.read_copilot_oauth_token(host="github.com") is None
+
+
[email protected]("foreign_platform", ["darwin", "win32"])
+def test_linux_reader_noop_off_linux(
+ monkeypatch: pytest.MonkeyPatch, foreign_platform: str
+) -> None:
+ monkeypatch.setattr(copilot_linux_secret.sys, "platform", foreign_platform)
+ assert copilot_linux_secret.read_copilot_oauth_token(host="github.com") is None
+
+
+def test_windows_reader_noop_off_windows(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(copilot_auth.os, "name", "posix")
+ assert copilot_auth._read_windows_copilot_cli_oauth_token() is None
+
+
+# ---------------------------------------------------------------------------
+# 3. The proxy injects exactly the wrapper-validated token (determinism).
+# ---------------------------------------------------------------------------
+def test_proxy_injects_explicit_token_over_discovered_one(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Reset the cached module-level provider so this test is self-contained.
+ monkeypatch.setattr(copilot_auth, "_provider", None)
+ # What `wrap copilot --subscription` exports for the proxy:
+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "gho-validated")
+ monkeypatch.setenv("GITHUB_COPILOT_API_URL", BUSINESS_API)
+ monkeypatch.setenv("GITHUB_COPILOT_USE_TOKEN_EXCHANGE", "false")
+ # A *different* token is discoverable — it must be ignored entirely.
+ monkeypatch.setattr(
+ copilot_auth, "read_cached_oauth_token", lambda: "gho-WRONG-should-not-be-used"
+ )
+
+ headers = asyncio.run(
+ copilot_auth.apply_copilot_api_auth(
+ {"authorization": "Bearer placeholder"},
+ url=f"{BUSINESS_API}/v1/chat/completions",
+ )
+ )
+
+ assert headers["Authorization"] == "Bearer gho-validated"
+ assert "authorization" not in headers
+
+
+# ---------------------------------------------------------------------------
+# 4. Full wrapper→proxy chain carries one consistent token, any account host.
+# ---------------------------------------------------------------------------
+def test_end_to_end_subscription_chain(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(copilot_auth, "_provider", None)
+
+ # (a) wrapper side: resolve + validate the subscription token, then
+ # discover the account-specific API endpoint.
+ _stub_all_secret_stores(monkeypatch)
+ _clear_token_env(monkeypatch)
+ monkeypatch.setenv("GITHUB_COPILOT_TOKEN", "gho-seat-token")
+ monkeypatch.setattr(
+ copilot_auth,
+ "_fetch_copilot_user_info",
+ lambda token: {"endpoints": {"api": BUSINESS_API}} if token == "gho-seat-token" else None,
+ )
+ resolved_token = copilot_auth.resolve_subscription_bearer_token()
+ resolved_url = copilot_auth.resolve_copilot_api_url(resolved_token)
+ assert resolved_token == "gho-seat-token"
+ assert resolved_url == BUSINESS_API
+
+ # (b) hand-off: the wrapper exports exactly these for the proxy.
+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", resolved_token)
+ monkeypatch.setenv("GITHUB_COPILOT_API_URL", resolved_url)
+
+ # (c) proxy side: build the upstream URL (Copilot has no /v1 prefix) and
+ # inject the same token onto the outbound request.
+ upstream = copilot_auth.build_copilot_upstream_url(resolved_url, "/v1/chat/completions")
+ assert upstream == "https://api.business.githubcopilot.com/chat/completions"
+
+ headers = asyncio.run(
+ copilot_auth.apply_copilot_api_auth({"authorization": "Bearer placeholder"}, url=upstream)
+ )
+ assert headers["Authorization"] == f"Bearer {resolved_token}"