From d3644736207dde2aa0b45295323afed3cb1041a4 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:09:42 -0700 Subject: [PATCH] refactor(model-providers): fetch_models stubs drop to the ABC; commandcode and AI Gateway catalog GETs go through open_credentialed_url vertex, bedrock and copilot-acp each overrode ProviderProfile.fetch_models with an identical `return None`, and the overrides could not simply be deleted because the base implementation derives a URL from base_url and would GET e.g. bedrock-runtime.../models or acp://copilot/models. ProviderProfile now carries `supports_model_listing` (default True); the base fetch_models returns None before touching the network when it is False, and the three SDK/subprocess-backed profiles set it in their constructors instead of overriding. Separately, two catalog GETs still went through bare urllib.request.urlopen: commandcode's fetch_models and hermes_cli.models._fetch_ai_gateway_models (which sends the AI Gateway bearer). Both now use the redirect-safe open_credentialed_url path (_urlopen_model_catalog_request in models.py, also applied to the unauthenticated fetch_ai_gateway_models for consistency). This is a security behavior change: a cross-origin redirect from either endpoint no longer forwards the Authorization/attribution headers to the redirect target. The AI Gateway tests that patched the global urlopen are repointed at hermes_cli.models._urlopen_model_catalog_request (the seam tests/hermes_cli/test_models.py already uses), the commandcode test patches open_credentialed_url on the plugin module, and two invariant tests pin the no-network guard and the bearer routing. --- hermes_cli/models.py | 4 ++-- plugins/model-providers/bedrock/__init__.py | 7 +------ .../model-providers/commandcode/__init__.py | 3 ++- .../model-providers/copilot-acp/__init__.py | 7 +------ plugins/model-providers/vertex/__init__.py | 7 +------ providers/base.py | 4 ++++ tests/hermes_cli/test_ai_gateway_models.py | 20 ++++++++++++++----- .../test_commandcode_profile.py | 4 +--- tests/providers/test_fetch_models_base_url.py | 13 ++++++++++++ 9 files changed, 40 insertions(+), 29 deletions(-) diff --git a/hermes_cli/models.py b/hermes_cli/models.py index d70dc09fcd..0c662667b3 100644 --- a/hermes_cli/models.py +++ b/hermes_cli/models.py @@ -637,7 +637,7 @@ def fetch_ai_gateway_models( from hermes_constants import AI_GATEWAY_BASE_URL fallback = list(VERCEL_AI_GATEWAY_MODELS) - live = _fetch_live_catalog_index(f"{AI_GATEWAY_BASE_URL.rstrip('/')}/models", timeout, urllib.request.urlopen) + live = _fetch_live_catalog_index(f"{AI_GATEWAY_BASE_URL.rstrip('/')}/models", timeout, _urlopen_model_catalog_request) if live is None: return list(_ai_gateway_catalog_cache or fallback) _, live_by_id = live @@ -2481,7 +2481,7 @@ def _fetch_ai_gateway_models(timeout: float = 5.0) -> Optional[list[str]]: headers = {"Authorization": f"Bearer {api_key}", "User-Agent": _HERMES_USER_AGENT} try: url = base_url.rstrip("/") + "/models" - data = _get_json(url, timeout=timeout, headers=headers, opener=urllib.request.urlopen) + data = _get_json(url, timeout=timeout, headers=headers) return [ m["id"] for m in data.get("data", []) if m.get("id") and m.get("type") == "language" and "tool-use" in (m.get("tags") or [])] diff --git a/plugins/model-providers/bedrock/__init__.py b/plugins/model-providers/bedrock/__init__.py index f1d3194901..e461307b00 100644 --- a/plugins/model-providers/bedrock/__init__.py +++ b/plugins/model-providers/bedrock/__init__.py @@ -7,17 +7,12 @@ from providers.base import ProviderProfile class BedrockProfile(ProviderProfile): """AWS Bedrock — no REST /v1/models endpoint; uses AWS SDK.""" - def fetch_models( - self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0 - ) -> list[str] | None: - """Bedrock model listing requires AWS SDK, not a REST call.""" - return None - bedrock = BedrockProfile( name="bedrock", aliases=("aws", "aws-bedrock", "amazon-bedrock", "amazon"), api_mode="bedrock_converse", env_vars=(), # AWS SDK credentials — not env vars base_url="https://bedrock-runtime.us-east-1.amazonaws.com", auth_type="aws_sdk", + supports_model_listing=False, # listing goes through the AWS SDK, not a REST call ) register_provider(bedrock) diff --git a/plugins/model-providers/commandcode/__init__.py b/plugins/model-providers/commandcode/__init__.py index 37bfff5b2f..0f57962c25 100644 --- a/plugins/model-providers/commandcode/__init__.py +++ b/plugins/model-providers/commandcode/__init__.py @@ -6,6 +6,7 @@ import json import logging import urllib.request +from hermes_cli.urllib_security import open_credentialed_url from providers import register_provider from providers.base import ProviderProfile, _profile_user_agent @@ -30,7 +31,7 @@ class CommandCodeProfile(ProviderProfile): req = urllib.request.Request(models_url) req.add_header("Accept", "application/json") req.add_header("User-Agent", _profile_user_agent()) - with urllib.request.urlopen(req, timeout=timeout) as resp: + with open_credentialed_url(req, timeout=timeout) as resp: data = json.loads(resp.read().decode()) return [m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m] except Exception as exc: diff --git a/plugins/model-providers/copilot-acp/__init__.py b/plugins/model-providers/copilot-acp/__init__.py index 0f3b87ca1d..1be440c4d1 100644 --- a/plugins/model-providers/copilot-acp/__init__.py +++ b/plugins/model-providers/copilot-acp/__init__.py @@ -21,12 +21,6 @@ class CopilotACPProfile(ProviderProfile): return CopilotACPClient(**client_kwargs) - def fetch_models( - self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0 - ) -> list[str] | None: - """Model listing is handled by the ACP subprocess.""" - return None - copilot_acp = CopilotACPProfile( name="copilot-acp", aliases=("github-copilot-acp", "copilot-acp-agent"), @@ -34,6 +28,7 @@ copilot_acp = CopilotACPProfile( env_vars=(), # Managed by ACP subprocess base_url="acp://copilot", # ACP internal scheme auth_type="external_process", + supports_model_listing=False, # model listing is handled by the ACP subprocess # How to launch the CLI; env var names predate this profile (formerly hardcoded in # hermes_cli/auth.py), so existing setups keep working. process_command="copilot", diff --git a/plugins/model-providers/vertex/__init__.py b/plugins/model-providers/vertex/__init__.py index 51fe68ca41..5227f6bf84 100644 --- a/plugins/model-providers/vertex/__init__.py +++ b/plugins/model-providers/vertex/__init__.py @@ -22,18 +22,13 @@ class VertexProfile(ProviderProfile): thinking_config = _snake_case_gemini_thinking_config(raw) if raw else None return {"extra_body": {"google": {"thinking_config": thinking_config}}} if thinking_config else {} - def fetch_models( - self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0 - ) -> list[str] | None: - """No ``/models`` route on the OpenAI-compat endpoint; setup ships a curated list.""" - return None - vertex = VertexProfile( name="vertex", aliases=("google-vertex", "vertex-ai", "gcp-vertex"), api_mode="chat_completions", env_vars=(), # OAuth2 via service account / ADC — not a static key env var base_url="https://aiplatform.googleapis.com", # real base_url computed at runtime auth_type="vertex", default_aux_model="google/gemini-3.6-flash", + supports_model_listing=False, # no /models route on the OpenAI-compat endpoint; setup ships a curated list ) register_provider(vertex) diff --git a/providers/base.py b/providers/base.py index b509d36f5a..0941c5d8d7 100644 --- a/providers/base.py +++ b/providers/base.py @@ -55,6 +55,8 @@ class ProviderProfile: models_url: str = "" # explicit models endpoint; falls back to {base_url}/models auth_type: str = "api_key" # api_key|oauth_device_code|oauth_external|copilot|aws_sdk supports_health_check: bool = True # False → doctor skips /models probe for this provider + # False → fetch_models returns None without a network call (catalog comes from an SDK/subprocess). + supports_model_listing: bool = True # ── Vision support ──────────────────────────────────────── # True when the provider's API accepts image content inside @@ -300,6 +302,8 @@ class ProviderProfile: Callers must always fall back to the static _PROVIDER_MODELS list when this returns None. """ + if not self.supports_model_listing: + return None caller_base = (base_url or "").strip() effective_base = caller_base or self.base_url custom_base = bool(caller_base) and ( diff --git a/tests/hermes_cli/test_ai_gateway_models.py b/tests/hermes_cli/test_ai_gateway_models.py index b08c98d192..7c16f5ce56 100644 --- a/tests/hermes_cli/test_ai_gateway_models.py +++ b/tests/hermes_cli/test_ai_gateway_models.py @@ -94,7 +94,7 @@ def test_fetch_ai_gateway_models_filters_against_live_catalog(): for mid in live_ids ] } - with patch("urllib.request.urlopen", return_value=_mock_urlopen(payload)): + with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen(payload)): result = fetch_ai_gateway_models(force_refresh=True) assert [mid for mid, _ in result] == live_ids @@ -111,7 +111,7 @@ def test_fetch_ai_gateway_models_tags_free_models(): {"id": second_id, "pricing": {"input": "0", "output": "0"}}, ] } - with patch("urllib.request.urlopen", return_value=_mock_urlopen(payload)): + with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen(payload)): result = fetch_ai_gateway_models(force_refresh=True) by_id = dict(result) @@ -129,7 +129,7 @@ def test_free_moonshot_model_auto_promoted_to_top_even_if_not_curated(): {"id": unlisted_free_moonshot, "pricing": {"input": "0", "output": "0"}}, ] } - with patch("urllib.request.urlopen", return_value=_mock_urlopen(payload)): + with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen(payload)): result = fetch_ai_gateway_models(force_refresh=True) assert result[0] == (unlisted_free_moonshot, "recommended") @@ -145,7 +145,7 @@ def test_paid_moonshot_does_not_get_auto_promoted(): {"id": "moonshotai/some-paid-variant", "pricing": {"input": "0.001", "output": "0.002"}}, ] } - with patch("urllib.request.urlopen", return_value=_mock_urlopen(payload)): + with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen(payload)): result = fetch_ai_gateway_models(force_refresh=True) assert result[0][0] == first_curated @@ -153,6 +153,16 @@ def test_paid_moonshot_does_not_get_auto_promoted(): def test_fetch_ai_gateway_models_falls_back_on_error(): _reset_caches() - with patch("urllib.request.urlopen", side_effect=OSError("network")): + with patch("hermes_cli.models._urlopen_model_catalog_request", side_effect=OSError("network")): result = fetch_ai_gateway_models(force_refresh=True) assert result == list(VERCEL_AI_GATEWAY_MODELS) + + +def test_fetch_ai_gateway_models_routes_bearer_through_catalog_opener(monkeypatch): + """The keyed catalog GET carries the AI Gateway bearer, so it must go through the + redirect-safe catalog opener rather than bare urlopen (which forwards headers cross-origin).""" + monkeypatch.setenv("AI_GATEWAY_API_KEY", "gw-secret") + with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen({"data": []})) as opener: + assert models_module._fetch_ai_gateway_models() == [] + req = opener.call_args.args[0] + assert req.get_header("Authorization") == "Bearer gw-secret" diff --git a/tests/plugins/model_providers/test_commandcode_profile.py b/tests/plugins/model_providers/test_commandcode_profile.py index 7ae3f2953e..dd7537e19f 100644 --- a/tests/plugins/model_providers/test_commandcode_profile.py +++ b/tests/plugins/model_providers/test_commandcode_profile.py @@ -353,9 +353,7 @@ class TestCommandCodeBaseUrlOverride: captured["url"] = req.full_url return _FakeResp() - with mock_patch.object( - cc_mod.urllib.request, "urlopen", side_effect=fake_urlopen - ): + with mock_patch.object(cc_mod, "open_credentialed_url", side_effect=fake_urlopen): result = commandcode_profile.fetch_models( api_key="k", base_url=cc_mod._COMMANDCODE_BASE + "/" ) diff --git a/tests/providers/test_fetch_models_base_url.py b/tests/providers/test_fetch_models_base_url.py index 59f11fecb5..edbd5ed301 100644 --- a/tests/providers/test_fetch_models_base_url.py +++ b/tests/providers/test_fetch_models_base_url.py @@ -210,3 +210,16 @@ class TestModelPickerBaseUrlIntegration: mock_profile.fetch_models.assert_called_once() call_kwargs = mock_profile.fetch_models.call_args assert call_kwargs.kwargs.get("base_url") == "https://custom.proxy.com" + + +def test_profiles_without_model_listing_never_hit_the_network(): + """SDK/subprocess-backed profiles (bedrock, vertex, copilot-acp) still carry a base_url the + generic fetch_models would happily GET ``/models`` against; the flag must short-circuit first.""" + from providers import list_providers + + flagged = [p for p in list_providers() if not p.supports_model_listing] + assert {p.name for p in flagged} >= {"bedrock", "vertex", "copilot-acp"} + with patch("hermes_cli.urllib_security.open_credentialed_url") as opener: + for profile in flagged: + assert profile.fetch_models(api_key="k", base_url=profile.base_url) is None, profile.name + opener.assert_not_called()