Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

fix(security): guard provider endpoint overrides and loopback proxy routing (#1246)

Ilia Alshanetsky627def1c85a8
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index 88e5fd8a..2b54c26c 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -444,6 +444,24 @@ An explicit `--register` wins over `LAST30DAYS_REGISTER`; the environment/config
When you invoke `/last30days` from Claude Code, Codex, or Gemini, the host model **is** the reasoning provider for plan + synthesis - you don't need any of the keys above unless you also run the script headlessly (cron, CI, watchlist).
+### Provider endpoint overrides
+
+Point a provider at a gateway (LiteLLM, an enterprise proxy, a self-hosted OpenAI-compatible server) without a code change:
+
+| Var | Default |
+| --- | --- |
+| `OPENAI_BASE_URL` | `https://api.openai.com/v1/responses` |
+| `XAI_BASE_URL` | `https://api.x.ai/v1/responses` |
+| `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1/chat/completions` |
+
+These redirect the request that carries the provider's `Authorization: Bearer <key>` header, so they are a credential boundary, not just a URL setting:
+
+- **`https://` is required for remote hosts.** An `http://` override to anything other than loopback is refused with a stderr warning and the vendor endpoint is used instead - otherwise the API key would go over the wire in cleartext.
+- **`http://` on loopback is allowed** (`localhost`, `127.0.0.0/8`, `::1`) so a local gateway or SSH tunnel keeps working. These provider requests bypass HTTP proxy settings for the request, keeping the bearer token on the local connection.
+- A host or API root ending in a version segment (for example, `/v1` or `/api/v1`) gets the provider's route appended. A complete custom gateway route is used unchanged, including its query string.
+- **`--preflight` reports all three** under `endpoint_overrides` / `ignored_endpoint_overrides`, so you can see before a run whether a config file is redirecting a key. Rejected values appear only by variable name, never by URL or embedded credentials.
+- A per-project `.claude/last30days.env` can set them only when project config is trusted (`LAST30DAYS_TRUST_PROJECT_CONFIG=1`); untrusted project files are ignored and listed by `--preflight`.
+
---
## Web search backend priority
diff --git a/changelog.d/+provider-endpoint-override-guard.security.md b/changelog.d/+provider-endpoint-override-guard.security.md
new file mode 100644
index 00000000..b81e4f94
--- /dev/null
+++ b/changelog.d/+provider-endpoint-override-guard.security.md
@@ -0,0 +1 @@
+Provider endpoint overrides (`OPENAI_BASE_URL`, `XAI_BASE_URL`, `OPENROUTER_BASE_URL`) now reject remote cleartext `http://` targets and use the vendor endpoint instead. Rejection warnings omit the configured URL so embedded credentials cannot leak to stderr. Loopback `http://` overrides still work for local gateways (LiteLLM, Ollama, SSH tunnels) and bypass configured HTTP proxies so the bearer token stays on the local connection. `--preflight` already listed all three override keys; it now marks rejected values as ignored rather than active and reports only the variable names.
diff --git a/skills/last30days/scripts/lib/http.py b/skills/last30days/scripts/lib/http.py
index f09fb543..93724783 100644
--- a/skills/last30days/scripts/lib/http.py
+++ b/skills/last30days/scripts/lib/http.py
@@ -124,15 +124,19 @@ class _StripAuthOnCrossOriginRedirect(urllib.request.HTTPRedirectHandler):
_opener = urllib.request.build_opener(_StripAuthOnCrossOriginRedirect)
+_direct_opener = urllib.request.build_opener(
+ urllib.request.ProxyHandler({}), _StripAuthOnCrossOriginRedirect
+)
_DEFAULT_URLOPEN = urllib.request.urlopen
-def _open_request(req, timeout):
+def _open_request(req, timeout, *, bypass_proxy=False):
"""Honor test patches of urllib.request.urlopen; otherwise use the strip opener."""
current = urllib.request.urlopen
if current is not _DEFAULT_URLOPEN:
return current(req, timeout=timeout)
- return _opener.open(req, timeout=timeout)
+ opener = _direct_opener if bypass_proxy else _opener
+ return opener.open(req, timeout=timeout)
def open_request(req, timeout):
@@ -777,6 +781,7 @@ def request(
deadline_monotonic: float | None = None,
cancel: threading.Event | None = None,
owned_get: bool = False,
+ bypass_proxy: bool = False,
) -> Union[Dict[str, Any], str]:
"""Make an HTTP request and return JSON response.
@@ -795,6 +800,7 @@ def request(
attempts and retry delays.
owned_get: Run GET transport in a child that is killed and reaped at
its deadline. Requires deadline_monotonic; other methods are refused.
+ bypass_proxy: Use a direct connection for this request and its redirects.
Returns:
Parsed JSON response as dict, or raw text string if raw=True.
@@ -806,6 +812,8 @@ def request(
raise ValueError("owned transport requires a bodyless GET")
if owned_get and deadline_monotonic is None:
raise ValueError("owned GET requires an operation deadline")
+ if owned_get and bypass_proxy:
+ raise ValueError("owned GET does not support proxy bypass")
headers = headers or {}
headers.setdefault("User-Agent", USER_AGENT)
@@ -883,7 +891,11 @@ def request(
request_timeout: float,
) -> tuple[int, str | None, urllib.error.HTTPError | None]:
try:
- with _open_request(req, request_timeout) as response:
+ transport = (
+ _open_request(req, request_timeout, bypass_proxy=True)
+ if bypass_proxy else _open_request(req, request_timeout)
+ )
+ with transport as response:
return response.status, response.read().decode('utf-8'), None
except urllib.error.HTTPError as error:
# Error bodies can stall just like successful bodies. Read both
diff --git a/skills/last30days/scripts/lib/permission_preflight.py b/skills/last30days/scripts/lib/permission_preflight.py
index e9a9c1be..201cb799 100644
--- a/skills/last30days/scripts/lib/permission_preflight.py
+++ b/skills/last30days/scripts/lib/permission_preflight.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Any
-from . import env
+from . import env, providers as provider_endpoints
ENDPOINT_OVERRIDE_KEYS = {
@@ -113,10 +113,22 @@ def build(
},
}
- active_endpoint_overrides = sorted(
- key for key in ENDPOINT_OVERRIDE_KEYS if config.get(key)
+ active_endpoint_overrides: list[str] = []
+ rejected_provider_overrides: list[str] = []
+ for key in sorted(ENDPOINT_OVERRIDE_KEYS):
+ value = str(config.get(key) or "").strip()
+ if not value:
+ continue
+ if (
+ key in provider_endpoints.PROVIDER_BASE_URL_KEYS
+ and not provider_endpoints.allowed_base_url_override(value)
+ ):
+ rejected_provider_overrides.append(key)
+ else:
+ active_endpoint_overrides.append(key)
+ ignored_endpoint_overrides = sorted(
+ set(diagnose.get("ignored_endpoint_overrides") or []) | set(rejected_provider_overrides)
)
- ignored_endpoint_overrides = sorted(diagnose.get("ignored_endpoint_overrides") or [])
external_commands = {
name: {"status": _status(bool(available))}
for name, available in sorted((diagnose.get("external_commands") or {}).items())
@@ -135,6 +147,12 @@ def build(
+ _format_names(templated_keys)
+ ". Replace each with a real value or remove it."
)
+ if rejected_provider_overrides:
+ action_items.append(
+ "Provider endpoint override(s) ignored: "
+ + _format_names(rejected_provider_overrides)
+ + ". Use HTTPS, or HTTP on loopback."
+ )
return {
"status": "action_needed" if action_items else "ready",
diff --git a/skills/last30days/scripts/lib/perplexity.py b/skills/last30days/scripts/lib/perplexity.py
index 5e5cac8f..ee46103f 100644
--- a/skills/last30days/scripts/lib/perplexity.py
+++ b/skills/last30days/scripts/lib/perplexity.py
@@ -1078,12 +1078,14 @@ def _openrouter_sonar_search(
}
_log(f"Querying OpenRouter {model} for '{query}' ({from_date} to {to_date})")
# Honor OPENROUTER_BASE_URL like the planner/rerank client does (providers.py).
+ url = providers.resolve_endpoint("OPENROUTER_BASE_URL", OPENROUTER_URL)
data = http.post(
- providers.resolve_endpoint("OPENROUTER_BASE_URL", OPENROUTER_URL),
+ url,
payload,
headers=headers,
timeout=120 if deep else 30,
retries=1,
+ bypass_proxy=providers.is_loopback_http_endpoint(url),
)
choices = data.get("choices")
diff --git a/skills/last30days/scripts/lib/providers.py b/skills/last30days/scripts/lib/providers.py
index 30a1a475..6285743e 100644
--- a/skills/last30days/scripts/lib/providers.py
+++ b/skills/last30days/scripts/lib/providers.py
@@ -2,11 +2,13 @@
from __future__ import annotations
+import ipaddress
import json
import os
import re
import sys
from typing import Any
+from urllib.parse import urlsplit, urlunsplit
from . import env, http, schema
@@ -24,6 +26,63 @@ OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
# constant is suffix-free. If GEMINI_FLASH_LITE moves to a non-preview stable ID,
# double-check that OpenRouter's slug still maps to the same upstream model.
OPENROUTER_DEFAULT = "google/gemini-3.1-flash-lite-preview"
+PROVIDER_BASE_URL_KEYS = frozenset({"OPENAI_BASE_URL", "XAI_BASE_URL", "OPENROUTER_BASE_URL"})
+
+
+def _is_loopback(host: str) -> bool:
+ """True for hosts that never leave the machine."""
+ if host == "localhost":
+ return True
+ try:
+ return ipaddress.ip_address(host).is_loopback
+ except ValueError:
+ return False
+
+
+def allowed_base_url_override(value: str) -> bool:
+ try:
+ parts = urlsplit(value)
+ host = parts.hostname
+ except ValueError:
+ return False
+ return bool(host) and (
+ parts.scheme == "https" or (parts.scheme == "http" and _is_loopback(host))
+ )
+
+
+def is_loopback_http_endpoint(url: str) -> bool:
+ parts = urlsplit(url)
+ return parts.scheme == "http" and _is_loopback(parts.hostname or "")
+
+
+def base_url_override(key: str, default: str) -> str:
+ """Resolve a provider base-URL override, refusing cleartext remote hosts.
+
+ Every provider resolves its endpoint through here so one guard covers both
+ ways a value arrives: the process environment, and
+ ``_propagate_config_to_environ`` pushing a `.env` value into os.environ.
+
+ A base-URL override redirects the request that carries the provider's bearer
+ token, so an `http://` override to a remote host would put the API key on
+ the wire in cleartext. That is refused and the built-in vendor endpoint is
+ used instead - failing closed protects the credential, and the warning makes
+ the drop visible instead of leaving the user to wonder why their gateway is
+ being bypassed. Loopback is the one legitimate `http://` case (a local
+ LiteLLM/Ollama gateway or an SSH tunnel never leaves the machine), so it is
+ allowed.
+ """
+ raw = (os.environ.get(key) or "").strip()
+ if not raw:
+ return default
+ if allowed_base_url_override(raw):
+ return raw
+ sys.stderr.write(
+ f"[last30days] WARNING: ignoring {key} - a provider endpoint override "
+ "must be https:// (http:// is allowed only on localhost), otherwise the API "
+ f"key would be sent in cleartext. Using {default} instead.\n"
+ )
+ sys.stderr.flush()
+ return default
_ENDPOINT_PATHS = {
@@ -41,17 +100,19 @@ def resolve_endpoint(env_var: str, default_url: str) -> str:
path. This module historically required the full endpoint URL instead, so a
value copied from a provider's setup guide POSTed to the API root and failed.
- Accept both forms: an API root gets the endpoint path appended, and a value
- that already ends with the endpoint path is used unchanged.
+ Accept both forms: a host or versioned API root gets the endpoint path
+ appended, and a complete gateway route is used unchanged. Query strings
+ stay after the path in either form.
"""
- override = os.environ.get(env_var, "").strip()
- if not override:
+ override = base_url_override(env_var, default_url)
+ if override == default_url:
return default_url
- override = override.rstrip("/")
- path = _ENDPOINT_PATHS[default_url]
- if override.endswith(path):
- return override
- return override + path
+ parts = urlsplit(override)
+ root_path = parts.path.rstrip("/")
+ last_segment = root_path.rsplit("/", 1)[-1]
+ if not root_path or re.fullmatch(r"v\d+(?:beta\d*)?", last_segment):
+ return urlunsplit(parts._replace(path=root_path + _ENDPOINT_PATHS[default_url]))
+ return override
class ReasoningClient:
@@ -146,14 +207,16 @@ class OpenAIClient(ReasoningClient):
"input": prompt,
"temperature": 0,
}
+ endpoint = resolve_endpoint("OPENAI_BASE_URL", OPENAI_RESPONSES_URL)
response = http.post(
- resolve_endpoint("OPENAI_BASE_URL", OPENAI_RESPONSES_URL),
+ endpoint,
payload,
headers={
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
},
timeout=90,
+ bypass_proxy=is_loopback_http_endpoint(endpoint),
)
return extract_openai_text(response)
@@ -177,14 +240,16 @@ class XAIClient(ReasoningClient):
"model": model,
"input": [{"role": "user", "content": prompt}],
}
+ endpoint = resolve_endpoint("XAI_BASE_URL", XAI_RESPONSES_URL)
response = http.post(
- resolve_endpoint("XAI_BASE_URL", XAI_RESPONSES_URL),
+ endpoint,
payload,
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
},
timeout=90,
+ bypass_proxy=is_loopback_http_endpoint(endpoint),
)
return extract_openai_text(response)
@@ -209,14 +274,16 @@ class OpenRouterClient(ReasoningClient):
"messages": [{"role": "user", "content": prompt}],
"temperature": 0,
}
+ endpoint = resolve_endpoint("OPENROUTER_BASE_URL", OPENROUTER_URL)
response = http.post(
- resolve_endpoint("OPENROUTER_BASE_URL", OPENROUTER_URL),
+ endpoint,
payload,
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
},
timeout=90,
+ bypass_proxy=is_loopback_http_endpoint(endpoint),
)
return extract_openai_text(response)
diff --git a/skills/last30days/scripts/lib/xai_x.py b/skills/last30days/scripts/lib/xai_x.py
index bac0cd17..daf5bbf3 100644
--- a/skills/last30days/scripts/lib/xai_x.py
+++ b/skills/last30days/scripts/lib/xai_x.py
@@ -144,6 +144,7 @@ def search_x(
url, payload, headers=headers, timeout=timeout,
retries=1, deadline_monotonic=deadline_monotonic,
cancel=cancel,
+ bypass_proxy=providers.is_loopback_http_endpoint(url),
)
diff --git a/tests/test_permission_preflight.py b/tests/test_permission_preflight.py
index 320c96bf..8ec4571a 100644
--- a/tests/test_permission_preflight.py
+++ b/tests/test_permission_preflight.py
@@ -211,6 +211,35 @@ def test_cli_preflight_propagates_file_endpoint_overrides(tmp_path, monkeypatch,
)
+def test_cli_preflight_rejects_file_override_without_leaking_it(tmp_path, monkeypatch, capsys):
+ secret = "dummy-secret-do-not-report"
+ config_file = tmp_path / ".env"
+ config_file.write_text(
+ f"OPENROUTER_BASE_URL=http://{secret}@gateway.example/v1?token={secret}\n",
+ encoding="utf-8",
+ )
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(env, "CONFIG_FILE", config_file)
+ for key in ("OPENAI_BASE_URL", "XAI_BASE_URL", "OPENROUTER_BASE_URL"):
+ monkeypatch.setenv(key, "")
+ monkeypatch.setattr(sys, "argv", ["last30days.py", "--preflight", "--emit=json"])
+
+ with mock.patch.object(env, "_load_keychain", return_value={}), \
+ mock.patch.object(env, "_load_pass", return_value={}):
+ assert cli.main() == 0
+
+ captured = capsys.readouterr()
+ preflight = json.loads(captured.out)
+ assert preflight["status"] == "action_needed"
+ assert preflight["network"]["endpoint_overrides"] == []
+ assert preflight["network"]["ignored_endpoint_overrides"] == ["OPENROUTER_BASE_URL"]
+ assert secret not in captured.out + captured.err
+ assert providers.resolve_endpoint("OPENROUTER_BASE_URL", providers.OPENROUTER_URL) == (
+ providers.OPENROUTER_URL
+ )
+ assert secret not in capsys.readouterr().err
+
+
def test_diagnose_uses_preflight_endpoint_override_key_set():
ignored_keys = sorted(permission_preflight.ENDPOINT_OVERRIDE_KEYS) + ["UNRELATED_KEY"]
diag = pipeline.diagnose(
diff --git a/tests/test_provider_base_url_guard.py b/tests/test_provider_base_url_guard.py
new file mode 100644
index 00000000..5efbfabf
--- /dev/null
+++ b/tests/test_provider_base_url_guard.py
@@ -0,0 +1,105 @@
+"""Provider endpoint overrides must never carry an API key over cleartext.
+
+A base-URL override redirects the request that holds the provider's bearer
+token, so the guard in providers.base_url_override is a credential control, not
+a cosmetic URL check. These tests pin the three shapes that matter: https is
+honored, remote http is refused, and loopback http stays usable for a local
+gateway.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from lib import permission_preflight, providers
+
+
+OVERRIDES = [
+ ("OPENAI_BASE_URL", providers.OPENAI_RESPONSES_URL),
+ ("XAI_BASE_URL", providers.XAI_RESPONSES_URL),
+ ("OPENROUTER_BASE_URL", providers.OPENROUTER_URL),
+]
+
+
[email protected]("key,default", OVERRIDES)
+def test_unset_override_uses_vendor_endpoint(key, default, monkeypatch):
+ monkeypatch.delenv(key, raising=False)
+ assert providers.base_url_override(key, default) == default
+
+
[email protected]("key,default", OVERRIDES)
+def test_https_override_is_honored(key, default, monkeypatch):
+ monkeypatch.setenv(key, "https://gateway.internal/v1/responses")
+ assert providers.base_url_override(key, default) == "https://gateway.internal/v1/responses"
+
+
+ "value",
+ [
+ "http://attacker.example/v1",
+ "http://10.0.0.5:8080/v1",
+ "ftp://attacker.example/v1",
+ "//attacker.example/v1",
+ "attacker.example/v1",
+ ],
+)
+def test_cleartext_or_schemeless_remote_override_is_refused(value, monkeypatch, capsys):
+ monkeypatch.setenv("OPENAI_BASE_URL", value)
+ resolved = providers.base_url_override("OPENAI_BASE_URL", providers.OPENAI_RESPONSES_URL)
+ assert resolved == providers.OPENAI_RESPONSES_URL
+ # The drop must be visible, and the warning must not be the leak itself.
+ err = capsys.readouterr().err
+ assert "OPENAI_BASE_URL" in err
+ assert "cleartext" in err
+
+
+def test_rejected_override_does_not_print_embedded_credentials(monkeypatch, capsys):
+ secret = "dummy-secret-do-not-log"
+ monkeypatch.setenv(
+ "OPENAI_BASE_URL",
+ f"http://{secret}@gateway.example/path/{secret}?token={secret}",
+ )
+
+ assert providers.base_url_override("OPENAI_BASE_URL", providers.OPENAI_RESPONSES_URL) == (
+ providers.OPENAI_RESPONSES_URL
+ )
+ warning = capsys.readouterr().err
+ assert "OPENAI_BASE_URL" in warning
+ assert "cleartext" in warning
+ assert secret not in warning
+
+
+def test_rejected_override_is_not_reported_as_active(monkeypatch):
+ secret = "dummy-secret-do-not-report"
+ rejected = f"http://gateway.example/v1?token={secret}"
+ monkeypatch.setenv("OPENROUTER_BASE_URL", rejected)
+ preflight = permission_preflight.build(
+ {"OPENROUTER_BASE_URL": rejected},
+ {"ignored_endpoint_overrides": [], "safe": True},
+ )
+
+ assert preflight["network"]["endpoint_overrides"] == []
+ assert preflight["network"]["ignored_endpoint_overrides"] == ["OPENROUTER_BASE_URL"]
+ assert preflight["status"] == "action_needed"
+ assert secret not in str(preflight)
+
+
+ "value",
+ [
+ "http://localhost:4000/v1",
+ "http://127.0.0.1:4000/v1",
+ "http://127.0.0.2:4000/v1",
+ "http://[::1]:4000/v1",
+ ],
+)
+def test_loopback_http_override_stays_usable(value, monkeypatch):
+ """A local LiteLLM/Ollama gateway never puts the key on the wire."""
+ monkeypatch.setenv("OPENAI_BASE_URL", value)
+ assert providers.base_url_override("OPENAI_BASE_URL", providers.OPENAI_RESPONSES_URL) == value
+
+
[email protected]("key,_default", OVERRIDES)
+def test_every_propagated_override_is_preflight_reportable(key, _default):
+ """Each provider override key remains in the preflight endpoint inventory."""
+ assert key in permission_preflight.ENDPOINT_OVERRIDE_KEYS
diff --git a/tests/test_provider_loopback_proxy.py b/tests/test_provider_loopback_proxy.py
new file mode 100644
index 00000000..93fe783c
--- /dev/null
+++ b/tests/test_provider_loopback_proxy.py
@@ -0,0 +1,163 @@
+"""Loopback provider endpoints must not send bearer tokens through a proxy."""
+
+from __future__ import annotations
+
+import http.server as stdlib_http
+import json
+import threading
+import urllib.request
+
+import pytest
+
+from lib import http, perplexity, providers, xai_x
+
+
+def serve():
+ running = []
+
+ def start(*, reply="direct", payload=None, redirect_to=None):
+ requests = []
+
+ class Handler(stdlib_http.BaseHTTPRequestHandler):
+ def do_POST(self):
+ self._respond()
+
+ def do_GET(self):
+ self._respond()
+
+ def _respond(self):
+ length = int(self.headers.get("Content-Length", "0"))
+ self.rfile.read(length)
+ requests.append(
+ (self.command, self.path, {key.lower(): value for key, value in self.headers.items()})
+ )
+ if redirect_to:
+ self.send_response(302)
+ self.send_header("Location", redirect_to)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ return
+ body = json.dumps(payload if payload is not None else {"output_text": reply}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_args):
+ pass
+
+ server = stdlib_http.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ running.append((server, thread))
+ return f"http://127.0.0.1:{server.server_port}", requests
+
+ yield start
+
+ for server, thread in reversed(running):
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
+def _enable_proxy(monkeypatch, proxy_url):
+ monkeypatch.setenv("HTTP_PROXY", proxy_url)
+ monkeypatch.setenv("http_proxy", proxy_url)
+ monkeypatch.delenv("NO_PROXY", raising=False)
+ monkeypatch.delenv("no_proxy", raising=False)
+ monkeypatch.setattr(
+ http, "_opener", urllib.request.build_opener(http._StripAuthOnCrossOriginRedirect)
+ )
+
+
+ "key,client,route,host",
+ [
+ ("OPENAI_BASE_URL", providers.OpenAIClient, "/v1/responses", "127.0.0.1"),
+ ("OPENAI_BASE_URL", providers.OpenAIClient, "/v1/responses", "localhost"),
+ ("XAI_BASE_URL", providers.XAIClient, "/v1/responses", "127.0.0.1"),
+ ("OPENROUTER_BASE_URL", providers.OpenRouterClient, "/v1/chat/completions", "127.0.0.1"),
+ ],
+)
+def test_loopback_provider_request_bypasses_proxy(key, client, route, host, monkeypatch, serve):
+ endpoint, endpoint_requests = serve()
+ proxy, proxy_requests = serve(reply="proxy")
+ _enable_proxy(monkeypatch, proxy)
+ monkeypatch.setenv(key, endpoint.replace("127.0.0.1", host, 1) + "/v1")
+
+ assert client("dummy-key").generate_text("model", "prompt") == "direct"
+ assert proxy_requests == []
+ assert len(endpoint_requests) == 1
+ method, path, headers = endpoint_requests[0]
+ assert (method, path) == ("POST", route)
+ assert headers["authorization"] == "Bearer dummy-key"
+
+
+def test_loopback_redirect_strips_bearer_and_stays_off_proxy(monkeypatch, serve):
+ target, target_requests = serve()
+ source, source_requests = serve(redirect_to=target + "/result")
+ proxy, proxy_requests = serve(reply="proxy")
+ _enable_proxy(monkeypatch, proxy)
+ monkeypatch.setenv("OPENAI_BASE_URL", source + "/v1")
+
+ assert providers.OpenAIClient("dummy-key").generate_text("model", "prompt") == "direct"
+ assert proxy_requests == []
+ assert len(source_requests) == 1
+ assert source_requests[0][2]["authorization"] == "Bearer dummy-key"
+ assert len(target_requests) == 1
+ assert target_requests[0][1] == "/result"
+ assert "authorization" not in target_requests[0][2]
+
+
+def test_loopback_provider_request_does_not_change_other_proxy_routes(monkeypatch, serve):
+ endpoint, endpoint_requests = serve()
+ proxy, proxy_requests = serve(reply="proxy")
+ _enable_proxy(monkeypatch, proxy)
+ monkeypatch.setenv("OPENAI_BASE_URL", endpoint + "/v1")
+
+ assert providers.OpenAIClient("dummy-key").generate_text("model", "prompt") == "direct"
+ assert proxy_requests == []
+ assert http.get(endpoint + "/status", retries=1) == {"output_text": "proxy"}
+ assert len(endpoint_requests) == 1
+ assert len(proxy_requests) == 1
+ assert "authorization" not in proxy_requests[0][2]
+
+
+def test_xai_x_search_loopback_override_bypasses_proxy(monkeypatch, serve):
+ endpoint, endpoint_requests = serve()
+ proxy, proxy_requests = serve(reply="proxy")
+ _enable_proxy(monkeypatch, proxy)
+ monkeypatch.setenv("XAI_BASE_URL", endpoint + "/v1")
+
+ response = xai_x.search_x(
+ "dummy-key", "model", "topic", "2026-09-01", "2026-10-01", depth="quick"
+ )
+
+ assert response == {"output_text": "direct"}
+ assert proxy_requests == []
+ assert len(endpoint_requests) == 1
+ assert endpoint_requests[0][0:2] == ("POST", "/v1/responses")
+ assert endpoint_requests[0][2]["authorization"] == "Bearer dummy-key"
+
+
+def test_openrouter_sonar_loopback_override_bypasses_proxy(monkeypatch, serve):
+ endpoint, endpoint_requests = serve(
+ payload={"choices": [{"message": {"content": "direct"}}]}
+ )
+ proxy, proxy_requests = serve(
+ payload={"choices": [{"message": {"content": "proxy"}}]}
+ )
+ _enable_proxy(monkeypatch, proxy)
+ monkeypatch.setenv("OPENROUTER_BASE_URL", endpoint + "/v1")
+
+ items, _ = perplexity._openrouter_sonar_search(
+ "topic", ("2026-09-01", "2026-10-01"), "dummy-key", deep=False
+ )
+
+ assert items[0]["snippet"] == "direct"
+ assert proxy_requests == []
+ assert len(endpoint_requests) == 1
+ assert endpoint_requests[0][0:2] == ("POST", "/v1/chat/completions")
+ assert endpoint_requests[0][2]["authorization"] == "Bearer dummy-key"
diff --git a/tests/test_providers_v3.py b/tests/test_providers_v3.py
index ac760350..cc728e57 100644
--- a/tests/test_providers_v3.py
+++ b/tests/test_providers_v3.py
@@ -174,6 +174,20 @@ class ResolveEndpointTests(unittest.TestCase):
self._resolve("https://example.test/v1/responses"),
)
+ def test_full_endpoint_query_string_is_preserved(self):
+ endpoint = "https://example.test/v1/responses?tenant=acme"
+ self.assertEqual(endpoint, self._resolve(endpoint))
+
+ def test_custom_gateway_route_is_preserved(self):
+ endpoint = "https://example.test/proxy?tenant=acme"
+ self.assertEqual(endpoint, self._resolve(endpoint))
+
+ def test_api_root_query_string_stays_after_appended_path(self):
+ self.assertEqual(
+ "https://example.test/v1/responses?tenant=acme",
+ self._resolve("https://example.test/v1?tenant=acme"),
+ )
+
def test_openrouter_uses_chat_completions_path(self):
self.assertEqual(
"https://example.test/api/v1/chat/completions",