diff --git a/github-copilot/README.md b/github-copilot/README.md index fc33aa3..3c37df6 100644 --- a/github-copilot/README.md +++ b/github-copilot/README.md @@ -20,9 +20,11 @@ hermes plugins install github-copilot ``` Needs a Hermes release in which Copilot has left core -([hermes-agent#144788](https://github.com/NousResearch/hermes-agent/pull/144788)). On an older Hermes the -plugin stays inactive and logs one warning: that Hermes still ships its own Copilot support, which keeps -working. +([hermes-agent#144788](https://github.com/NousResearch/hermes-agent/pull/144788)) and the generic +credential-pool runtime SDK: `providers.base.PoolRuntimeCredential`, +`ProviderProfile.prepare_pool_entry`, `refresh_pool_runtime_credentials`, and +`credential_pool_base_urls`. On a core missing these seams the plugin stays inactive and logs one +warning; upgrade core before using this plugin revision. ## Sign in @@ -61,6 +63,27 @@ Copilot list. starts `copilot --acp --stdio` per request; point it elsewhere with `HERMES_COPILOT_ACP_COMMAND` (or `COPILOT_CLI_PATH`) and `HERMES_COPILOT_ACP_ARGS`. +## Credential-pool recovery + +Pool rows retain the durable GitHub grant. After a row is selected, its exchanged Copilot bearer +and account endpoint are transient runtime credentials, never replacements in `auth.json`. +On a 401 or a stale-credential refusal (400 integrator, bare 403), Hermes renews only the row that +supplied the failed request: its memory, disk and failure-cache entries are evicted before a fresh +exchange of that same grant. A fine-grained PAT is never exchanged, so its row is not renewed. +Failed forced renewal returns no replacement; it never substitutes an ambient account or raw token. +Normal initial resolution still permits the existing same-account raw-token fallback. + +Runtime endpoint changes are restricted to these exact HTTPS origins: +`https://api.githubcopilot.com`, `https://api.individual.githubcopilot.com`, +`https://api.business.githubcopilot.com`, and `https://api.enterprise.githubcopilot.com`. +Custom relays, alternate ports, path-prefixed URLs and lookalike domains are not authorized account +endpoint transitions. Catalog source ordering and fallback policy are unchanged. + +GitHub Enterprise Cloud (`copilot-api..ghe.com`) is not one of these origins yet: core +cannot admit a per-profile enterprise origin for pool rows. An env token with `COPILOT_GH_HOST` and +`COPILOT_API_BASE_URL` set as above keeps working through core's env resolution, which re-exchanges +it after a 401, but without pool rotation. `hermes auth add copilot` rows are not supported on GHEC. + ## Premium requests Copilot reads the `x-initiator` header to tell a request you started (`user`) from an agent follow-up diff --git a/github-copilot/__init__.py b/github-copilot/__init__.py index 2b2e5bc..543eef2 100644 --- a/github-copilot/__init__.py +++ b/github-copilot/__init__.py @@ -21,6 +21,7 @@ "api_mode_for_model", "client_headers", "request_headers", "max_tokens_param", "seed_pool_credentials", "refresh_runtime_credentials", "external_auth_evidence", "live_context_length", "replay_message_carriers", "start_device_login", "picker_catalog", + "prepare_pool_entry", "refresh_pool_runtime_credentials", "credential_pool_base_urls", ) @@ -37,11 +38,13 @@ def _bundled_copilot_dirs() -> list[Path]: def inert_reason() -> str | None: """Why this core must not get these profiles, or None when it should.""" - from providers.base import ProviderProfile + from providers import base if bundled := _bundled_copilot_dirs(): return f"this Hermes core still bundles GitHub Copilot ({bundled[0]})" - if missing := [name for name in _REQUIRED_SEAMS if not hasattr(ProviderProfile, name)]: + if not hasattr(base, "PoolRuntimeCredential"): + return "this Hermes core lacks the PoolRuntimeCredential provider SDK" + if missing := [name for name in _REQUIRED_SEAMS if not hasattr(base.ProviderProfile, name)]: return f"this Hermes core lacks the provider seams the plugin needs ({', '.join(missing)})" return None @@ -49,8 +52,8 @@ def inert_reason() -> str | None: def _register() -> bool: reason = inert_reason() if reason: - logger.warning("github-copilot plugin is inactive: %s. Update Hermes; until then the core's " - "own Copilot support is used.", reason) + logger.warning("github-copilot plugin is inactive: %s. Update Hermes before using this " + "plugin revision.", reason) return False from providers import register_provider diff --git a/github-copilot/copilot/__init__.py b/github-copilot/copilot/__init__.py index 413c171..e360023 100644 --- a/github-copilot/copilot/__init__.py +++ b/github-copilot/copilot/__init__.py @@ -55,6 +55,12 @@ def fetch_account_usage( name="copilot", aliases=("github-copilot", "github-models", "github-model", "github"), env_vars=("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"), base_url="https://api.githubcopilot.com", auth_type="copilot", ambient_credentials=True, **RESPONSES_PROFILE_FIELDS, **SETUP_FIELDS, + credential_pool_base_urls=( + "https://api.githubcopilot.com", + "https://api.individual.githubcopilot.com", + "https://api.business.githubcopilot.com", + "https://api.enterprise.githubcopilot.com", + ), hostnames=HOSTNAMES, metadata_hostnames=METADATA_HOSTNAMES, models_dev_id=MODELS_DEV_ID, **CATALOG_FIELDS, **PICKER_FIELDS, **AUTH_ROW_FIELDS, ) diff --git a/github-copilot/copilot/credentials.py b/github-copilot/copilot/credentials.py index 49fcae8..96f30f4 100644 --- a/github-copilot/copilot/credentials.py +++ b/github-copilot/copilot/credentials.py @@ -22,6 +22,7 @@ from typing import Any, Optional from agent.secret_scope import get_secret +from providers.base import PoolRuntimeCredential from utils import atomic_json_write logger = logging.getLogger(__name__) @@ -410,7 +411,7 @@ def _fetch_exchange_with_retry(req, timeout: float, fp: str) -> dict: if attempt < _EXCHANGE_MAX_ATTEMPTS: sleep_s = _EXCHANGE_BACKOFF_BASE_SECONDS * attempt logger.debug("Copilot token exchange attempt %d/%d failed (%s); retrying in %.1fs", - attempt, _EXCHANGE_MAX_ATTEMPTS, exc, sleep_s) + attempt, _EXCHANGE_MAX_ATTEMPTS, type(exc).__name__, sleep_s) time.sleep(sleep_s) _exchange_failure_cache[fp] = time.time() + ( _EXCHANGE_FAILURE_TTL_PERMANENT_SECONDS if permanent_failure @@ -667,6 +668,8 @@ def _pool_token() -> tuple[str, str]: class CopilotCredentialsMixin: """Fills the generic credential seams of ``providers.base.ProviderProfile`` for Copilot.""" + base_url: str # supplied by ProviderProfile in the concrete CopilotProfile + def resolve_api_key_secret(self) -> tuple[str, str]: """The exchanged Copilot token. A home that never chose Copilot gets the raw env token (it still reads as present) and GitHub is not called: provider listings resolve this for every @@ -708,11 +711,8 @@ def runtime_base_url(self, *, api_key: str, default: str, env_url: str) -> str: logger.debug("Copilot base URL resolution fell back to default: %s", exc) return base_url - def prepare_pool_entry(self, entry: Any, api_key: str) -> str: - """A pool row may still carry the RAW GitHub token: the seeder skips the exchange while - copilot is merely discovered (ambient gh login, not in config). Here copilot IS the runtime - target, and a raw token routes to the language-server integrator whose allowlist omits - enterprise-only models (400 model_not_available_for_integrator).""" + def prepare_pool_entry(self, entry: Any, api_key: str) -> str | PoolRuntimeCredential: + """Exchange the selected GitHub grant without changing its durable pool row.""" if not api_key or not validate_copilot_token(api_key)[0]: return api_key # already an exchanged API token api_token, enterprise_base_url = get_copilot_api_token(api_key) @@ -720,10 +720,26 @@ def prepare_pool_entry(self, entry: Any, api_key: str) -> str: if not _is_fine_grained_pat(api_key): _warn_raw_degradation_once(api_key) return api_key - entry.access_token = api_token - if enterprise_base_url: - entry.base_url = enterprise_base_url - return api_token + return PoolRuntimeCredential(api_key=api_token, base_url=enterprise_base_url or self.base_url) + + def refresh_pool_runtime_credentials(self, entry: Any, *, reason: str) -> Optional[PoolRuntimeCredential]: + """Force renewal for this failed row only; never consult ambient credentials or fall back.""" + if reason not in _RUNTIME_REFRESHERS: + return None + raw_token = entry.access_token + if not isinstance(raw_token, str) or not validate_copilot_token(raw_token)[0]: + return None + if _is_fine_grained_pat(raw_token): + return None # never exchanged by design: the PAT is the bearer, nothing to renew + try: + evict_cached_exchanged_token(raw_token) + api_token, _expires_at, base_url = exchange_copilot_token(raw_token) + except Exception as exc: + logger.debug("Copilot pool credential renewal failed (%s)", type(exc).__name__) + return None + if api_token == raw_token: + return None + return PoolRuntimeCredential(api_key=api_token, base_url=base_url or self.base_url) def seed_pool_credentials(self, *, suppressed_sources: frozenset, explicitly_configured: bool) -> list[dict]: @@ -739,24 +755,9 @@ def seed_pool_credentials(self, *, suppressed_sources: frozenset, source_name = f"env:{source}" if source_name in suppressed_sources: # per-source gate BEFORE the network exchange return [] - from .activation import github_calls_allowed - - # Core's ``explicitly_configured`` counts any profile env var, so a GH_TOKEN kept for - # other tools would pass it; the plugin's own check does not (``activation``). - del explicitly_configured - if not github_calls_allowed(): - # Only discovered here (an ambient env token), not selected anywhere: no model is - # routed to it, so the exchange — and its degradation warning on every pool load — - # buys nothing (#114740). Seed the raw token; selecting copilot re-seeds and exchanges. - api_token, enterprise_base_url = token, None - else: - api_token, enterprise_base_url = get_copilot_api_token(token) - # A failed exchange falls back to the RAW token, which the Copilot API routes to the - # "copilot-language-server" integrator whose allowlist omits enterprise-only models - # -> HTTP 400 on every turn. Surface it once. A fine-grained PAT is raw by design. - if api_token == token and not enterprise_base_url and not _is_fine_grained_pat(token): - _warn_raw_degradation_once(token) - return [{"source": source_name, "access_token": api_token, "base_url": enterprise_base_url, + # The durable pool row holds the GitHub grant. Exchange only after selection; + # an expiring bearer must never become the persisted account credential. + return [{"source": source_name, "access_token": token, "base_url": None, "label": source}] except Exception as exc: # health: allow BLE001 -- moved verbatim from core (hermes_cli/copilot_auth.py, credential_pool, client_lifecycle, auth.py) logger.debug("Copilot token seed failed: %s", exc) diff --git a/github-copilot/copilot/wire.py b/github-copilot/copilot/wire.py index 2f6d53a..e5b318f 100644 --- a/github-copilot/copilot/wire.py +++ b/github-copilot/copilot/wire.py @@ -2,7 +2,8 @@ Fills the generic ProviderProfile wire seams (``providers/base.py`` L1 block). Every hook here is pure and answers from the arguments alone, except ``api_mode_for_model`` with an ``api_key``, which -may read the account's cached live catalog to normalize the model id and choose its HTTP wire. +may read the account's cached live catalog to normalize the model id and choose its HTTP wire (a +pooled GitHub grant reads it through its exchanged bearer). """ from __future__ import annotations @@ -99,7 +100,15 @@ class CopilotWireMixin: def api_mode_for_model(self, model: str, *, api_key: str | None = None) -> str | None: # Keyless init/aux/fallback hooks are pure: normalize IDs but never borrow another account's cache. - return model_api_mode(model, catalog=[] if api_key is None else None, api_key=api_key) + if api_key is None: + return model_api_mode(model, catalog=[]) + from .credentials import get_copilot_api_token, validate_copilot_token + + # A pool row reaches this hook with its durable GitHub grant before core prepares the row. Read + # the catalog with the bearer the request will carry (the same cached exchange preparation uses). + if validate_copilot_token(api_key)[0]: + api_key = get_copilot_api_token(api_key)[0] + return model_api_mode(model, api_key=api_key) def client_headers( self, *, base_url: str, api_key: str = "", has_images: bool = False, diff --git a/github-copilot/plugin.yaml b/github-copilot/plugin.yaml index cf1acac..f80e0fb 100644 --- a/github-copilot/plugin.yaml +++ b/github-copilot/plugin.yaml @@ -6,6 +6,8 @@ description: > providers: copilot (the Copilot API with your GitHub account, signed in with `hermes auth add copilot` or a COPILOT_GITHUB_TOKEN / GH_TOKEN / GITHUB_TOKEN token) and copilot-acp (drives your installed GitHub Copilot CLI over ACP). Needs a Hermes core - without bundled Copilot; on older cores it stays inactive. + without bundled Copilot and with the generic credential-pool runtime SDK + (PoolRuntimeCredential, refresh_pool_runtime_credentials, credential_pool_base_urls); + on older cores it stays inactive. author: "Nous Research" homepage: https://github.com/NousResearch/hermes-labs-plugins/tree/main/github-copilot diff --git a/github-copilot/tests/test_copilot_pool_401_recovery.py b/github-copilot/tests/test_copilot_pool_401_recovery.py new file mode 100644 index 0000000..9d1d71e --- /dev/null +++ b/github-copilot/tests/test_copilot_pool_401_recovery.py @@ -0,0 +1,178 @@ +"""A pool-only Copilot sign-in (``hermes auth add copilot``) recovers from an expired exchanged token +through core's runtime resolver and ``AIAgent``, for both provider spellings a session can carry, and +never saves or sends the GitHub grant as a bearer. + +Harness adapted from @recoilburner's review on NousResearch/hermes-agent#154360. Only the network +exchange (``_fetch_exchange_with_retry``), the catalog read and the chat transport are replaced. +""" + +from __future__ import annotations + +import json +import socket +import time +from unittest.mock import patch + +import pytest + +from github_copilot_plugin.copilot import catalog, credentials + +SIGN_IN = "ghu_FAKE" + "0" * 32 +OLD_SIGN_IN = "ghu_FAKEold" + "9" * 29 +STALE = "tid=FAKEstale;exp=1;proxy-ep=proxy.enterprise.githubcopilot.com" +FRESH = "tid=FAKEfresh;exp=9999999999;proxy-ep=proxy.enterprise.githubcopilot.com" +OLD_PASS = "tid=FAKEoldseat;exp=9999999999;proxy-ep=proxy.enterprise.githubcopilot.com" +API = "https://api.enterprise.githubcopilot.com" +MODEL = "claude-opus-5.5" +EXPIRED = "IDE token expired: unauthorized: token expired" +# The canonical name and the profile alias ``/model`` stores (``github-copilot``). +SPELLINGS = ("copilot", "github-copilot") + + +@pytest.fixture(autouse=True) +def catalog_reads(monkeypatch): + """No socket leaves the process; catalog reads are recorded (and find nothing) instead of fetched. + The home selects ``copilot`` in config.yaml, so core's left-core migration would fetch the catalog's + released plugin into it; the hermetic-harness switch keeps that off.""" + def refuse(self, address): + raise OSError(f"network disabled in this test: {address!r}") + + monkeypatch.setattr(socket.socket, "connect", refuse) + monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1") + reads = [] + monkeypatch.setattr(catalog, "fetch_github_model_catalog", + lambda api_key=None, timeout=5.0: reads.append(api_key)) + return reads + + +@pytest.fixture +def exchanges(monkeypatch): + """The first exchange of SIGN_IN hands out STALE (the startup token, expired by the time it is + sent); every later one hands out FRESH; OLD_SIGN_IN gets its own token.""" + calls = [] + + def exchange(req, timeout, fp): + grant = req.get_header("Authorization").split(" ", 1)[1] + calls.append(grant) + token = (STALE if calls.count(SIGN_IN) == 1 else FRESH) if grant == SIGN_IN else OLD_PASS + return {"token": token, "expires_at": time.time() + 86400, "endpoints": {"api": API}} + + monkeypatch.setattr(credentials, "_fetch_exchange_with_retry", exchange) + return calls + + +def _save_rows(home, grants): + rows = [{"id": f"pool-{i}", "label": "seat", "auth_type": "api_key", "priority": i, + "source": "manual:device_code", "access_token": grant, "base_url": "https://api.githubcopilot.com"} + for i, grant in enumerate(grants)] + (home / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {"copilot": rows}})) + (home / "config.yaml").write_text(f"model:\n provider: copilot\n default: {MODEL}\n") + from hermes_cli import config + + config._LOAD_CONFIG_CACHE.clear() + config._RAW_CONFIG_CACHE.clear() + + +def _saved_grants(home): + return [row["access_token"] + for row in json.loads((home / "auth.json").read_text())["credential_pool"]["copilot"]] + + +def _chat(spelling, accepted, turns=1): + """Resolve the runtime the way the gateway does, then run ``turns`` chats on one agent. The chat + API accepts only bearers in ``accepted`` and answers any other with Copilot's expiry 401.""" + import httpx + import openai + + from agent.credential_pool import credential_pool_matches_provider + from hermes_cli.runtime_provider import resolve_runtime_provider + from run_agent import AIAgent + + runtime = resolve_runtime_provider(requested=spelling, target_model=MODEL) + pool = runtime.get("credential_pool") + assert pool is not None and pool.provider == "copilot" + # Capability, not version: a core whose agent drops the pool for this spelling cannot recover. + if not credential_pool_matches_provider(pool, spelling, base_url=runtime["base_url"]): + assert spelling != "copilot" + pytest.skip(f"this core drops the copilot credential pool for the {spelling!r} spelling " + "(credential_pool_matches_provider); needs core's alias binding") + bearers = [] + + def answer(request): + body = json.loads(request.content or b"{}") + if "messages" not in body: + return httpx.Response(404, text="not found") + bearer = request.headers.get("authorization", "").removeprefix("Bearer ") + bearers.append(bearer) + if bearer not in accepted: + return httpx.Response(401, text=EXPIRED) + delta = {"role": "assistant", "content": "ok"} + if body.get("stream"): + chunks = [{"choices": [{"index": 0, "delta": delta, "finish_reason": None}]}, + {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}] + sse = "".join("data: " + json.dumps({"id": "c", "object": "chat.completion.chunk", "created": 0, + "model": MODEL, **c}) + "\n\n" for c in chunks) + return httpx.Response(200, text=sse + "data: [DONE]\n\n", headers={"content-type": "text/event-stream"}) + return httpx.Response(200, json={ + "id": "c", "object": "chat.completion", "created": 0, "model": MODEL, + "choices": [{"index": 0, "message": delta, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}) + + def offline_openai(**kwargs): + return openai.OpenAI(**{**kwargs, "http_client": httpx.Client(transport=httpx.MockTransport(answer))}) + + with patch("agent.process_bootstrap.OpenAI", side_effect=offline_openai): + agent = AIAgent(base_url=runtime["base_url"], model=MODEL, api_key=runtime["api_key"], provider=spelling, + api_mode="chat_completions", quiet_mode=True, skip_context_files=True, skip_memory=True, + enabled_toolsets=[], credential_pool=pool) + replies = [agent.chat(f"hi {turn}") for turn in range(turns)] + return replies, bearers + + +@pytest.mark.parametrize("spelling", SPELLINGS) +@pytest.mark.parametrize("grants", [[SIGN_IN], [SIGN_IN, OLD_SIGN_IN]], ids=["1row", "2rows"]) +def test_expired_token_renews_the_selected_grant_once(hermes_home, exchanges, catalog_reads, spelling, grants): + _save_rows(hermes_home, grants) + + replies, bearers = _chat(spelling, {FRESH, OLD_PASS}, turns=2) + + assert replies == ["ok", "ok"] + assert bearers == [STALE, FRESH, FRESH] + assert exchanges == [SIGN_IN, SIGN_IN] # the startup exchange and one renewal, of the selected grant + assert _saved_grants(hermes_home) == grants + assert not set(grants) & set(bearers + catalog_reads) + + +@pytest.mark.parametrize("spelling", SPELLINGS) +def test_refused_renewed_token_does_not_loop(hermes_home, exchanges, catalog_reads, spelling): + _save_rows(hermes_home, [SIGN_IN]) + + replies, bearers = _chat(spelling, set()) + + assert replies[0] != "ok" + # Startup exchange plus core's capped same-row renewals: the turn ends instead of looping. + assert len(bearers) <= 3 and len(exchanges) <= 4 + assert bearers[0] == STALE and set(bearers[1:]) == {FRESH} and set(exchanges) == {SIGN_IN} + assert _saved_grants(hermes_home) == [SIGN_IN] + assert SIGN_IN not in bearers + catalog_reads + + +@pytest.mark.parametrize("spelling", SPELLINGS) +def test_exchange_outage_never_sends_the_grant(hermes_home, monkeypatch, catalog_reads, spelling): + _save_rows(hermes_home, [SIGN_IN]) + calls = [] + + def exchange(req, timeout, fp): + calls.append(fp) + if len(calls) == 1: + return {"token": STALE, "expires_at": time.time() + 86400, "endpoints": {"api": API}} + raise ValueError("exchange down") + + monkeypatch.setattr(credentials, "_fetch_exchange_with_retry", exchange) + + replies, bearers = _chat(spelling, {FRESH}) + + assert replies[0] != "ok" + assert bearers == [STALE] + assert _saved_grants(hermes_home) == [SIGN_IN] + assert SIGN_IN not in bearers + catalog_reads diff --git a/github-copilot/tests/test_copilot_pool_exchange.py b/github-copilot/tests/test_copilot_pool_exchange.py index f324c24..5e91f11 100644 --- a/github-copilot/tests/test_copilot_pool_exchange.py +++ b/github-copilot/tests/test_copilot_pool_exchange.py @@ -28,7 +28,7 @@ def test_runtime_selected_copilot_exchanges_ambient_pool_token(tmp_path, monkeyp _cfg._RAW_CONFIG_CACHE.clear() monkeypatch.setattr(copilot_credentials, "resolve_copilot_token", lambda: ("ghu_raw_gh_token", "GH_TOKEN")) monkeypatch.setattr(copilot_credentials, "get_copilot_api_token", - lambda tok: ("tid=exchanged;exp=1", "https://api.enterprise.ghe.example")) + lambda tok: ("tid=exchanged;exp=1", "https://api.enterprise.githubcopilot.com")) monkeypatch.setattr(copilot_wire, "model_api_mode", lambda *a, **k: "chat_completions") monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "copilot") @@ -36,4 +36,7 @@ def test_runtime_selected_copilot_exchanges_ambient_pool_token(tmp_path, monkeyp assert resolved["provider"] == "copilot" assert resolved["api_key"] == "tid=exchanged;exp=1" - assert resolved["base_url"].startswith("https://api.enterprise.ghe.example") + assert resolved["base_url"] == "https://api.enterprise.githubcopilot.com" + row = resolved["credential_pool"].entries()[0] + assert row.access_token == "ghu_raw_gh_token" + assert row.runtime_api_key == "tid=exchanged;exp=1" diff --git a/github-copilot/tests/test_plugin_registration.py b/github-copilot/tests/test_plugin_registration.py index 85d9add..18148df 100644 --- a/github-copilot/tests/test_plugin_registration.py +++ b/github-copilot/tests/test_plugin_registration.py @@ -65,14 +65,16 @@ def test_core_that_bundles_copilot_gets_no_registration(tmp_path, monkeypatch, c assert len(warnings) == 1 and "still bundles GitHub Copilot" in warnings[0] -def test_core_without_the_provider_seams_gets_no_registration(monkeypatch, caplog): - monkeypatch.delattr(ProviderProfile, "api_mode_for_model") +@pytest.mark.parametrize("seam", ["api_mode_for_model", "prepare_pool_entry", + "refresh_pool_runtime_credentials", "credential_pool_base_urls"]) +def test_core_without_the_provider_seams_gets_no_registration(monkeypatch, caplog, seam): + monkeypatch.delattr(ProviderProfile, seam) with caplog.at_level(logging.WARNING): module, calls = _fresh_load(monkeypatch) assert module.ACTIVE is False and calls == [] - assert "api_mode_for_model" in caplog.text + assert seam in caplog.text def test_leftover_bytecode_dir_does_not_count_as_bundled(tmp_path, monkeypatch): @@ -86,3 +88,13 @@ def test_leftover_bytecode_dir_does_not_count_as_bundled(tmp_path, monkeypatch): assert module.ACTIVE is True assert calls == ["copilot", "copilot-acp"] + + +def test_core_without_runtime_pair_type_stays_inactive(monkeypatch, caplog): + import providers.base as base + + monkeypatch.delattr(base, "PoolRuntimeCredential") + with caplog.at_level(logging.WARNING): + module, calls = _fresh_load(monkeypatch) + assert module.ACTIVE is False and calls == [] + assert "PoolRuntimeCredential" in caplog.text diff --git a/github-copilot/tests/test_pool_durable_grants.py b/github-copilot/tests/test_pool_durable_grants.py new file mode 100644 index 0000000..45ce029 --- /dev/null +++ b/github-copilot/tests/test_pool_durable_grants.py @@ -0,0 +1,269 @@ +"""Selected Copilot credentials must not replace the durable GitHub grant.""" + +import json +from io import BytesIO + +import pytest + +from agent.credential_pool import load_pool +from hermes_cli import config as cfg, runtime_provider +from github_copilot_plugin.copilot import credentials, wire + + +GRANT = "ghu_fake_pool_grant" +BEARER = "tid=fake_pool_bearer" +URL = "https://api.business.githubcopilot.com" + + +def test_configured_env_pool_seeds_raw_without_exchange(hermes_home, monkeypatch): + (hermes_home / "config.yaml").write_text("model:\n provider: copilot\n default: gpt-4.1\n") + cfg._LOAD_CONFIG_CACHE.clear() + cfg._RAW_CONFIG_CACHE.clear() + monkeypatch.setenv("COPILOT_GITHUB_TOKEN", GRANT) + calls = [] + monkeypatch.setattr(credentials, "get_copilot_api_token", lambda token: (calls.append(token) or BEARER, URL)) + + pool = load_pool("copilot") + + assert calls == [] + assert pool.entries()[0].access_token == GRANT + + +def test_selected_manual_row_stays_raw_after_persist_and_reload(hermes_home, monkeypatch): + (hermes_home / "config.yaml").write_text("model:\n provider: copilot\n default: gpt-4.1\n") + (hermes_home / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {"copilot": [{ + "id": "manual-one", "label": "first", "auth_type": "api_key", "priority": 0, + "source": "manual:device_code", "access_token": GRANT, + "base_url": "https://api.githubcopilot.com"}]}})) + cfg._LOAD_CONFIG_CACHE.clear() + cfg._RAW_CONFIG_CACHE.clear() + monkeypatch.setattr(credentials, "get_copilot_api_token", lambda token: (BEARER, URL)) + monkeypatch.setattr(wire, "model_api_mode", lambda *a, **k: "chat_completions") + + resolved = runtime_provider.resolve_runtime_provider(requested="copilot", target_model="gpt-4.1") + assert resolved["api_key"] == BEARER + assert resolved["base_url"] == URL + pool = resolved["credential_pool"] + pool._persist() + reloaded = load_pool("copilot").entries()[0] + assert (reloaded.id, reloaded.label, reloaded.access_token) == ("manual-one", "first", GRANT) + + +@pytest.mark.parametrize("reason", ["unauthorized", "stale", "auxiliary_unauthorized"]) +def test_failed_manual_row_refresh_exchanges_only_that_grant(hermes_home, monkeypatch, reason): + rows = [ + {"id": "first", "label": "First", "priority": 0, "source": "manual", "auth_type": "api_key", + "access_token": "ghu_fake_other", "base_url": "https://api.githubcopilot.com"}, + {"id": "failed", "label": "Failed", "priority": 1, "source": "manual", "auth_type": "api_key", + "access_token": GRANT, "base_url": "https://api.githubcopilot.com"}, + ] + (hermes_home / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {"copilot": rows}})) + calls = [] + + def exchange(req, timeout): + calls.append(req.get_header("Authorization")) + return BytesIO(json.dumps({"token": BEARER, "expires_at": 4102444800, + "endpoints": {"api": URL}}).encode()) + + monkeypatch.setattr(credentials, "_urlopen_bounded", exchange) + pool = load_pool("copilot") + monkeypatch.setenv("GH_TOKEN", "ghu_fake_ambient") + fp = credentials._token_fingerprint(GRANT) + other_fp = credentials._token_fingerprint("ghu_fake_other") + stale = ("tid=revoked", 4102444800, URL) + credentials._jwt_cache.update({fp: stale, other_fp: stale}) + credentials._save_jwt_to_disk(fp, *stale) + credentials._save_jwt_to_disk(other_fp, *stale) + credentials._exchange_failure_cache.update({fp: 4102444800, other_fp: 4102444800}) + refreshed = pool.try_refresh_runtime_matching( + api_key_hint=GRANT, credential_id="failed", reason=reason) + + assert calls == [f"token {GRANT}"] + assert refreshed is not None + assert refreshed.runtime_api_key == BEARER + assert refreshed.runtime_base_url == URL + assert credentials._jwt_cache[other_fp] == stale + assert credentials._load_jwt_from_disk(other_fp) == stale + assert credentials._exchange_failure_cache[other_fp] == 4102444800 + assert fp not in credentials._exchange_failure_cache + pool._persist() + stored = json.loads((hermes_home / "auth.json").read_text())["credential_pool"]["copilot"] + assert next(row for row in stored if row["id"] == "failed")["access_token"] == GRANT + + +def test_forced_renewal_failure_never_uses_ambient_or_logs_grants(hermes_home, monkeypatch, caplog): + import logging + from agent.credential_pool import PooledCredential, CredentialPool + + row = PooledCredential(id="failed", label="Failed", priority=0, + provider="copilot", auth_type="api_key", + source="manual", access_token=GRANT, + base_url="https://api.githubcopilot.com") + pool = CredentialPool("copilot", [row]) + monkeypatch.setenv("COPILOT_GITHUB_TOKEN", "ghu_fake_ambient") + calls = [] + + def reject(req, timeout): + calls.append(req.get_header("Authorization")) + raise RuntimeError(f"transport accidentally echoed {GRANT}") + + monkeypatch.setattr(credentials, "_urlopen_bounded", reject) + monkeypatch.setattr(credentials.time, "sleep", lambda seconds: None) + with caplog.at_level(logging.DEBUG): + refreshed = pool.try_refresh_runtime_matching( + credential_id=row.id, api_key_hint=GRANT, reason="stale") + + assert calls == [f"token {GRANT}"] * credentials._EXCHANGE_MAX_ATTEMPTS + assert refreshed is None + assert row.runtime_api_key == GRANT + assert GRANT not in caplog.text + assert "ghu_fake_ambient" not in caplog.text + + +@pytest.mark.parametrize("endpoint", [ + "https://api.githubcopilot.com", + "https://api.individual.githubcopilot.com", + "https://api.business.githubcopilot.com", + "https://api.enterprise.githubcopilot.com", +]) +def test_selected_pair_is_transient_for_every_official_origin(monkeypatch, endpoint): + from agent.credential_pool import PooledCredential, CredentialPool + from providers import get_provider_profile + from providers.base import PoolRuntimeCredential + + row = PooledCredential(id="one", label="One", priority=0, provider="copilot", + auth_type="api_key", source="manual", access_token=GRANT, + base_url="https://api.githubcopilot.com") + before = row.to_dict() + monkeypatch.setattr(credentials, "get_copilot_api_token", lambda token: (BEARER, endpoint)) + profile = get_provider_profile("copilot") + result = profile.prepare_pool_entry(row, GRANT) + assert isinstance(result, PoolRuntimeCredential) + assert (result.api_key, result.base_url) == (BEARER, endpoint) + assert row.to_dict() == before + prepared = CredentialPool("copilot", [row]).prepare_runtime_entry(row) + assert (prepared.runtime_api_key, prepared.runtime_base_url) == (BEARER, endpoint) + assert row.to_dict() == before + + +@pytest.mark.parametrize("endpoint", [ + "https://api.enterprise.ghe.example", + "https://api.githubcopilot.com.evil.example", + "http://api.githubcopilot.com", + "https://api.githubcopilot.com/relay", + "https://api.githubcopilot.com:8443", + "https://copilot-api.acme.ghe.com", # GHEC is not a pool origin yet (README § Credential-pool recovery) +]) +def test_foreign_exchange_route_cannot_retarget_pool(monkeypatch, endpoint): + from agent.credential_pool import PooledCredential, CredentialPool + + row = PooledCredential(id="one", label="One", priority=0, provider="copilot", + auth_type="api_key", source="manual", access_token=GRANT, + base_url="https://api.githubcopilot.com") + before = row.to_dict() + monkeypatch.setattr(credentials, "get_copilot_api_token", lambda token: (BEARER, endpoint)) + assert CredentialPool("copilot", [row]).prepare_runtime_entry(row) is None + assert row.to_dict() == before + + +@pytest.mark.parametrize("endpoint", ["https://copilot-api.acme.ghe.com", "https://api.githubcopilot.com.evil.example"]) +def test_renewal_cannot_retarget_pool_to_a_foreign_route(monkeypatch, endpoint): + from agent.credential_pool import PooledCredential, CredentialPool + + row = PooledCredential(id="one", label="One", priority=0, provider="copilot", + auth_type="api_key", source="manual", access_token=GRANT, + base_url="https://api.githubcopilot.com") + before = row.to_dict() + monkeypatch.setattr(credentials, "exchange_copilot_token", lambda token: (BEARER, 4102444800, endpoint)) + pool = CredentialPool("copilot", [row]) + + assert pool.try_refresh_runtime_matching(credential_id="one", api_key_hint=GRANT, reason="unauthorized") is None + assert (row.runtime_api_key, row.runtime_base_url) == (GRANT, "https://api.githubcopilot.com") + assert row.to_dict() == before + + +def test_ghec_env_token_keeps_its_enterprise_endpoint_outside_the_pool(hermes_home, monkeypatch): + """GHEC is not a pool origin yet (README): the documented env setup still reaches its enterprise + endpoint through core's env resolution, and the pooled grant stays raw.""" + ghec = "https://copilot-api.acme.ghe.com" + (hermes_home / "config.yaml").write_text("model:\n provider: copilot\n default: gpt-4.1\n") + cfg._LOAD_CONFIG_CACHE.clear() + cfg._RAW_CONFIG_CACHE.clear() + monkeypatch.setenv("COPILOT_GH_HOST", "acme.ghe.com") + monkeypatch.setenv("COPILOT_API_BASE_URL", ghec) + monkeypatch.setenv("COPILOT_GITHUB_TOKEN", GRANT) + exchanged_at = [] + + def exchange(req, timeout, fp): + exchanged_at.append(req.full_url) + return {"token": BEARER, "expires_at": 4102444800, "endpoints": {"api": ghec}} + + monkeypatch.setattr(credentials, "_fetch_exchange_with_retry", exchange) + monkeypatch.setattr(wire, "model_api_mode", lambda *a, **k: "chat_completions") + + resolved = runtime_provider.resolve_runtime_provider(requested="copilot", target_model="gpt-4.1") + + assert (resolved["api_key"], resolved["base_url"]) == (BEARER, ghec) + assert resolved.get("credential_pool") is None + assert set(exchanged_at) == {"https://api.acme.ghe.com/copilot_internal/v2/token"} + assert load_pool("copilot").entries()[0].access_token == GRANT + before_refresh = len(exchanged_at) + from providers import get_provider_profile + + assert get_provider_profile("copilot").refresh_runtime_credentials(reason="unauthorized") == (BEARER, ghec) + assert len(exchanged_at) == before_refresh + 1 + + +def test_normal_preparation_keeps_same_account_raw_fallback(monkeypatch, caplog): + from agent.credential_pool import PooledCredential, CredentialPool + + row = PooledCredential(id="one", label="One", priority=0, provider="copilot", + auth_type="api_key", source="manual", access_token=GRANT, + base_url="https://api.githubcopilot.com") + calls = [] + monkeypatch.setenv("GH_TOKEN", "ghu_fake_ambient") + monkeypatch.setattr(credentials, "get_copilot_api_token", lambda token: (calls.append(token) or token, None)) + prepared = CredentialPool("copilot", [row]).prepare_runtime_entry(row) + assert calls == [GRANT] + assert prepared.runtime_api_key == GRANT + assert prepared.access_token == GRANT + assert "degraded to RAW token" in caplog.text + + +@pytest.mark.parametrize("reason", ["unauthorized", "stale", "auxiliary_unauthorized"]) +def test_forced_renewal_declines_a_fine_grained_pat_before_any_io(hermes_home, monkeypatch, reason): + """A fine-grained PAT is the bearer itself and is never exchanged: there is nothing to renew.""" + from agent.credential_pool import CredentialPool, PooledCredential + from providers import get_provider_profile + + pat = "github_pat_fake_fine_grained" + row = PooledCredential(id="pat", label="PAT", priority=0, provider="copilot", auth_type="api_key", + source="manual", access_token=pat, base_url="https://api.githubcopilot.com") + pool = CredentialPool("copilot", [row]) + fp = credentials._token_fingerprint(pat) + cached = ("tid=sentinel", 4102444800, URL) + credentials._jwt_cache[fp] = cached + credentials._save_jwt_to_disk(fp, *cached) + credentials._exchange_failure_cache[fp] = 4102444800 + calls = [] + monkeypatch.setattr(credentials, "_urlopen_bounded", lambda req, timeout: calls.append(req.full_url)) + monkeypatch.setattr(credentials, "exchange_copilot_token", lambda *a, **k: calls.append("exchange")) + + assert get_provider_profile("copilot").refresh_pool_runtime_credentials(row, reason=reason) is None + assert pool.try_refresh_runtime_matching(credential_id="pat", api_key_hint=pat, reason=reason) is None + assert calls == [] + assert credentials._jwt_cache[fp] == cached + assert credentials._load_jwt_from_disk(fp) == cached + assert credentials._exchange_failure_cache[fp] == 4102444800 + assert row.access_token == pat and row.runtime_api_key == pat + + +def test_forced_renewal_declines_exchange_that_returns_same_raw_grant(monkeypatch): + from types import SimpleNamespace + from providers import get_provider_profile + + monkeypatch.setattr(credentials, "evict_cached_exchanged_token", lambda token: None) + monkeypatch.setattr(credentials, "exchange_copilot_token", lambda token: (token, 4102444800, None)) + result = get_provider_profile("copilot").refresh_pool_runtime_credentials( + SimpleNamespace(access_token=GRANT), reason="unauthorized") + assert result is None